commit stringlengths 40 40 | subject stringlengths 1 1.49k | old_file stringlengths 4 311 | new_file stringlengths 4 311 | new_contents stringlengths 1 29.8k | old_contents stringlengths 0 9.9k | lang stringclasses 3 values | proba float64 0 1 |
|---|---|---|---|---|---|---|---|
5de02410d6a1b78b8ac5f2c6fed6d119a76565a5 | Remove print statement | agenda/events/templatetags/calendar.py | agenda/events/templatetags/calendar.py | #
# Copyright (C) 2009 Novopia Solutions Inc.
#
# Author: Pierre-Luc Beaudoin <pierre-luc.beaudoin@nov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# -----
# This file is derived from http://www.djangosnippets.org/snippets/129/
# A code snipped that comes without licence information
from datetime import date, timedelta
from django import template
from agenda.events.models import Event
from django.db.models import Q
register = template.Library()
def get_last_day_of_month(year, month):
if (month == 12):
year += 1
month = 1
else:
month += 1
return date(year, month, 1) - timedelta(1)
def month_cal(year, month, region=None):
first_day_of_month = date(year, month, 1)
last_day_of_month = get_last_day_of_month(year, month)
first_day_of_calendar = (first_day_of_month
- timedelta(first_day_of_month.weekday()+1))
last_day_of_calendar = (last_day_of_month
+ timedelta(7 - last_day_of_month.weekday()))
# print last_day_of_month.isoweekday()
today = date.today()
# Filter local events for given region, include national and
# international events
if region is not None:
q = Q(city__region=region)
else:
q = Q()
event_list = (Event.objects
.filter(start_time__gte=first_day_of_calendar)
.filter(end_time__lte=last_day_of_calendar)
.filter(moderated=True)
.filter(q))
month_cal = []
week = []
week_headers = []
i = 0
day = first_day_of_calendar
while day <= last_day_of_calendar:
if i < 7:
week_headers.append(day)
cal_day = {}
cal_day['day'] = day
cal_day['event'] = False
day_events = []
for event in event_list:
if day >= event.start_time.date() and day <= event.end_time.date():
day_events.append(event)
cal_day['events'] = day_events
cal_day['in_month'] = (day.month == month)
cal_day['is_past'] = (day < today)
cal_day['is_today'] = (day == today)
week.append(cal_day)
if day.weekday() == 5:
month_cal.append(week)
week = []
i += 1
day += timedelta(1)
return {'calendar': month_cal, 'headers': week_headers, 'region': region}
register.inclusion_tag('calendar.html')(month_cal)
| #
# Copyright (C) 2009 Novopia Solutions Inc.
#
# Author: Pierre-Luc Beaudoin <pierre-luc.beaudoin@nov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# -----
# This file is derived from http://www.djangosnippets.org/snippets/129/
# A code snipped that comes without licence information
from datetime import date, timedelta
from django import template
from agenda.events.models import Event
from django.db.models import Q
register = template.Library()
def get_last_day_of_month(year, month):
if (month == 12):
year += 1
month = 1
else:
month += 1
return date(year, month, 1) - timedelta(1)
def month_cal(year, month, region=None):
first_day_of_month = date(year, month, 1)
last_day_of_month = get_last_day_of_month(year, month)
first_day_of_calendar = (first_day_of_month
- timedelta(first_day_of_month.weekday()+1))
last_day_of_calendar = (last_day_of_month
+ timedelta(7 - last_day_of_month.weekday()))
print last_day_of_month.isoweekday()
today = date.today()
# Filter local events for given region, include national and
# international events
if region is not None:
q = Q(city__region=region)
else:
q = Q()
event_list = (Event.objects
.filter(start_time__gte=first_day_of_calendar)
.filter(end_time__lte=last_day_of_calendar)
.filter(moderated=True)
.filter(q))
month_cal = []
week = []
week_headers = []
i = 0
day = first_day_of_calendar
while day <= last_day_of_calendar:
if i < 7:
week_headers.append(day)
cal_day = {}
cal_day['day'] = day
cal_day['event'] = False
day_events = []
for event in event_list:
if day >= event.start_time.date() and day <= event.end_time.date():
day_events.append(event)
cal_day['events'] = day_events
cal_day['in_month'] = (day.month == month)
cal_day['is_past'] = (day < today)
cal_day['is_today'] = (day == today)
week.append(cal_day)
if day.weekday() == 5:
month_cal.append(week)
week = []
i += 1
day += timedelta(1)
return {'calendar': month_cal, 'headers': week_headers, 'region': region}
register.inclusion_tag('calendar.html')(month_cal)
| Python | 0.007015 |
7847d22f95f44792e35108af24267161411c5bf1 | Remove settings override with no effect | analytical/tests/test_tag_gosquared.py | analytical/tests/test_tag_gosquared.py | """
Tests for the GoSquared template tags and filters.
"""
from django.contrib.auth.models import User, AnonymousUser
from django.http import HttpRequest
from django.template import Context
from django.test.utils import override_settings
from analytical.templatetags.gosquared import GoSquaredNode
from analytical.tests.utils import TagTestCase
from analytical.utils import AnalyticalException
@override_settings(GOSQUARED_SITE_TOKEN='ABC-123456-D')
class GoSquaredTagTestCase(TagTestCase):
"""
Tests for the ``gosquared`` template tag.
"""
def test_tag(self):
r = self.render_tag('gosquared', 'gosquared')
self.assertTrue('GoSquared.acct = "ABC-123456-D";' in r, r)
def test_node(self):
r = GoSquaredNode().render(Context({}))
self.assertTrue('GoSquared.acct = "ABC-123456-D";' in r, r)
@override_settings(GOSQUARED_SITE_TOKEN=None)
def test_no_token(self):
self.assertRaises(AnalyticalException, GoSquaredNode)
@override_settings(GOSQUARED_SITE_TOKEN='this is not a token')
def test_wrong_token(self):
self.assertRaises(AnalyticalException, GoSquaredNode)
@override_settings(ANALYTICAL_AUTO_IDENTIFY=True)
def test_auto_identify(self):
r = GoSquaredNode().render(Context({'user': User(username='test',
first_name='Test', last_name='User')}))
self.assertTrue('GoSquared.UserName = "Test User";' in r, r)
@override_settings(ANALYTICAL_AUTO_IDENTIFY=True)
def test_manual_identify(self):
r = GoSquaredNode().render(Context({
'user': User(username='test', first_name='Test', last_name='User'),
'gosquared_identity': 'test_identity',
}))
self.assertTrue('GoSquared.UserName = "test_identity";' in r, r)
@override_settings(ANALYTICAL_AUTO_IDENTIFY=True)
def test_identify_anonymous_user(self):
r = GoSquaredNode().render(Context({'user': AnonymousUser()}))
self.assertFalse('GoSquared.UserName = ' in r, r)
@override_settings(ANALYTICAL_INTERNAL_IPS=['1.1.1.1'])
def test_render_internal_ip(self):
req = HttpRequest()
req.META['REMOTE_ADDR'] = '1.1.1.1'
context = Context({'request': req})
r = GoSquaredNode().render(context)
self.assertTrue(r.startswith(
'<!-- GoSquared disabled on internal IP address'), r)
self.assertTrue(r.endswith('-->'), r)
| """
Tests for the GoSquared template tags and filters.
"""
from django.contrib.auth.models import User, AnonymousUser
from django.http import HttpRequest
from django.template import Context
from django.test.utils import override_settings
from analytical.templatetags.gosquared import GoSquaredNode
from analytical.tests.utils import TagTestCase
from analytical.utils import AnalyticalException
@override_settings(GOSQUARED_SITE_TOKEN='ABC-123456-D')
class GoSquaredTagTestCase(TagTestCase):
"""
Tests for the ``gosquared`` template tag.
"""
def test_tag(self):
r = self.render_tag('gosquared', 'gosquared')
self.assertTrue('GoSquared.acct = "ABC-123456-D";' in r, r)
def test_node(self):
r = GoSquaredNode().render(Context({}))
self.assertTrue('GoSquared.acct = "ABC-123456-D";' in r, r)
@override_settings(GOSQUARED_SITE_TOKEN=None)
def test_no_token(self):
self.assertRaises(AnalyticalException, GoSquaredNode)
@override_settings(GOSQUARED_SITE_TOKEN='this is not a token')
def test_wrong_token(self):
self.assertRaises(AnalyticalException, GoSquaredNode)
@override_settings(ANALYTICAL_AUTO_IDENTIFY=True)
def test_auto_identify(self):
r = GoSquaredNode().render(Context({'user': User(username='test',
first_name='Test', last_name='User')}))
self.assertTrue('GoSquared.UserName = "Test User";' in r, r)
@override_settings(ANALYTICAL_AUTO_IDENTIFY=True)
def test_manual_identify(self):
r = GoSquaredNode().render(Context({
'user': User(username='test', first_name='Test', last_name='User'),
'gosquared_identity': 'test_identity',
}))
self.assertTrue('GoSquared.UserName = "test_identity";' in r, r)
@override_settings(ANALYTICAL_AUTO_IDENTIFY=True, USER_ID=None)
def test_identify_anonymous_user(self):
r = GoSquaredNode().render(Context({'user': AnonymousUser()}))
self.assertFalse('GoSquared.UserName = ' in r, r)
@override_settings(ANALYTICAL_INTERNAL_IPS=['1.1.1.1'])
def test_render_internal_ip(self):
req = HttpRequest()
req.META['REMOTE_ADDR'] = '1.1.1.1'
context = Context({'request': req})
r = GoSquaredNode().render(context)
self.assertTrue(r.startswith(
'<!-- GoSquared disabled on internal IP address'), r)
self.assertTrue(r.endswith('-->'), r)
| Python | 0 |
8713f44fbd35f012ac7e01a64cffcfdf846fee9f | Remove a relative import that escaped test.test_importlib. | Lib/test/test_importlib/__init__.py | Lib/test/test_importlib/__init__.py | import os
import sys
from test import support
import unittest
def test_suite(package=__package__, directory=os.path.dirname(__file__)):
suite = unittest.TestSuite()
for name in os.listdir(directory):
if name.startswith(('.', '__')):
continue
path = os.path.join(directory, name)
if (os.path.isfile(path) and name.startswith('test_') and
name.endswith('.py')):
submodule_name = os.path.splitext(name)[0]
module_name = "{0}.{1}".format(package, submodule_name)
__import__(module_name, level=0)
module_tests = unittest.findTestCases(sys.modules[module_name])
suite.addTest(module_tests)
elif os.path.isdir(path):
package_name = "{0}.{1}".format(package, name)
__import__(package_name, level=0)
package_tests = getattr(sys.modules[package_name], 'test_suite')()
suite.addTest(package_tests)
else:
continue
return suite
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
support.run_unittest(test_loader.discover(start_dir, top_level_dir=top_dir))
| import os
import sys
from .. import support
import unittest
def test_suite(package=__package__, directory=os.path.dirname(__file__)):
suite = unittest.TestSuite()
for name in os.listdir(directory):
if name.startswith(('.', '__')):
continue
path = os.path.join(directory, name)
if (os.path.isfile(path) and name.startswith('test_') and
name.endswith('.py')):
submodule_name = os.path.splitext(name)[0]
module_name = "{0}.{1}".format(package, submodule_name)
__import__(module_name, level=0)
module_tests = unittest.findTestCases(sys.modules[module_name])
suite.addTest(module_tests)
elif os.path.isdir(path):
package_name = "{0}.{1}".format(package, name)
__import__(package_name, level=0)
package_tests = getattr(sys.modules[package_name], 'test_suite')()
suite.addTest(package_tests)
else:
continue
return suite
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
support.run_unittest(test_loader.discover(start_dir, top_level_dir=top_dir))
| Python | 0 |
4d597a8e71c0020b0f1d36e1cca64b5a353b0643 | modify version | Abe/version.py | Abe/version.py | __version__ = '0.88'
| __version__ = '0.8pre'
| Python | 0 |
8c7abe561cd95331fef17b4fd1c7fe67386826a2 | change the input url | AddDataTest.py | AddDataTest.py | __author__ = 'chuqiao'
import EventsPortal
from datetime import datetime
import logging
def logger():
"""
Function that initialises logging system
"""
global logger
# create logger with 'syncsolr'
logger = logging.getLogger('adddata')
logger.setLevel(logging.DEBUG)
# specifies the lowest severity that will be dispatched to the appropriate destination
# create file handler which logs even debug messages
fh = logging.FileHandler('adddata.log')
# fh.setLevel(logging.WARN)
# create console handler and set level to debug
ch = logging.StreamHandler()
# StreamHandler instances send messages to streams
# ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(ch)
logger.addHandler(fh)
# EventsPortal.addDataToSolrFromUrl("http://www.elixir-europe.org:8080/events", "http://www.elixir-europe.org:8080/events");
logger()
logger.info('start at %s' % datetime.now())
# EventsPortal.addDataToSolrFromUrl("http://bioevents-portal.org/eventsfull/test?state=published&field_type_tid=All", "http://bioevents-portal.org/events","http://139.162.217.53:8983/solr/eventsportal");
# EventsPortal.addDataToSolrFromUrl("http://bioevents-portal.org/eventsfull", "http://bioevents-portal.org/events","http://139.162.217.53:8983/solr/eventsportal");
# EventsPortal.addDataToSolrFromUrl("http://bioevents-portal.org/eventsfull/upcoming?state=published&field_type_tid=All", "http://bioevents-portal.org/events","http://139.162.217.53:8983/solr/eventsportal");
# EventsPortal.addDataToSolrFromUrl("http://bioevents-portal.org/eventsfull", "http://bioevents-portal.org/events","http://localhost:8983/solr/event_portal");
EventsPortal.addDataToSolrFromUrl("http://bioevents-portal.org/eventsfull/test?state=published&field_type_tid=All", "http://bioevents-portal.org/events","139.162.217.53:8983/solr/eventsportal")
logger.info('finish at %s' % datetime.now())
if __name__ == '__main__':
EventsPortal.addDataToSolrFromUrl("http://bioevents-portal.org/eventsfull/test?state=published&field_type_tid=All", "http://bioevents-portal.org/events","139.162.217.53:8983/solr/eventsportal")
| __author__ = 'chuqiao'
import EventsPortal
from datetime import datetime
import logging
def logger():
"""
Function that initialises logging system
"""
global logger
# create logger with 'syncsolr'
logger = logging.getLogger('adddata')
logger.setLevel(logging.DEBUG)
# specifies the lowest severity that will be dispatched to the appropriate destination
# create file handler which logs even debug messages
fh = logging.FileHandler('adddata.log')
# fh.setLevel(logging.WARN)
# create console handler and set level to debug
ch = logging.StreamHandler()
# StreamHandler instances send messages to streams
# ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(ch)
logger.addHandler(fh)
# EventsPortal.addDataToSolrFromUrl("http://www.elixir-europe.org:8080/events", "http://www.elixir-europe.org:8080/events");
logger()
logger.info('start at %s' % datetime.now())
# EventsPortal.addDataToSolrFromUrl("http://bioevents-portal.org/eventsfull/test?state=published&field_type_tid=All", "http://bioevents-portal.org/events","http://139.162.217.53:8983/solr/eventsportal");
# EventsPortal.addDataToSolrFromUrl("http://bioevents-portal.org/eventsfull", "http://bioevents-portal.org/events","http://139.162.217.53:8983/solr/eventsportal");
# EventsPortal.addDataToSolrFromUrl("http://bioevents-portal.org/eventsfull/upcoming?state=published&field_type_tid=All", "http://bioevents-portal.org/events","http://139.162.217.53:8983/solr/eventsportal");
# EventsPortal.addDataToSolrFromUrl("http://bioevents-portal.org/eventsfull", "http://bioevents-portal.org/events","http://localhost:8983/solr/event_portal");
EventsPortal.addDataToSolrFromUrl("http://bioevents-portal.org/eventsfull/test?state=published&field_type_tid=All", "http://bioevents-portal.org/events","localhost:8983/solr/event_portal")
logger.info('finish at %s' % datetime.now())
if __name__ == '__main__':
EventsPortal.addDataToSolrFromUrl("http://bioevents-portal.org/eventsfull/test?state=published&field_type_tid=All", "http://bioevents-portal.org/events","localhost:8983/solr/event_portal")
| Python | 0.999997 |
d98cdb7eae40b5bb11b5d1fc0eacc35ef6bf310d | Order filter for report page | wye/reports/views.py | wye/reports/views.py | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from wye.organisations.models import Organisation
from wye.workshops.models import Workshop
from wye.profiles.models import Profile
import datetime
from wye.base.constants import WorkshopStatus
@login_required
def index(request, days):
print(request.user.is_staff)
if not request.user.is_staff:
return ""
d = datetime.datetime.now() - datetime.timedelta(days=int(days))
organisations = Organisation.objects.filter(
active=True).filter(created_at__gte=d)
workshops = Workshop.objects.filter(
is_active=True).filter(
expected_date__gte=d).filter(
expected_date__lt=datetime.datetime.now()).filter(
status__in=[WorkshopStatus.COMPLETED,
WorkshopStatus.FEEDBACK_PENDING]).order_by('expected_date')
profiles = Profile.objects.filter(user__date_joined__gte=d)
no_of_participants = sum([w.no_of_participants for w in workshops])
template_name = 'reports/index.html'
context_dict = {}
context_dict['organisations'] = organisations
context_dict['workshops'] = workshops
context_dict['profiles'] = profiles
context_dict['no_of_participants'] = no_of_participants
context_dict['date'] = d
workshops = Workshop.objects.filter(
is_active=True)
return render(request, template_name, context_dict)
| from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from wye.organisations.models import Organisation
from wye.workshops.models import Workshop
from wye.profiles.models import Profile
import datetime
from wye.base.constants import WorkshopStatus
@login_required
def index(request, days):
print(request.user.is_staff)
if not request.user.is_staff:
return ""
d = datetime.datetime.now() - datetime.timedelta(days=int(days))
organisations = Organisation.objects.filter(
active=True).filter(created_at__gte=d)
workshops = Workshop.objects.filter(
is_active=True).filter(
expected_date__gte=d).filter(
expected_date__lt=datetime.datetime.now()).filter(
status__in=[WorkshopStatus.COMPLETED,
WorkshopStatus.FEEDBACK_PENDING])
profiles = Profile.objects.filter(user__date_joined__gte=d)
no_of_participants = sum([w.no_of_participants for w in workshops])
template_name = 'reports/index.html'
context_dict = {}
context_dict['organisations'] = organisations
context_dict['workshops'] = workshops
context_dict['profiles'] = profiles
context_dict['no_of_participants'] = no_of_participants
context_dict['date'] = d
workshops = Workshop.objects.filter(
is_active=True)
return render(request, template_name, context_dict)
| Python | 0 |
0403ba1bcbc1089f42cdb0ed7a37439363f4e963 | Fix bug | reid/utils/data/dataset.py | reid/utils/data/dataset.py | from __future__ import print_function
import os.path as osp
import numpy as np
from ..serialization import read_json
def _pluck(identities, indices, relabel=False):
ret = []
for index, pid in enumerate(indices):
pid_images = identities[pid]
for camid, cam_images in enumerate(pid_images):
for fname in cam_images:
name = osp.splitext(fname)[0]
x, y, _ = map(int, name.split('_'))
assert pid == x and camid == y
if relabel:
ret.append((fname, index, camid))
else:
ret.append((fname, pid, camid))
return ret
class Dataset(object):
def __init__(self, root, split_id=0):
self.root = root
self.split_id = split_id
self.meta = None
self.split = None
self.train, self.val, self.trainval = [], [], []
self.query, self.gallery = [], []
self.num_train_ids, self.num_val_ids, self.num_trainval_ids = 0, 0, 0
@property
def images_dir(self):
return osp.join(self.root, 'images')
def load(self, num_val=0.3, verbose=True):
splits = read_json(osp.join(self.root, 'splits.json'))
if self.split_id >= len(splits):
raise ValueError("split_id exceeds total splits {}"
.format(len(splits)))
self.split = splits[self.split_id]
# Randomly split train / val
trainval_pids = np.asarray(self.split['trainval'])
np.random.shuffle(trainval_pids)
num = len(trainval_pids)
if isinstance(num_val, float):
num_val = int(round(num * num_val))
if num_val >= num or num_val < 0:
raise ValueError("num_val exceeds total identities {}"
.format(num))
train_pids = sorted(trainval_pids[:-num_val])
val_pids = sorted(trainval_pids[-num_val:])
self.meta = read_json(osp.join(self.root, 'meta.json'))
identities = self.meta['identities']
self.train = _pluck(identities, train_pids, relabel=True)
self.val = _pluck(identities, val_pids, relabel=True)
self.trainval = _pluck(identities, trainval_pids, relabel=True)
self.query = _pluck(identities, self.split['query'])
self.gallery = _pluck(identities, self.split['gallery'])
self.num_train_ids = len(train_pids)
self.num_val_ids = len(val_pids)
self.num_trainval_ids = len(trainval_pids)
if verbose:
print(self.__class__.__name__, "dataset loaded")
print(" subset | # ids | # images")
print(" ---------------------------")
print(" train | {:5d} | {:8d}"
.format(self.num_train_ids, len(self.train)))
print(" val | {:5d} | {:8d}"
.format(self.num_val_ids, len(self.val)))
print(" trainval | {:5d} | {:8d}"
.format(self.num_trainval_ids, len(self.trainval)))
print(" query | {:5d} | {:8d}"
.format(len(self.split['query']), len(self.query)))
print(" gallery | {:5d} | {:8d}"
.format(len(self.split['gallery']), len(self.gallery)))
def _check_integrity(self):
return osp.isdir(osp.join(self.root, 'images')) and \
osp.isfile(osp.join(self.root, 'meta.json')) and \
osp.isfile(osp.join(self.root, 'splits.json'))
| from __future__ import print_function
import os.path as osp
import numpy as np
from ..serialization import read_json
def _pluck(identities, indices, relabel=False):
ret = []
for index, pid in enumerate(indices):
pid_images = identities[pid]
for camid, cam_images in enumerate(pid_images):
for fname in cam_images:
name = osp.splitext(fname)[0]
x, y, _ = map(int, name.split('_'))
assert pid == x and camid == y
if relabel:
ret.append((fname, index, camid))
else:
ret.append((fname, pid, camid))
return ret
class Dataset(object):
def __init__(self, root, split_id=0):
self.root = root
self.split_id = split_id
self.meta = None
self.split = None
self.train, self.val, self.trainval = [], [], []
self.query, self.gallery = [], []
self.num_train_ids, self.num_val_ids, self.num_trainval_ids = 0, 0, 0
@property
def images_dir(self):
return osp.join(self.root, 'images')
def load(self, num_val=0.3, verbose=True):
splits = read_json(osp.join(self.root, 'splits.json'))
if self.split_id >= len(splits):
raise ValueError("split_id exceeds total splits {}"
.format(len(splits)))
self.split = splits[self.split_id]
# Randomly split train / val
trainval_pids = np.asarray(self.split['trainval'])
np.random.shuffle(trainval_pids)
num = len(trainval_pids)
if isinstance(num_val, float):
num_val = int(round(num * num_val))
if num_val >= num or num_val < 0:
raise ValueError("num_val exceeds total identities {}"
.format(num))
train_pids = sorted(trainval_pids[:-num_val])
val_pids = sorted(trainval_pids[-num_val:])
self.meta = read_json(osp.join(self.root, 'meta.json'))
identities = self.meta['identities']
self.train = _pluck(identities, train_pids, relabel=True)
self.val = _pluck(identities, val_pids, relabel=True)
self.trainval = _pluck(identities, trainval_pids, relabel=True)
self.query = _pluck(identities, self.split['query'])
self.gallery = _pluck(identities, self.split['gallery'])
self.num_train_ids = len(train_pids)
self.num_val_ids = len(val_pids)
self.num_trainval_ids = len(trainval_pids)
if verbose:
print(self.__class__.__name__, "dataset loaded")
print(" subset | # ids | # images")
print(" ---------------------------")
print(" train | {:5d} | {:8d}"
.format(self.num_train_ids, len(self.train)))
print(" val | {:5d} | {:8d}"
.format(self.num_val_ids, len(self.val)))
print(" trainval | {:5d} | {:8d}"
.format(self.num_trainval_ids, len(self.val)))
print(" query | {:5d} | {:8d}"
.format(len(self.split['query']), len(self.query)))
print(" gallery | {:5d} | {:8d}"
.format(len(self.split['gallery']), len(self.gallery)))
def _check_integrity(self):
return osp.isdir(osp.join(self.root, 'images')) and \
osp.isfile(osp.join(self.root, 'meta.json')) and \
osp.isfile(osp.join(self.root, 'splits.json'))
| Python | 0.000001 |
af669e8ab8a502505389adf63e0d5216765fdba4 | fix exclude events | viradacultural_social_api/views.py | viradacultural_social_api/views.py | from rest_framework import viewsets
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import FbUser, Event
from .serializer import FbUserSerializer
from rest_framework import permissions
import facebook
class MinhaViradaView(APIView):
permission_classes = (permissions.AllowAny,)
def get(self, request):
fb_user_uid = request.query_params.get('uid')
if fb_user_uid:
try:
fb_user = FbUser.objects.get(uid=fb_user_uid)
serializer = FbUserSerializer(fb_user)
return Response(serializer.data)
except FbUser.DoesNotExist:
return Response('')
else:
return Response('')
def post(self, request):
fb_user_uid = request.data.get('uid')
data = request.data
data['fb_user_uid'] = fb_user_uid
# import ipdb;ipdb.set_trace()
if fb_user_uid:
fb_user, _ = FbUser.objects.get_or_create(uid=fb_user_uid)
serializer = FbUserSerializer(fb_user, data=data)
if serializer.is_valid():
serializer.save()
events = request.data.get('events')
events_objects = []
for event in events:
events_objects.append(Event.objects.get_or_create(event_id=event, fb_user=fb_user))
Event.objects.exclude(event_id__in=events).delete()
return Response('{status: success}')
else:
return Response('{status: fail}')
# class FriendsOnEventViewSet(APIView):
# """
# API endpoint that allows users to be viewed or edited.
# """
# queryset = FbUser.objects.all()
# serializer_class = UserSerializer
#
# def get(self, request, *args, **kwargs):
# fb_user_id = request.query_params('uid')
# oauth_access_token = request.query_params('fbtoken')
# graph = facebook.GraphAPI(oauth_access_token)
# profile = graph.get_object("me")
# friends = graph.get_connections("me", "friends")
#
#
# class FriendsPositionsView(viewsets.ModelViewSet):
# """
# API endpoint that allows users to be viewed or edited.
# """
# queryset = FbUser.objects.all()
# serializer_class = UserSerializer
#
# def get(self, request, *args, **kwargs):
# fb_user_id = request.query_params('uid')
# oauth_access_token = request.query_params('fbtoken')
# graph = facebook.GraphAPI(oauth_access_token)
# profile = graph.get_object("me")
# friends = graph.get_connections("me", "friends")
# from django.contrib.gis.geos import fromstr
# pnt = fromstr('POINT(-90.5 29.5)', srid=4326)
| from rest_framework import viewsets
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import FbUser, Event
from .serializer import FbUserSerializer
from rest_framework import permissions
import facebook
class MinhaViradaView(APIView):
permission_classes = (permissions.AllowAny,)
def get(self, request):
fb_user_uid = request.query_params.get('uid')
if fb_user_uid:
try:
fb_user = FbUser.objects.get(uid=fb_user_uid)
serializer = FbUserSerializer(fb_user)
return Response(serializer.data)
except FbUser.DoesNotExist:
return Response('{}')
else:
return Response('{}')
def post(self, request):
fb_user_uid = request.data.get('uid')
data = request.data
data['fb_user_uid'] = fb_user_uid
if fb_user_uid:
fb_user, _ = FbUser.objects.get_or_create(uid=fb_user_uid)
serializer = FbUserSerializer(fb_user, data=data)
if serializer.is_valid():
serializer.save()
events = request.data.get('events')
for event in events:
Event.objects.get_or_create(event_id=event, fb_user=fb_user)
return Response('{status: success}')
else:
return Response('{status: fail}')
# class FriendsOnEventViewSet(APIView):
# """
# API endpoint that allows users to be viewed or edited.
# """
# queryset = FbUser.objects.all()
# serializer_class = UserSerializer
#
# def get(self, request, *args, **kwargs):
# fb_user_id = request.query_params('uid')
# oauth_access_token = request.query_params('fbtoken')
# graph = facebook.GraphAPI(oauth_access_token)
# profile = graph.get_object("me")
# friends = graph.get_connections("me", "friends")
#
#
# class FriendsPositionsView(viewsets.ModelViewSet):
# """
# API endpoint that allows users to be viewed or edited.
# """
# queryset = FbUser.objects.all()
# serializer_class = UserSerializer
#
# def get(self, request, *args, **kwargs):
# fb_user_id = request.query_params('uid')
# oauth_access_token = request.query_params('fbtoken')
# graph = facebook.GraphAPI(oauth_access_token)
# profile = graph.get_object("me")
# friends = graph.get_connections("me", "friends")
# from django.contrib.gis.geos import fromstr
# pnt = fromstr('POINT(-90.5 29.5)', srid=4326)
| Python | 0.000024 |
10f7938e37180c0cb3b701223cf6d1855e7d8f93 | Drop python_2_unicode_compatible for Settings, fix docs build on rtfd | watchdog_kj_kultura/main/models.py | watchdog_kj_kultura/main/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from model_utils.models import TimeStampedModel
from tinymce.models import HTMLField
from django.contrib.sites.models import Site
class SettingsQuerySet(models.QuerySet):
pass
class Settings(TimeStampedModel):
site = models.OneToOneField(Site, verbose_name=_("Site"))
home_content = HTMLField(verbose_name=_("Content of home page"))
objects = SettingsQuerySet.as_manager()
class Meta:
verbose_name = _("Settings")
verbose_name_plural = _("Settings")
ordering = ['created', ]
| from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from model_utils.models import TimeStampedModel
from tinymce.models import HTMLField
from django.contrib.sites.models import Site
class SettingsQuerySet(models.QuerySet):
pass
@python_2_unicode_compatible
class Settings(TimeStampedModel):
site = models.OneToOneField(Site, verbose_name=_("Site"))
home_content = HTMLField(verbose_name=_("Content of home page"))
objects = SettingsQuerySet.as_manager()
class Meta:
verbose_name = _("Settings")
verbose_name_plural = _("Settings")
ordering = ['created', ]
| Python | 0 |
5f8580e9d28d08e13f40692a2247f41ea8c5b4b9 | Remove extra newline. | tests/test_additional_io.py | tests/test_additional_io.py | __author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>"
__date__ = "$Jul 28, 2014 11:50:37 EDT$"
import nanshe.nanshe.additional_io
class TestAdditionalIO(object):
num_files = 10
def setup(self):
import tempfile
self.temp_dir = tempfile.mkdtemp()
self.temp_files = []
for i in xrange(TestAdditionalIO.num_files):
self.temp_files.append(tempfile.NamedTemporaryFile(suffix = ".tif", dir = self.temp_dir))
self.temp_files.sort(cmp = lambda a, b: 2*(a.name > b.name) - 1)
def test_expand_pathname_list(self):
import itertools
matched_filenames = nanshe.nanshe.additional_io.expand_pathname_list(self.temp_dir + "/*.tif")
matched_filenames.sort(cmp = lambda a, b: 2*(a > b) - 1)
assert(len(matched_filenames) == len(self.temp_files))
for each_l, each_f in itertools.izip(matched_filenames, self.temp_files):
assert(each_l == each_f.name)
def teardown(self):
import shutil
for i in xrange(len(self.temp_files)):
self.temp_files[i].close()
self.temp_files = []
shutil.rmtree(self.temp_dir)
self.temp_dir = ""
| __author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>"
__date__ = "$Jul 28, 2014 11:50:37 EDT$"
import nanshe.nanshe.additional_io
class TestAdditionalIO(object):
num_files = 10
def setup(self):
import tempfile
self.temp_dir = tempfile.mkdtemp()
self.temp_files = []
for i in xrange(TestAdditionalIO.num_files):
self.temp_files.append(tempfile.NamedTemporaryFile(suffix = ".tif", dir = self.temp_dir))
self.temp_files.sort(cmp = lambda a, b: 2*(a.name > b.name) - 1)
def test_expand_pathname_list(self):
import itertools
matched_filenames = nanshe.nanshe.additional_io.expand_pathname_list(self.temp_dir + "/*.tif")
matched_filenames.sort(cmp = lambda a, b: 2*(a > b) - 1)
assert(len(matched_filenames) == len(self.temp_files))
for each_l, each_f in itertools.izip(matched_filenames, self.temp_files):
assert(each_l == each_f.name)
def teardown(self):
import shutil
for i in xrange(len(self.temp_files)):
self.temp_files[i].close()
self.temp_files = []
shutil.rmtree(self.temp_dir)
self.temp_dir = ""
| Python | 0 |
db06f101a07f0e122c35e8b662ed4fe6a26c4811 | Add SkipTest to test_content_disposition | tests/test_awss3_storage.py | tests/test_awss3_storage.py | import os
import uuid
import mock
import requests
from nose import SkipTest
from depot._compat import PY2
S3Storage = None
FILE_CONTENT = b'HELLO WORLD'
class TestS3FileStorage(object):
def setup(self):
try:
global S3Storage
from depot.io.awss3 import S3Storage
except ImportError:
raise SkipTest('Boto not installed')
env = os.environ
access_key_id = env.get('AWS_ACCESS_KEY_ID')
secret_access_key = env.get('AWS_SECRET_ACCESS_KEY')
if access_key_id is None or secret_access_key is None:
raise SkipTest('Amazon S3 credentials not available')
PID = os.getpid()
NODE = str(uuid.uuid1()).rsplit('-', 1)[-1] # Travis runs multiple tests concurrently
self.default_bucket_name = 'filedepot-%s' % (access_key_id.lower(), )
self.cred = (access_key_id, secret_access_key)
self.fs = S3Storage(access_key_id, secret_access_key,
'filedepot-testfs-%s-%s-%s' % (access_key_id.lower(), NODE, PID))
def test_fileoutside_depot(self):
fid = str(uuid.uuid1())
key = self.fs._bucket_driver.new_key(fid)
key.set_contents_from_string(FILE_CONTENT)
f = self.fs.get(fid)
assert f.read() == FILE_CONTENT
def test_invalid_modified(self):
fid = str(uuid.uuid1())
key = self.fs._bucket_driver.new_key(fid)
key.set_metadata('x-depot-modified', 'INVALID')
key.set_contents_from_string(FILE_CONTENT)
f = self.fs.get(fid)
assert f.last_modified is None, f.last_modified
def test_creates_bucket_when_missing(self):
with mock.patch('boto.s3.connection.S3Connection.lookup', return_value=None):
with mock.patch('boto.s3.connection.S3Connection.lookup',
return_value='YES') as mock_create:
fs = S3Storage(*self.cred)
mock_create.assert_called_with(self.default_bucket_name)
def test_default_bucket_name(self):
with mock.patch('boto.s3.connection.S3Connection.lookup', return_value='YES'):
fs = S3Storage(*self.cred)
assert fs._bucket_driver.bucket == 'YES'
def test_public_url(self):
fid = str(uuid.uuid1())
key = self.fs._bucket_driver.new_key(fid)
key.set_contents_from_string(FILE_CONTENT)
f = self.fs.get(fid)
assert '.s3.amazonaws.com' in f.public_url, f.public_url
assert f.public_url.endswith('/%s' % fid), f.public_url
def test_content_disposition(self):
if not PY2:
raise SkipTest('Test is for Python2.X only')
file_id = self.fs.create(b'content', u'test.txt', 'text/plain')
test_file = self.fs.get(file_id)
response = requests.get(test_file.public_url)
assert response.headers['Content-Disposition'] == "inline;filename=test.txt;filename*=utf-8''test.txt"
def teardown(self):
keys = [key.name for key in self.fs._bucket_driver.bucket]
if keys:
self.fs._bucket_driver.bucket.delete_keys(keys)
try:
self.fs._conn.delete_bucket(self.fs._bucket_driver.bucket.name)
except:
pass
| import os
import uuid
import mock
import requests
from nose import SkipTest
from depot._compat import PY2
S3Storage = None
FILE_CONTENT = b'HELLO WORLD'
class TestS3FileStorage(object):
def setup(self):
try:
global S3Storage
from depot.io.awss3 import S3Storage
except ImportError:
raise SkipTest('Boto not installed')
env = os.environ
access_key_id = env.get('AWS_ACCESS_KEY_ID')
secret_access_key = env.get('AWS_SECRET_ACCESS_KEY')
if access_key_id is None or secret_access_key is None:
raise SkipTest('Amazon S3 credentials not available')
PID = os.getpid()
NODE = str(uuid.uuid1()).rsplit('-', 1)[-1] # Travis runs multiple tests concurrently
self.default_bucket_name = 'filedepot-%s' % (access_key_id.lower(), )
self.cred = (access_key_id, secret_access_key)
self.fs = S3Storage(access_key_id, secret_access_key,
'filedepot-testfs-%s-%s-%s' % (access_key_id.lower(), NODE, PID))
def test_fileoutside_depot(self):
fid = str(uuid.uuid1())
key = self.fs._bucket_driver.new_key(fid)
key.set_contents_from_string(FILE_CONTENT)
f = self.fs.get(fid)
assert f.read() == FILE_CONTENT
def test_invalid_modified(self):
fid = str(uuid.uuid1())
key = self.fs._bucket_driver.new_key(fid)
key.set_metadata('x-depot-modified', 'INVALID')
key.set_contents_from_string(FILE_CONTENT)
f = self.fs.get(fid)
assert f.last_modified is None, f.last_modified
def test_creates_bucket_when_missing(self):
with mock.patch('boto.s3.connection.S3Connection.lookup', return_value=None):
with mock.patch('boto.s3.connection.S3Connection.lookup',
return_value='YES') as mock_create:
fs = S3Storage(*self.cred)
mock_create.assert_called_with(self.default_bucket_name)
def test_default_bucket_name(self):
with mock.patch('boto.s3.connection.S3Connection.lookup', return_value='YES'):
fs = S3Storage(*self.cred)
assert fs._bucket_driver.bucket == 'YES'
def test_public_url(self):
fid = str(uuid.uuid1())
key = self.fs._bucket_driver.new_key(fid)
key.set_contents_from_string(FILE_CONTENT)
f = self.fs.get(fid)
assert '.s3.amazonaws.com' in f.public_url, f.public_url
assert f.public_url.endswith('/%s' % fid), f.public_url
def test_content_disposition(self):
if not PY2:
return
file_id = self.fs.create(b'content', u'test.txt', 'text/plain')
test_file = self.fs.get(file_id)
response = requests.get(test_file.public_url)
assert response.headers['Content-Disposition'] == "inline;filename=test.txt;filename*=utf-8''test.txt"
def teardown(self):
keys = [key.name for key in self.fs._bucket_driver.bucket]
if keys:
self.fs._bucket_driver.bucket.delete_keys(keys)
try:
self.fs._conn.delete_bucket(self.fs._bucket_driver.bucket.name)
except:
pass
| Python | 0.000001 |
1b11207f40d956267ae046bc51313a3cccc4776a | Fix typo in cdl filename | cdl_parser.py | cdl_parser.py | #!/usr/bin/env python
"""
Class to load and parse Common Data Language (CDL) files and
tokenize the dimensions and variables
Written by Brian Powell on 04/30/13
Copyright (c)2013 University of Hawaii under the BSD-License.
"""
from __future__ import print_function
import datetime
import re
def cdl_parser(filename):
"""
Given a netcdf-compliant CDL file, parse it to determine the structure:
dimensions, variables, attributes, and global attributes
Parameters
----------
filename : string
name and path of CDL file to parse
Returns
-------
dims, vars, attr: dict
dictionaries description dimensions, variables, and attributes
"""
dim_pat=re.compile(r"\s*(\w+)\s*=\s*(\w*)\s*;")
var_pat=re.compile(r"\s*(\w+)\s*(\w+)\({0,1}([\w\s,]*)\){0,1}\s*;")
attr_pat=re.compile(r"\s*(\w+):(\w+)\s*=\s*\"*([^\"]*)\"*\s*;")
global_attr_pat=re.compile(r"\s*:(\w+)\s*=\s*\"*([^\"]*)\"*\s*;")
mode=None
dims=dict()
attr=dict()
vars=list()
vcount=dict()
types={"float":"f4", "double":"f8", "short":"i2", "int":"i4", "char":"S1"}
for line in open(filename, 'r'):
# Check if this is a dimension definition line. If it is, add
# the dimension to the definition
parser = dim_pat.match(line)
if parser != None:
tokens = parser.groups()
if tokens[1].upper() == "UNLIMITED":
dims[tokens[0]]=0
else:
dims[tokens[0]]=int(tokens[1])
continue
# Check if this is a variable definition line. If it is, add
# the variable to the definition
parser = var_pat.match(line)
if parser != None:
tokens = parser.groups()
nvar = { "name": tokens[1],
"type": types[tokens[0]],
"dims": tokens[2].strip().split(", ") }
vars.append(nvar)
vcount[tokens[1]]=len(vars)-1
continue
# If this is an attribute, add the info to the appropriate variable
parser = attr_pat.match(line)
if parser != None:
tokens = parser.groups()
if "attr" not in vars[vcount[tokens[0]]]:
vars[vcount[tokens[0]]]["attr"] = dict()
vars[vcount[tokens[0]]]["attr"][tokens[1]] = tokens[2]
continue
# If this is a global attribute, add the info
parser = global_attr_pat.match(line)
if parser != None:
tokens = parser.groups()
attr[tokens[0]]=tokens[1]
continue
return dims, vars, attr
if __name__ == "__main__":
cdl_parser("out.cdl")
| #!/usr/bin/env python
"""
Class to load and parse Common Data Language (CDL) files and
tokenize the dimensions and variables
Written by Brian Powell on 04/30/13
Copyright (c)2013 University of Hawaii under the BSD-License.
"""
from __future__ import print_function
import datetime
import re
def cdl_parser(filename):
"""
Given a netcdf-compliant CDL file, parse it to determine the structure:
dimensions, variables, attributes, and global attributes
Parameters
----------
filename : string
name and path of CDL file to parse
Returns
-------
dims, vars, attr: dict
dictionaries description dimensions, variables, and attributes
"""
dim_pat=re.compile(r"\s*(\w+)\s*=\s*(\w*)\s*;")
var_pat=re.compile(r"\s*(\w+)\s*(\w+)\({0,1}([\w\s,]*)\){0,1}\s*;")
attr_pat=re.compile(r"\s*(\w+):(\w+)\s*=\s*\"*([^\"]*)\"*\s*;")
global_attr_pat=re.compile(r"\s*:(\w+)\s*=\s*\"*([^\"]*)\"*\s*;")
mode=None
dims=dict()
attr=dict()
vars=list()
vcount=dict()
types={"float":"f4", "double":"f8", "short":"i2", "int":"i4", "char":"S1"}
for line in open(file, 'r'):
# Check if this is a dimension definition line. If it is, add
# the dimension to the definition
parser = dim_pat.match(line)
if parser != None:
tokens = parser.groups()
if tokens[1].upper() == "UNLIMITED":
dims[tokens[0]]=0
else:
dims[tokens[0]]=int(tokens[1])
continue
# Check if this is a variable definition line. If it is, add
# the variable to the definition
parser = var_pat.match(line)
if parser != None:
tokens = parser.groups()
nvar = { "name": tokens[1],
"type": types[tokens[0]],
"dims": tokens[2].strip().split(", ") }
vars.append(nvar)
vcount[tokens[1]]=len(vars)-1
continue
# If this is an attribute, add the info to the appropriate variable
parser = attr_pat.match(line)
if parser != None:
tokens = parser.groups()
if "attr" not in vars[vcount[tokens[0]]]:
vars[vcount[tokens[0]]]["attr"] = dict()
vars[vcount[tokens[0]]]["attr"][tokens[1]] = tokens[2]
continue
# If this is a global attribute, add the info
parser = global_attr_pat.match(line)
if parser != None:
tokens = parser.groups()
attr[tokens[0]]=tokens[1]
continue
return dims, vars, attr
if __name__ == "__main__":
cdl_parser("out.cdl")
| Python | 0.997939 |
10e2638b8bafb15f66deb4a9ca442593a0ab52f2 | test fix | tests/test_core/test_ffi.py | tests/test_core/test_ffi.py | from textwrap import dedent
from os.path import dirname, join
try:
from unittest.mock import Mock, patch
except ImportError:
from mock import Mock, patch
from cffi import FFI
from pywincffi.core.ffi import Library
from pywincffi.core.testutil import TestCase
from pywincffi.exceptions import ResourceNotFoundError
class TestFFI(TestCase):
"""
Tests the ``pywinffi.core.ffi.ffi`` global.
"""
def test_unicode(self):
ffi, _ = Library.load()
self.assertTrue(ffi._windows_unicode)
def test_instance(self):
ffi, _ = Library.load()
self.assertIsInstance(ffi, FFI)
class TestSourcePaths(TestCase):
"""
Tests for ``pywincffi.core.ffi.Library.[HEADERS|SOURCES]``
"""
def test_sources_exist(self):
for path in Library.SOURCES:
try:
with open(path, "r"):
pass
except (OSError, IOError, WindowsError) as error:
self.fail("Failed to load %s: %s" % (path, error))
def test_headers_exist(self):
for path in Library.HEADERS:
try:
with open(path, "r"):
pass
except (OSError, IOError, WindowsError) as error:
self.fail("Failed to load %s: %s" % (path, error))
class TestLibraryLoad(TestCase):
"""
Tests for ``pywincffi.core.ffi.Library.load``
"""
def setUp(self):
self._cache = Library.CACHE
Library.CACHE = (None, None)
def tearDown(self):
Library.CACHE = self._cache
def test_header_not_found(self):
with patch.object(Library, "HEADERS", ("foobar", )):
with self.assertRaises(ResourceNotFoundError):
Library.load()
def test_loads_library(self):
fake_header = dedent("""
#define HELLO_WORLD 42
""")
with patch.object(Library, "_load_files", return_value=fake_header):
ffi, library = Library.load()
self.assertEqual(library.HELLO_WORLD, 42)
def test_caches_library(self):
fake_header = dedent("""
#define HELLO_WORLD 42
""")
with patch.object(Library, "_load_files", return_value=fake_header):
ffi1, lib1 = Library.load()
ffi2, lib2 = Library.load()
self.assertIs(ffi1, ffi2)
self.assertIs(lib1, lib2)
| from textwrap import dedent
from os.path import dirname, join
try:
from unittest.mock import Mock, patch
except ImportError:
from mock import Mock, patch
from cffi import FFI
from pywincffi.core.ffi import Library
from pywincffi.core.testutil import TestCase
from pywincffi.exceptions import ResourceNotFoundError
class TestFFI(TestCase):
"""
Tests the ``pywinffi.core.ffi.ffi`` global.
"""
def test_unicode(self):
ffi, _ = Library.load()
self.assertTrue(ffi._windows_unicode)
def test_instance(self):
ffi, _ = Library.load()
self.assertIsInstance(ffi, FFI)
class TestSourcePaths(TestCase):
"""
Tests for ``pywincffi.core.ffi.Library.[HEADERS|SOURCES]``
"""
def test_sources_exist(self):
for path in Library.SOURCES:
try:
with open(path, "r"):
pass
except (OSError, IOError, WindowsError) as error:
self.fail("Failed to load %s: %s" % (path, error))
def test_headers_exist(self):
for path in Library.HEADERS:
try:
with open(path, "r"):
pass
except (OSError, IOError, WindowsError) as error:
self.fail("Failed to load %s: %s" % (path, error))
class TestLibraryLoad(TestCase):
"""
Tests for ``pywincffi.core.ffi.Library.load``
"""
def setUp(self):
self._cache = Library.CACHE
Library.CACHE = (None, None)
def tearDown(self):
Library.CACHE = self._cache
def test_header_not_found(self):
with patch.object(Library, "HEADERS", ("foobar", )):
with self.assertRaises(ResourceNotFoundError):
Library.load()
def test_loads_library(self):
fake_header = dedent("""
#define HELLO_WORLD 42
""")
with patch.object(Library, "_load_files", return_value=fake_header):
ffi, library = Library.load()
self.assertEqual(library.HELLO_WORLD, 42)
def test_caches_library(self):
self.assertIsNone(Library.CACHE)
fake_header = dedent("""
#define HELLO_WORLD 42
""")
with patch.object(Library, "_load_files", return_value=fake_header):
ffi1, lib1 = Library.load()
ffi2, lib2 = Library.load()
self.assertIs(ffi1, ffi2)
self.assertIs(lib1, lib2)
| Python | 0.000001 |
78c3e6b7b3a12d74416f43995d50b04bdb817f0b | Fix test failure | tests/test_pkg_resources.py | tests/test_pkg_resources.py | import sys
import tempfile
import os
import zipfile
import pkg_resources
try:
unicode
except NameError:
unicode = str
class EggRemover(unicode):
def __call__(self):
if self in sys.path:
sys.path.remove(self)
if os.path.exists(self):
os.remove(self)
class TestZipProvider(object):
finalizers = []
@classmethod
def setup_class(cls):
"create a zip egg and add it to sys.path"
egg = tempfile.NamedTemporaryFile(suffix='.egg', delete=False)
zip_egg = zipfile.ZipFile(egg, 'w')
zip_info = zipfile.ZipInfo()
zip_info.filename = 'mod.py'
zip_info.date_time = 2013, 5, 12, 13, 25, 0
zip_egg.writestr(zip_info, 'x = 3\n')
zip_info = zipfile.ZipInfo()
zip_info.filename = 'data.dat'
zip_info.date_time = 2013, 5, 12, 13, 25, 0
zip_egg.writestr(zip_info, 'hello, world!')
zip_egg.close()
egg.close()
sys.path.append(egg.name)
cls.finalizers.append(EggRemover(egg.name))
@classmethod
def teardown_class(cls):
for finalizer in cls.finalizers:
finalizer()
def test_resource_filename_rewrites_on_change(self):
"""
If a previous call to get_resource_filename has saved the file, but
the file has been subsequently mutated with different file of the
same size and modification time, it should not be overwritten on a
subsequent call to get_resource_filename.
"""
import mod
manager = pkg_resources.ResourceManager()
zp = pkg_resources.ZipProvider(mod)
filename = zp.get_resource_filename(manager, 'data.dat')
assert os.stat(filename).st_mtime == 1368379500
f = open(filename, 'w')
f.write('hello, world?')
f.close()
os.utime(filename, (1368379500, 1368379500))
filename = zp.get_resource_filename(manager, 'data.dat')
f = open(filename)
assert f.read() == 'hello, world!'
manager.cleanup_resources()
class TestResourceManager(object):
def test_get_cache_path(self):
mgr = pkg_resources.ResourceManager()
path = mgr.get_cache_path('foo')
type_ = str(type(path))
message = "Unexpected type from get_cache_path: " + type_
assert isinstance(path, (unicode, str)), message
| import sys
import tempfile
import os
import zipfile
import pkg_resources
try:
unicode
except NameError:
unicode = str
class EggRemover(unicode):
def __call__(self):
if self in sys.path:
sys.path.remove(self)
if os.path.exists(self):
os.remove(self)
class TestZipProvider(object):
finalizers = []
@classmethod
def setup_class(cls):
"create a zip egg and add it to sys.path"
egg = tempfile.NamedTemporaryFile(suffix='.egg', delete=False)
zip_egg = zipfile.ZipFile(egg, 'w')
zip_info = zipfile.ZipInfo()
zip_info.filename = 'mod.py'
zip_info.date_time = 2013, 5, 12, 13, 25, 0
zip_egg.writestr(zip_info, 'x = 3\n')
zip_info = zipfile.ZipInfo()
zip_info.filename = 'data.dat'
zip_info.date_time = 2013, 5, 12, 13, 25, 0
zip_egg.writestr(zip_info, 'hello, world!')
zip_egg.close()
egg.close()
sys.path.append(egg.name)
cls.finalizers.append(EggRemover(egg.name))
@classmethod
def teardown_class(cls):
for finalizer in cls.finalizers:
finalizer()
def test_resource_filename_rewrites_on_change(self):
"""
If a previous call to get_resource_filename has saved the file, but
the file has been subsequently mutated with different file of the
same size and modification time, it should not be overwritten on a
subsequent call to get_resource_filename.
"""
import mod
manager = pkg_resources.ResourceManager()
zp = pkg_resources.ZipProvider(mod)
filename = zp.get_resource_filename(manager, 'data.dat')
assert os.stat(filename).st_mtime == 1368379500
f = open(filename, 'wb')
f.write('hello, world?')
f.close()
os.utime(filename, (1368379500, 1368379500))
filename = zp.get_resource_filename(manager, 'data.dat')
f = open(filename)
assert f.read() == 'hello, world!'
manager.cleanup_resources()
class TestResourceManager(object):
def test_get_cache_path(self):
mgr = pkg_resources.ResourceManager()
path = mgr.get_cache_path('foo')
type_ = str(type(path))
message = "Unexpected type from get_cache_path: " + type_
assert isinstance(path, (unicode, str)), message
| Python | 0.000128 |
f356adde3cb4776ad0a34b47be54a6e14972ce17 | Improve Python 3.x compatibility | tests/unit/test_excutils.py | tests/unit/test_excutils.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Red Hat, 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 openstack.common import excutils
from tests import utils
class SaveAndReraiseTest(utils.BaseTestCase):
def test_save_and_reraise_exception(self):
e = None
msg = 'foo'
try:
try:
raise Exception(msg)
except:
with excutils.save_and_reraise_exception():
pass
except Exception as _e:
e = _e
self.assertEqual(str(e), msg)
def test_save_and_reraise_exception_dropped(self):
e = None
msg = 'second exception'
try:
try:
raise Exception('dropped')
except:
with excutils.save_and_reraise_exception():
raise Exception(msg)
except Exception as _e:
e = _e
self.assertEqual(str(e), msg)
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Red Hat, 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 openstack.common import excutils
from tests import utils
class SaveAndReraiseTest(utils.BaseTestCase):
def test_save_and_reraise_exception(self):
e = None
msg = 'foo'
try:
try:
raise Exception(msg)
except:
with excutils.save_and_reraise_exception():
pass
except Exception, _e:
e = _e
self.assertEqual(str(e), msg)
def test_save_and_reraise_exception_dropped(self):
e = None
msg = 'second exception'
try:
try:
raise Exception('dropped')
except:
with excutils.save_and_reraise_exception():
raise Exception(msg)
except Exception, _e:
e = _e
self.assertEqual(str(e), msg)
| Python | 0.000022 |
514064ce5a0bc7d3ecab10d1b810e5b751ed79af | update supported thumbnail types | contrib/frontends/django/nntpchan/nntpchan/thumbnail.py | contrib/frontends/django/nntpchan/nntpchan/thumbnail.py | from django.conf import settings
import subprocess
import os
img_ext = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'ico']
vid_ext = ['mp4', 'webm', 'm4v', 'ogv', 'avi', 'txt']
def generate(fname, tname, placeholder):
"""
generate thumbnail
"""
ext = fname.split('.')[-1]
cmd = None
if ext in img_ext:
cmd = [settings.CONVERT_PATH, '-thumbnail', '200', fname, tname]
elif ext in vid_ext:
cmd = [settings.FFMPEG_PATH, '-i', fname, '-vf', 'scale=300:200', '-vframes', '1', tname]
if cmd is None:
os.link(placeholder, tname)
else:
subprocess.run(cmd, check=True)
| from django.conf import settings
import subprocess
import os
img_ext = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'ico', 'pdf', 'ps']
vid_ext = ['mp4', 'webm', 'm4v', 'ogv', 'avi', 'txt']
def generate(fname, tname, placeholder):
"""
generate thumbnail
"""
ext = fname.split('.')[-1]
cmd = None
if ext in img_ext:
cmd = [settings.CONVERT_PATH, '-thumbnail', '200', fname, tname]
elif ext in vid_ext:
cmd = [settings.FFMPEG_PATH, '-i', fname, '-vf', 'scale=300:200', '-vframes', '1', tname]
if cmd is None:
os.link(placeholder, tname)
else:
subprocess.run(cmd, check=True)
| Python | 0 |
d9204f19287060e1a88dfd1ac6072cd81eab5fe4 | add a validation mode | parse_aurinfo.py | parse_aurinfo.py | #!/usr/bin/env python
from copy import deepcopy
import pprint
import sys
MULTIVALUED_ATTRS = set([
'arch',
'groups',
'makedepends',
'checkdepends',
'optdepends',
'depends',
'provides',
'conflicts',
'replaces',
'options',
'license',
'source',
'noextract',
'backup',
])
def IsMultiValued(attr):
return attr in MULTIVALUED_ATTRS
class AurInfo(object):
def __init__(self):
self._pkgbase = {}
self._packages = {}
def GetPackageNames(self):
return self._packages.keys()
def GetMergedPackage(self, pkgname):
package = deepcopy(self._pkgbase)
package['pkgname'] = pkgname
for k, v in self._packages.get(pkgname).items():
package[k] = deepcopy(v)
return package
def AddPackage(self, pkgname):
self._packages[pkgname] = {}
return self._packages[pkgname]
def SetPkgbase(self, pkgbasename):
self._pkgbase = {'pkgname' : pkgbasename}
return self._pkgbase
class ECatcherInterface(object):
def Catch(self, lineno, error):
raise NotImplementedError
class StderrECatcher(ECatcherInterface):
def Catch(self, lineno, error):
print('ERROR[%d]: %s' % (lineno, error), file=sys.stderr)
class CollectionECatcher(ECatcherInterface):
def __init__(self):
self._errors = []
def Catch(self, lineno, error):
self._errors.append((lineno, error))
def HasErrors(self):
return len(self._errors) > 0
def ParseAurinfoFromIterable(iterable, ecatcher=None):
aurinfo = AurInfo()
if ecatcher is None:
ecatcher = StderrECatcher()
current_package = None
lineno = 0
for line in iterable:
lineno += 1
line = line.rstrip()
if not line:
# end of package
current_package = None
continue
if not line.startswith('\t'):
# start of new package
try:
key, value = line.split(' = ', 1)
except ValueError:
ecatcher.Catch(lineno, 'unexpected header format in section=%s' %
current_package['pkgname'])
continue
if key == 'pkgbase':
current_package = aurinfo.SetPkgbase(value)
else:
current_package = aurinfo.AddPackage(value)
else:
if current_package is None:
ecatcher.Catch(lineno, 'package attribute found outside of '
'a package section')
continue
# package attribute
try:
key, value = line.lstrip('\t').split(' = ', 1)
except ValueError:
ecatcher.Catch(lineno, 'unexpected attribute format in '
'section=%s' % current_package['pkgname'])
if IsMultiValued(key):
if not current_package.get(key):
current_package[key] = []
current_package[key].append(value)
else:
if not current_package.get(key):
current_package[key] = value
else:
ecatcher.Catch(lineno, 'overwriting attribute '
'%s: %s -> %s' % (key, current_package[key],
value))
return aurinfo
def ParseAurinfo(filename='.AURINFO', ecatcher=None):
with open(filename) as f:
return ParseAurinfoFromIterable(f, ecatcher)
def ValidateAurinfo(filename='.AURINFO'):
ecatcher = CollectionECatcher()
ParseAurinfo(filename, ecatcher)
return not ecatcher.HasErrors()
if __name__ == '__main__':
pp = pprint.PrettyPrinter(indent=4)
if len(sys.argv) == 1:
print('error: not enough arguments')
sys.exit(1)
elif len(sys.argv) == 2:
action = sys.argv[1]
filename = '.AURINFO'
else:
action, filename = sys.argv[1:3]
if action == 'parse':
aurinfo = ParseAurinfo()
for pkgname in aurinfo.GetPackageNames():
print(">>> merged package: %s" % pkgname)
pp.pprint(aurinfo.GetMergedPackage(pkgname))
print()
elif action == 'validate':
sys.exit(not ValidateAurinfo(filename))
else:
print('unknown action: %s' % action)
sys.exit(1)
| #!/usr/bin/env python
from copy import deepcopy
import pprint
MULTIVALUED_ATTRS = set([
'arch',
'groups',
'makedepends',
'checkdepends',
'optdepends',
'depends',
'provides',
'conflicts',
'replaces',
'options',
'license',
'source',
'noextract',
'backup',
])
def IsMultiValued(attr):
return attr in MULTIVALUED_ATTRS
class AurInfo(object):
def __init__(self):
self._pkgbase = {}
self._packages = {}
def GetPackageNames(self):
return self._packages.keys()
def GetMergedPackage(self, pkgname):
package = deepcopy(self._pkgbase)
package['pkgname'] = pkgname
for k, v in self._packages.get(pkgname).items():
package[k] = deepcopy(v)
return package
def AddPackage(self, pkgname):
self._packages[pkgname] = {}
return self._packages[pkgname]
def SetPkgbase(self, pkgbasename):
self._pkgbase = {'pkgname' : pkgbasename}
return self._pkgbase
def ParseAurinfoFromIterable(iterable):
aurinfo = AurInfo()
current_package = None
for line in iterable:
line = line.rstrip()
if not line:
# end of package
current_package = None
continue
if not line.startswith('\t'):
# start of new package
try:
key, value = line.split(' = ', 1)
except ValueError:
print('ERROR: unexpected header format: section=%s, line=%s' % (
current_package['pkgname'], line))
continue
if key == 'pkgbase':
current_package = aurinfo.SetPkgbase(value)
else:
current_package = aurinfo.AddPackage(value)
else:
if current_package is None:
print('ERROR: package attribute found outside of a package section')
continue
# package attribute
try:
key, value = line.lstrip('\t').split(' = ', 1)
except ValueError:
print('ERROR: unexpected attribute format: section=%s, line=%s' % (
current_package['pkgname'], line))
if IsMultiValued(key):
if not current_package.get(key):
current_package[key] = []
current_package[key].append(value)
else:
if not current_package.get(key):
current_package[key] = value
else:
print('WARNING: overwriting attribute %s: %s -> %s' % (
key, current_package[key], value))
return aurinfo
def ParseAurinfo(filename='.AURINFO'):
with open(filename) as f:
return ParseAurinfoFromIterable(f)
if __name__ == '__main__':
pp = pprint.PrettyPrinter(indent=4)
aurinfo = ParseAurinfo()
for pkgname in aurinfo.GetPackageNames():
print(">>> merged package: %s" % pkgname)
pp.pprint(aurinfo.GetMergedPackage(pkgname))
print()
| Python | 0.000005 |
31c70f509a849de98e0327902c48bdfcb8bd99a9 | fix another off by one with blur | pendulum_demo.py | pendulum_demo.py | #!/usr/bin/env python
import sys
import math
import time
import StringIO
from PIL import Image
import scipy.constants
from mathics.world import World
from mathics.viewport import Viewport
from mathics.machines import Pendulum, Timer, Point, Vector
def serve_gif(frames, duration, nq=0):
from PIL import Image
from images2gif import writeGif
gif = StringIO.StringIO()
timer_start = time.time()
writeGif(gif, frames, duration/len(frames), nq=nq)
with open('image.gif', 'wb') as f:
gif.seek(0)
f.write(gif.read())
timer_end = time.time()
print "stored gif in %i seconds." % (timer_end - timer_start)
# server image.gif
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
PORT_NUMBER = 8000
#This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','image/gif')
self.end_headers()
gif.seek(0)
self.wfile.write(gif.read())
return
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
#Wait forever for incoming http requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
if __name__ == '__main__':
supersample = 2
width = 200
font_size = 11
step = 0.05
duration = 4
blur = 0
x = int(supersample*width)
y = (6 * x / 5)
world = World(x, y, Viewport.WHITE, ("/usr/share/fonts/truetype/freefont/FreeSansBold.ttf", supersample * font_size))
viewport_different = Viewport(-4, 1.9, 8, -0.5, (0,200,0))
viewport = Viewport(-3, 3, 3, -3, Viewport.BEIGE)
world.add_viewport(viewport, 0, y/6, x, y)
world.add_viewport(viewport_different, 0, 0, x, y/6)
seconds_pendulum = Pendulum(Point(0,1), Vector.from_polar((2/(2*math.pi)) * (2/(2*math.pi)) * scipy.constants.g, math.radians(320)))
world.add_machine(seconds_pendulum)
seconds2_pendulum = Pendulum(Point(0,2), Vector.from_polar((4/(2*math.pi)) * (4/(2*math.pi)) * scipy.constants.g, math.radians(300)))
world.add_machine(seconds2_pendulum)
timer = Timer(Point(2,2))
world.add_machine(timer)
viewport.add_axis(0.2, 1)
viewport.add_visualization(seconds_pendulum.visualization_basic)
viewport.add_visualization(seconds2_pendulum.visualization_basic)
viewport.add_visualization(timer.visualization_basic)
viewport_different.add_visualization(seconds_pendulum.visualization_different)
viewport_different.add_visualization(seconds2_pendulum.visualization_different)
timer_start = time.time()
duration = step * math.ceil(duration/step)
frames = world.get_frames(0, duration, step, blur, 1.0/supersample)
timer_end = time.time()
print "generated %i frames in %i seconds. %f fps" % (len(frames) * (blur+1) - blur, timer_end - timer_start, (len(frames)*(blur+1))/duration)
serve_gif(frames, duration)
| #!/usr/bin/env python
import sys
import math
import time
import StringIO
from PIL import Image
import scipy.constants
from mathics.world import World
from mathics.viewport import Viewport
from mathics.machines import Pendulum, Timer, Point, Vector
def serve_gif(frames, duration, nq=0):
from PIL import Image
from images2gif import writeGif
gif = StringIO.StringIO()
timer_start = time.time()
writeGif(gif, frames, duration/len(frames), nq=nq)
with open('image.gif', 'wb') as f:
gif.seek(0)
f.write(gif.read())
timer_end = time.time()
print "stored gif in %i seconds." % (timer_end - timer_start)
# server image.gif
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
PORT_NUMBER = 8000
#This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','image/gif')
self.end_headers()
gif.seek(0)
self.wfile.write(gif.read())
return
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
#Wait forever for incoming http requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
if __name__ == '__main__':
supersample = 2
width = 200
font_size = 11
step = 0.05
duration = 4
blur = 0
x = int(supersample*width)
y = (6 * x / 5)
world = World(x, y, Viewport.WHITE, ("/usr/share/fonts/truetype/freefont/FreeSansBold.ttf", supersample * font_size))
viewport_different = Viewport(-4, 1.9, 8, -0.5, (0,200,0))
viewport = Viewport(-3, 3, 3, -3, Viewport.BEIGE)
world.add_viewport(viewport, 0, y/6, x, y)
world.add_viewport(viewport_different, 0, 0, x, y/6)
seconds_pendulum = Pendulum(Point(0,1), Vector.from_polar((2/(2*math.pi)) * (2/(2*math.pi)) * scipy.constants.g, math.radians(320)))
world.add_machine(seconds_pendulum)
seconds2_pendulum = Pendulum(Point(0,2), Vector.from_polar((4/(2*math.pi)) * (4/(2*math.pi)) * scipy.constants.g, math.radians(300)))
world.add_machine(seconds2_pendulum)
timer = Timer(Point(2,2))
world.add_machine(timer)
viewport.add_axis(0.2, 1)
viewport.add_visualization(seconds_pendulum.visualization_basic)
viewport.add_visualization(seconds2_pendulum.visualization_basic)
viewport.add_visualization(timer.visualization_basic)
viewport_different.add_visualization(seconds_pendulum.visualization_different)
viewport_different.add_visualization(seconds2_pendulum.visualization_different)
timer_start = time.time()
duration = step * math.ceil(duration/step)
frames = world.get_frames(0, duration, step, blur, 1.0/supersample)
timer_end = time.time()
print "generated %i frames in %i seconds. %f fps" % (len(frames) * (blur+1) - blur, timer_end - timer_start, (len(frames)*blur)/duration)
serve_gif(frames, duration)
| Python | 0.000001 |
14b473fc1b3a084a22c3e1ef37e2589d91650b2f | Add td_includes argument to allow more flexible relative include paths for td files. | third_party/mlir/tblgen.bzl | third_party/mlir/tblgen.bzl | """BUILD extensions for MLIR table generation."""
def gentbl(name, tblgen, td_file, tbl_outs, td_srcs = [], td_includes = [], strip_include_prefix = None):
"""gentbl() generates tabular code from a table definition file.
Args:
name: The name of the build rule for use in dependencies.
tblgen: The binary used to produce the output.
td_file: The primary table definitions file.
tbl_outs: A list of tuples (opts, out), where each opts is a string of
options passed to tblgen, and the out is the corresponding output file
produced.
td_srcs: A list of table definition files included transitively.
td_includes: A list of include paths for relative includes.
strip_include_prefix: attribute to pass through to cc_library.
"""
srcs = []
srcs += td_srcs
if td_file not in td_srcs:
srcs += [td_file]
# Add google_mlir/include directory as include so derived op td files can
# import relative to that.
td_includes_str = "-I external/local_config_mlir/include -I external/org_tensorflow "
for td_include in td_includes:
td_includes_str += "-I %s " % td_include
td_includes_str += "-I $$(dirname $(location %s)) " % td_file
for (opts, out) in tbl_outs:
rule_suffix = "_".join(opts.replace("-", "_").replace("=", "_").split(" "))
native.genrule(
name = "%s_%s_genrule" % (name, rule_suffix),
srcs = srcs,
outs = [out],
tools = [tblgen],
message = "Generating code from table: %s" % td_file,
cmd = (("$(location %s) %s %s $(location %s) -o $@") % (
tblgen,
td_includes_str,
opts,
td_file,
)),
)
# List of opts that do not generate cc files.
skip_opts = ["-gen-op-doc"]
hdrs = [f for (opts, f) in tbl_outs if opts not in skip_opts]
native.cc_library(
name = name,
# include_prefix does not apply to textual_hdrs.
hdrs = hdrs if strip_include_prefix else [],
strip_include_prefix = strip_include_prefix,
textual_hdrs = hdrs,
)
| """BUILD extensions for MLIR table generation."""
def gentbl(name, tblgen, td_file, tbl_outs, td_srcs = [], strip_include_prefix = None):
"""gentbl() generates tabular code from a table definition file.
Args:
name: The name of the build rule for use in dependencies.
tblgen: The binary used to produce the output.
td_file: The primary table definitions file.
tbl_outs: A list of tuples (opts, out), where each opts is a string of
options passed to tblgen, and the out is the corresponding output file
produced.
td_srcs: A list of table definition files included transitively.
strip_include_prefix: attribute to pass through to cc_library.
"""
srcs = []
srcs += td_srcs
if td_file not in td_srcs:
srcs += [td_file]
# Add google_mlir/include directory as include so derived op td files can
# import relative to that.
td_includes = "-I external/local_config_mlir/include -I external/org_tensorflow "
td_includes += "-I $$(dirname $(location %s)) " % td_file
for (opts, out) in tbl_outs:
rule_suffix = "_".join(opts.replace("-", "_").replace("=", "_").split(" "))
native.genrule(
name = "%s_%s_genrule" % (name, rule_suffix),
srcs = srcs,
outs = [out],
tools = [tblgen],
message = "Generating code from table: %s" % td_file,
cmd = (("$(location %s) %s %s $(location %s) -o $@") % (
tblgen,
td_includes,
opts,
td_file,
)),
)
# List of opts that do not generate cc files.
skip_opts = ["-gen-op-doc"]
hdrs = [f for (opts, f) in tbl_outs if opts not in skip_opts]
native.cc_library(
name = name,
# include_prefix does not apply to textual_hdrs.
hdrs = hdrs if strip_include_prefix else [],
strip_include_prefix = strip_include_prefix,
textual_hdrs = hdrs,
)
| Python | 0 |
9920f7f8bab741146b436c864fb1ff4682a4bda9 | Use a bigger buffer | tile-hash-proxy/__init__.py | tile-hash-proxy/__init__.py | import SimpleHTTPServer
import SocketServer
import requests
import md5
def calc_hash_terrain(s):
# When Ian built the hash for terrain tiles he used the path without
# the leading slash and the first 6 chars of the hex digest instead of 5
m = md5.new()
m.update(s[1:])
md5_hash = m.hexdigest()
return md5_hash[:6]
def calc_hash_vector(s):
m = md5.new()
m.update(s)
md5_hash = m.hexdigest()
return md5_hash[:5]
date_prefix = ''
base_url = ''
calc_hash = None
class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
server_version = "0.1"
def do_GET(self):
query_params = self.path.split('?')
old_path = query_params[0]
md5_hash = calc_hash(old_path)
new_path = '%(date)s/%(md5)s%(path)s' % dict(
date=date_prefix,
md5=md5_hash,
path=self.path
)
url = '%s/%s' % (base_url, new_path)
res = requests.get(url)
self.send_response(res.status_code, res.reason)
for k, v in res.headers.iteritems():
if k != 'Server' and k != 'Date':
self.send_header(k, v)
if 'access-control-allow-origin' not in res.headers:
self.send_header('access-control-allow-origin', '*')
self.end_headers()
kilobyte = 1024 * 1000
chunk_size = 16 * kilobyte
for chunk in res.iter_content(chunk_size):
self.wfile.write(chunk)
self.wfile.close()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'port',
type=int,
help="Port to listen on")
parser.add_argument(
'date_prefix',
help="Date prefix string to append to the base URL")
parser.add_argument(
'base_url',
help="Base S3 URL to make requests to")
parser.add_argument(
'--terrain',
dest='variant',
action='store_const',
const='terrain',
default='vector',
help="Use Terrain tiles variant of hashing")
args = parser.parse_args()
date_prefix = args.date_prefix
base_url = args.base_url
if args.variant == 'vector':
calc_hash = calc_hash_vector
elif args.variant == 'terrain':
calc_hash = calc_hash_terrain
else:
print "Uh oh I don't know how to hash %s" % args.variant
httpd = SocketServer.TCPServer(("", args.port), Handler)
print "Serving at http://localhost:%d/" % args.port
httpd.serve_forever()
| import SimpleHTTPServer
import SocketServer
import requests
import md5
def calc_hash_terrain(s):
# When Ian built the hash for terrain tiles he used the path without
# the leading slash and the first 6 chars of the hex digest instead of 5
m = md5.new()
m.update(s[1:])
md5_hash = m.hexdigest()
return md5_hash[:6]
def calc_hash_vector(s):
m = md5.new()
m.update(s)
md5_hash = m.hexdigest()
return md5_hash[:5]
date_prefix = ''
base_url = ''
calc_hash = None
class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
server_version = "0.1"
def do_GET(self):
query_params = self.path.split('?')
old_path = query_params[0]
md5_hash = calc_hash(old_path)
new_path = '%(date)s/%(md5)s%(path)s' % dict(
date=date_prefix,
md5=md5_hash,
path=self.path
)
url = '%s/%s' % (base_url, new_path)
res = requests.get(url)
self.send_response(res.status_code, res.reason)
for k, v in res.headers.iteritems():
if k != 'Server' and k != 'Date':
self.send_header(k, v)
if 'access-control-allow-origin' not in res.headers:
self.send_header('access-control-allow-origin', '*')
self.end_headers()
kilobyte = 1024 * 1000
chunk_size = 1 * kilobyte
for chunk in res.iter_content(chunk_size):
self.wfile.write(chunk)
self.wfile.close()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'port',
type=int,
help="Port to listen on")
parser.add_argument(
'date_prefix',
help="Date prefix string to append to the base URL")
parser.add_argument(
'base_url',
help="Base S3 URL to make requests to")
parser.add_argument(
'--terrain',
dest='variant',
action='store_const',
const='terrain',
default='vector',
help="Use Terrain tiles variant of hashing")
args = parser.parse_args()
date_prefix = args.date_prefix
base_url = args.base_url
if args.variant == 'vector':
calc_hash = calc_hash_vector
elif args.variant == 'terrain':
calc_hash = calc_hash_terrain
else:
print "Uh oh I don't know how to hash %s" % args.variant
httpd = SocketServer.TCPServer(("", args.port), Handler)
print "Serving at http://localhost:%d/" % args.port
httpd.serve_forever()
| Python | 0.000051 |
45b778c637d263208699a16ba926f0da10d5b0f4 | Fix incorrect behaviour with check.py | tmc/exercise_tests/check.py | tmc/exercise_tests/check.py | import re
import xml.etree.ElementTree as ET
from os import path
from tmc.exercise_tests.basetest import BaseTest, TestResult
class CheckTest(BaseTest):
def __init__(self):
super().__init__("Check")
def applies_to(self, exercise):
return path.isfile(path.join(exercise.path(), "Makefile"))
def test(self, exercise):
_, _, err = self.run(["make", "clean", "all", "run-test"], exercise)
ret = []
testpath = path.join(exercise.path(), "test", "tmc_test_results.xml")
if not path.isfile(testpath):
return [TestResult(success=False, message=err)]
if len(err) > 0:
ret.append(TestResult(message=err, warning=True))
xmlsrc = ""
with open(testpath) as fp:
xmlsrc = fp.read()
xmlsrc = re.sub(r"&(\s)", r"&\1", xmlsrc)
ns = "{http://check.sourceforge.net/ns}"
matchtest = ns + "test"
matchdesc = ns + "description"
matchmsg = ns + "message"
root = ET.fromstring(xmlsrc)
for test in root.iter(matchtest):
name = test.find(matchdesc).text
if test.get("result") in ["failure", "error"]:
success = False
message = test.find(matchmsg).text
message = message.replace(r"&", "&")
else:
success = True
message = ""
ret.append(TestResult(success=success, name=name, message=message))
return ret
| import re
import xml.etree.ElementTree as ET
from os import path
from tmc.exercise_tests.basetest import BaseTest, TestResult
class CheckTest(BaseTest):
def __init__(self):
super().__init__("Check")
def applies_to(self, exercise):
return path.isfile(path.join(exercise.path(), "Makefile"))
def test(self, exercise):
_, _, err = self.run(["make", "clean", "all", "run-test"], exercise)
ret = []
testpath = path.join(exercise.path(), "test", "tmc_test_results.xml")
if not path.isfile(testpath):
return [TestResult(success=False, message=err)]
if len(err) > 0:
ret.append(TestResult(message=err, warning=True))
xmlsrc = ""
with open(testpath) as fp:
xmlsrc = fp.read()
xmlsrc = re.sub(r"&(\s)", r"&\1", xmlsrc)
ns = "{http://check.sourceforge.net/ns}"
matchtest = ns + "test"
matchdesc = ns + "description"
matchmsg = ns + "message"
root = ET.fromstring(xmlsrc)
for test in root.iter(matchtest):
success = True
name = test.find(matchdesc).text
message = None
if test.get("result") == "failure":
success = False
message = test.find(matchmsg).text
message = message.replace(r"&", "&")
ret.append(TestResult(success=success, name=name, message=message))
return ret
| Python | 0.000001 |
6fc67196062dcfbf6d14679e3c735bdcd27ca5a2 | add one file type in basic mode | HomeworkCleaner.py | HomeworkCleaner.py | #! D:\Python33\python.exe
# -*- coding: utf-8 -*-
# Module : HomeworkCleaner.py
# Author : bss
# Project : TA
# State :
# Creation Date : 2014-12-26
# Last modified: 2015-01-02 11:56:12
# Description :
#
import os
import zipfile
g_basicList = ['obj','tlog','pdb','ilk','idb','log','lastbuildstate',
'manifest','res','rc','cache','cs','resources','baml','lref',
'exe.config','filelistabsolute.txt','pch','cpp','h',
'unsuccessfulbuild']
# 是否要删除此文件
def checkClearDir(path, filenames, choose):
s = os.sep
path = path.lower() # windows
if (path.endswith('d.dll')):
dllname = path.split(os.sep)[-1][:-5]
for filename in filenames:
if dllname == filename[:-4]:
return True
if (path.endswith('.dll') or path.endswith('.exe')):
return False
if (path.endswith('.sdf') or
path.endswith('.opensdf') or
path.endswith('.aps') or
path.find(s+'ipch'+s) >= 0 or
path.endswith('.pdb')):
return True
if (path.find('debug'+s) >= 0 or
path.find('release'+s) >= 0) :
if 1 == choose: # basic
for ext in g_basicList:
if path.endswith('.' + ext):
return True
print('keep ' + path.split(os.sep)[-1])
else: # aggressive, only keep dll and exe
return True
return False
def zipDir(cd, dirname, choose):
zipName = os.path.join(cd, dirname + '.zip')
f = zipfile.ZipFile(zipName, 'w', zipfile.ZIP_DEFLATED)
searchDir = os.path.join(cd, dirname)
for dirpath, dirnames, filenames in os.walk(searchDir):
for filename in filenames:
fileAbsPath = os.path.join(dirpath, filename)
if not checkClearDir(fileAbsPath, filenames, choose):
f.write(fileAbsPath, fileAbsPath[searchDir.__len__():])
f.close()
def main():
cd = os.path.abspath('.')
print(cd)
print('https://github.com/bssthu/HomeworkCleaner')
choose = input('1. Basic; 2. Aggressive ')
try:
choose = int(choose)
except:
pass
if (choose != 1 and choose != 2):
print('bye~')
return
for dirname in os.listdir(cd):
if os.path.isdir(os.path.join(cd, dirname)) and (dirname != '.git'):
print(dirname + ':')
zipDir(cd, dirname, choose)
print('nice!')
if __name__ == '__main__':
main()
os.system('pause')
| #! D:\Python33\python.exe
# -*- coding: utf-8 -*-
# Module : HomeworkCleaner.py
# Author : bss
# Project : TA
# State :
# Creation Date : 2014-12-26
# Last modified: 2014-12-29 17:44:18
# Description :
#
import os
import zipfile
g_basicList = ['obj','tlog','pdb','ilk','idb','log','lastbuildstate',
'manifest','res','rc','cache','cs','resources','baml','lref',
'exe.config','filelistabsolute.txt','pch','cpp','h']
# 是否要删除此文件
def checkClearDir(path, filenames, choose):
s = os.sep
path = path.lower() # windows
if (path.endswith('d.dll')):
dllname = path.split(os.sep)[-1][:-5]
for filename in filenames:
if dllname == filename[:-4]:
return True
if (path.endswith('.dll') or path.endswith('.exe')):
return False
if (path.endswith('.sdf') or
path.endswith('.opensdf') or
path.endswith('.aps') or
path.find(s+'ipch'+s) >= 0 or
path.endswith('.pdb')):
return True
if (path.find('debug'+s) >= 0 or
path.find('release'+s) >= 0) :
if 1 == choose: # basic
for ext in g_basicList:
if path.endswith('.' + ext):
return True
print('keep ' + path.split(os.sep)[-1])
else: # aggressive, only keep dll and exe
return True
return False
def zipDir(cd, dirname, choose):
zipName = os.path.join(cd, dirname + '.zip')
f = zipfile.ZipFile(zipName, 'w', zipfile.ZIP_DEFLATED)
searchDir = os.path.join(cd, dirname)
for dirpath, dirnames, filenames in os.walk(searchDir):
for filename in filenames:
fileAbsPath = os.path.join(dirpath, filename)
if not checkClearDir(fileAbsPath, filenames, choose):
f.write(fileAbsPath, fileAbsPath[searchDir.__len__():])
f.close()
def main():
cd = os.path.abspath('.')
print(cd)
print('https://github.com/bssthu/HomeworkCleaner')
choose = input('1. Basic; 2. Aggressive ')
try:
choose = int(choose)
except:
pass
if (choose != 1 and choose != 2):
print('bye~')
return
for dirname in os.listdir(cd):
if os.path.isdir(os.path.join(cd, dirname)) and (dirname != '.git'):
print(dirname + ':')
zipDir(cd, dirname, choose)
print('nice!')
if __name__ == '__main__':
main()
os.system('pause')
| Python | 0.000001 |
85aa5449a040247a6156801e88857048a7db6dd5 | update revnum | IPython/Release.py | IPython/Release.py | # -*- coding: utf-8 -*-
"""Release data for the IPython project.
$Id: Release.py 2446 2007-06-14 22:30:58Z vivainio $"""
#*****************************************************************************
# Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
#
# Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
# <n8gray@caltech.edu>
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#*****************************************************************************
# Name of the package for release purposes. This is the name which labels
# the tarballs and RPMs made by distutils, so it's best to lowercase it.
name = 'ipython'
# For versions with substrings (like 0.6.16.svn), use an extra . to separate
# the new substring. We have to avoid using either dashes or underscores,
# because bdist_rpm does not accept dashes (an RPM) convention, and
# bdist_deb does not accept underscores (a Debian convention).
revision = '2445'
version = '0.8.2.svn.r' + revision.rstrip('M')
description = "An enhanced interactive Python shell."
long_description = \
"""
IPython provides a replacement for the interactive Python interpreter with
extra functionality.
Main features:
* Comprehensive object introspection.
* Input history, persistent across sessions.
* Caching of output results during a session with automatically generated
references.
* Readline based name completion.
* Extensible system of 'magic' commands for controlling the environment and
performing many tasks related either to IPython or the operating system.
* Configuration system with easy switching between different setups (simpler
than changing $PYTHONSTARTUP environment variables every time).
* Session logging and reloading.
* Extensible syntax processing for special purpose situations.
* Access to the system shell with user-extensible alias system.
* Easily embeddable in other Python programs.
* Integrated access to the pdb debugger and the Python profiler.
The latest development version is always available at the IPython subversion
repository_.
.. _repository: http://ipython.scipy.org/svn/ipython/ipython/trunk#egg=ipython-dev
"""
license = 'BSD'
authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
'Janko' : ('Janko Hauser','jhauser@zscout.de'),
'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
'Ville' : ('Ville Vainio','vivainio@gmail.com')
}
url = 'http://ipython.scipy.org'
download_url = 'http://ipython.scipy.org/dist'
platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
keywords = ['Interactive','Interpreter','Shell']
| # -*- coding: utf-8 -*-
"""Release data for the IPython project.
$Id: Release.py 2409 2007-05-28 18:45:23Z vivainio $"""
#*****************************************************************************
# Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
#
# Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
# <n8gray@caltech.edu>
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#*****************************************************************************
# Name of the package for release purposes. This is the name which labels
# the tarballs and RPMs made by distutils, so it's best to lowercase it.
name = 'ipython'
# For versions with substrings (like 0.6.16.svn), use an extra . to separate
# the new substring. We have to avoid using either dashes or underscores,
# because bdist_rpm does not accept dashes (an RPM) convention, and
# bdist_deb does not accept underscores (a Debian convention).
revision = '2408'
version = '0.8.2.svn.r' + revision.rstrip('M')
description = "An enhanced interactive Python shell."
long_description = \
"""
IPython provides a replacement for the interactive Python interpreter with
extra functionality.
Main features:
* Comprehensive object introspection.
* Input history, persistent across sessions.
* Caching of output results during a session with automatically generated
references.
* Readline based name completion.
* Extensible system of 'magic' commands for controlling the environment and
performing many tasks related either to IPython or the operating system.
* Configuration system with easy switching between different setups (simpler
than changing $PYTHONSTARTUP environment variables every time).
* Session logging and reloading.
* Extensible syntax processing for special purpose situations.
* Access to the system shell with user-extensible alias system.
* Easily embeddable in other Python programs.
* Integrated access to the pdb debugger and the Python profiler.
The latest development version is always available at the IPython subversion
repository_.
.. _repository: http://ipython.scipy.org/svn/ipython/ipython/trunk#egg=ipython-dev
"""
license = 'BSD'
authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
'Janko' : ('Janko Hauser','jhauser@zscout.de'),
'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
'Ville' : ('Ville Vainio','vivainio@gmail.com')
}
url = 'http://ipython.scipy.org'
download_url = 'http://ipython.scipy.org/dist'
platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
keywords = ['Interactive','Interpreter','Shell']
| Python | 0.000001 |
5e409ec1d8d53cd3005022ff090043a9e5f5cb31 | Update nyan.py | NyanCheck/nyan.py | NyanCheck/nyan.py | #!/usr/bin/python3
from gi.repository import Gtk
from gi.repository import GObject
import webbrowser
import urllib.request
import re
def getNyan():
USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36"
r = urllib.request.Request("http://nyanyan.it/", headers={'User-Agent': USER_AGENT, 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'})
data = urllib.request.urlopen(r)
data = data.read()
found = re.findall( '<div class="tytul">.*<div class="stronicowanieD" style="width:700px;margin-left:20px">', str(data) )
return found[0]
class nyanIcon:
def __init__( self ):
self.site = getNyan()
self.trayicon = Gtk.StatusIcon()
self.trayicon.set_from_file( "normal.png" )
self.trayicon.set_visible( True )
self.trayicon.connect( "activate", self.openNyan )
self.trayicon.connect( "popup-menu", self.options )
GObject.timeout_add( 5000, self.checkNyan )
Gtk.main()
def options( self, icon, button, time ):
self.menu = Gtk.Menu()
exit = Gtk.MenuItem()
exit.set_label( "Exit" )
exit.connect( "activate", Gtk.main_quit )
self.menu.append( exit )
self.menu.show_all()
def pos( menu, icon):
return (Gtk.StatusIcon.position_menu(menu, icon))
self.menu.popup(None, None, pos, self.trayicon, button, time)
def checkNyan( self, *args ):
tempsite = getNyan()
if tempsite != self.site:
self.site = tempsite
self.trayicon.set_from_file( "new.png" )
GObject.timeout_add( 60000*5, self.checkNyan )
def openNyan( self, *args ):
self.trayicon.set_from_file( "normal.png" )
webbrowser.open( "http://nyanyan.it/" )
app = nyanIcon()
| #!/usr/bin/python3
from gi.repository import Gtk
from gi.repository import GObject
import webbrowser
import urllib.request
import re
def getNyan():
USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36"
r = urllib.request.Request("http://nyanyan.it/", headers={'User-Agent': USER_AGENT, 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'})
data = urllib.request.urlopen(r)
data = data.read()
found = re.findall( '<div class="tytul">.*<div class="stronicowanieD" style="width:700px;margin-left:20px">', str(data) )
return found[0]
class nyanIcon:
def __init__( self ):
self.site = getNyan()
self.trayicon = Gtk.StatusIcon()
self.trayicon.set_from_file( "normal.png" )
self.trayicon.set_visible( True )
self.trayicon.connect( "activate", self.openNyan )
self.trayicon.connect( "popup-menu", self.options )
GObject.timeout_add( 5000, self.checkNyan )
Gtk.main()
def options( self, icon, button, time ):
self.menu = Gtk.Menu()
exit = Gtk.MenuItem()
exit.set_label( "Exit" )
exit.connect( "activate", Gtk.main_quit )
self.menu.append( exit )
self.menu.show_all()
def pos( menu, icon):
return (Gtk.StatusIcon.position_menu(menu, icon))
self.menu.popup(None, None, pos, self.trayicon, button, time)
def checkNyan( self, *args ):
"""Checks for new posts on http://nyanyan.it/
Takes no arguments and return true if there is new post.
"""
tempsite = getNyan()
if tempsite != self.site:
self.site = tempsite
self.trayicon.set_from_file( "new.png" )
GObject.timeout_add( 60000*5, self.checkNyan )
def openNyan( self, *args ):
self.trayicon.set_from_file( "normal.png" )
webbrowser.open( "http://nyanyan.it/" )
app = nyanIcon() | Python | 0.000001 |
992dc795d1f7c7ef670832a5144b7e72a9374af8 | update test_forms | wizard_builder/tests/test_forms.py | wizard_builder/tests/test_forms.py | from django.test import TestCase
from .. import managers
class FormSerializationTest(TestCase):
manager = managers.FormManager
fixtures = [
'wizard_builder_data',
]
expected_data = [{
'descriptive_text': 'answer wisely',
'field_id': 'question_2',
'id': 2,
'page': 2,
'position': 0,
'question_text': 'do androids dream of electric sheep?',
'text': 'do androids dream of electric sheep?',
'type': 'singlelinetext',
'choices': [],
}]
@classmethod
def setUpClass(cls):
super().setUpClass()
form = cls.manager.get_form_models()[1]
cls.actual_data = form.serialized
def test_same_size(self):
actual_data = self.actual_data
expected_data = self.expected_data
self.assertEqual(
len(actual_data),
len(expected_data),
)
def test_same_questions(self):
actual_data = self.actual_data
expected_data = self.expected_data
for index, expected_question in enumerate(expected_data):
actual_question = actual_data[index]
self.assertEqual(
actual_question,
expected_question,
)
| from django.test import TestCase
from .. import managers
class FormSerializationTest(TestCase):
manager = managers.FormManager
fixtures = [
'wizard_builder_data',
]
expected_data = [{
'descriptive_text': 'answer wisely',
'field_id': 'question_2',
'id': 2,
'page': 2,
'position': 0,
'question_text': 'do androids dream of electric sheep?',
'text': 'do androids dream of electric sheep?',
'type': 'singlelinetext',
'is_dropdown': False,
'choices': [],
}]
@classmethod
def setUpClass(cls):
super().setUpClass()
form = cls.manager.get_form_models()[1]
cls.actual_data = form.serialized
def test_same_size(self):
actual_data = self.actual_data
expected_data = self.expected_data
self.assertEqual(
len(actual_data),
len(expected_data),
)
def test_same_questions(self):
actual_data = self.actual_data
expected_data = self.expected_data
for index, expected_question in enumerate(expected_data):
actual_question = actual_data[index]
self.assertEqual(
actual_question,
expected_question,
)
| Python | 0.000001 |
a9465bcfe387a3eb8ba730eeda5285be079044d3 | test cleanup | wizard_builder/tests/test_views.py | wizard_builder/tests/test_views.py | from unittest import mock
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from .. import view_helpers
class ViewTest(TestCase):
fixtures = [
'wizard_builder_data',
]
@classmethod
def setUpClass(cls):
settings.SITE_ID = 1
super().setUpClass()
def setUp(self):
super().setUp()
self.step = '1'
self.data = {'question_2': 'aloe ipsum speakerbox'}
self.storage_data = {self.step: self.data}
def test_storage_receives_post_data(self):
url = reverse('wizard_update', kwargs={'step': self.step})
self.client.post(url, self.data)
self.assertEqual(
self.client.session['data'],
self.storage_data,
)
| from unittest import mock
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from .. import view_helpers
class ViewTest(TestCase):
fixtures = [
'wizard_builder_data',
]
@classmethod
def setUpClass(cls):
settings.SITE_ID = 1
super().setUpClass()
def test_storage_receives_post_data(self):
step = '1'
url = reverse('wizard_update', kwargs={'step': step})
data = {'question_2': 'aloe ipsum speakerbox'}
storage_data = {step: data}
self.client.post(url, data)
self.assertEqual(
self.client.session['data'],
storage_data,
)
| Python | 0.000001 |
17d12027929365e8ebcc69c32642068cc6208678 | Decode stdout in shell.run_cmd | powerline/lib/shell.py | powerline/lib/shell.py | # vim:fileencoding=utf-8:noet
from subprocess import Popen, PIPE
from locale import getlocale, getdefaultlocale, LC_MESSAGES
def run_cmd(pl, cmd, stdin=None):
try:
p = Popen(cmd, stdout=PIPE, stdin=PIPE)
except OSError as e:
pl.exception('Could not execute command ({0}): {1}', e, cmd)
return None
else:
stdout, err = p.communicate(stdin)
encoding = getlocale(LC_MESSAGES)[1] or getdefaultlocale()[1] or 'utf-8'
stdout = stdout.decode(encoding)
return stdout.strip()
def asrun(pl, ascript):
'''Run the given AppleScript and return the standard output and error.'''
return run_cmd(pl, ['osascript', '-'], ascript)
| # vim:fileencoding=utf-8:noet
from subprocess import Popen, PIPE
def run_cmd(pl, cmd, stdin=None):
try:
p = Popen(cmd, stdout=PIPE, stdin=PIPE)
except OSError as e:
pl.exception('Could not execute command ({0}): {1}', e, cmd)
return None
else:
stdout, err = p.communicate(stdin)
return stdout.strip()
def asrun(pl, ascript):
'''Run the given AppleScript and return the standard output and error.'''
return run_cmd(pl, ['osascript', '-'], ascript)
| Python | 0.999042 |
12b806a0c68ceb146eed3b4a9406f36e9f930ba6 | Fix bug with closing socket without creating it again. | rl-rc-car/sensor_client.py | rl-rc-car/sensor_client.py | """
This is used to gather our readings from the remote sensor server.
http://ilab.cs.byu.edu/python/socket/echoclient.html
"""
import socket
import numpy as np
import time
class SensorClient:
def __init__(self, host='192.168.2.9', port=8888, size=1024):
self.host = host
self.port = port
self.size = size
def get_readings(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.host, self.port))
readings = s.recv(self.size)
s.close()
# Turn our weird stringed list into an actual list.
readings = readings.decode('utf-8')
readings = readings[1:-1]
readings = readings.split(', ')
readings = [float(i) for i in readings]
# Numpy it.
return np.array([readings])
if __name__ == '__main__':
# Testing it out.
from becho import becho, bechonet
network = bechonet.BechoNet(
num_actions=6, num_inputs=3,
nodes_1=256, nodes_2=256, verbose=True,
load_weights=True,
weights_file='saved-models/sonar-and-ir-9750.h5')
pb = becho.ProjectBecho(
network, num_actions=6, num_inputs=3,
verbose=True, enable_training=False)
sensors = SensorClient()
while True:
# Get the reading.
readings = sensors.get_readings()
print(readings)
# Get the action.
action = pb.get_action(readings)
print("Doing action %d" % action)
time.sleep(0.5)
| """
This is used to gather our readings from the remote sensor server.
http://ilab.cs.byu.edu/python/socket/echoclient.html
"""
import socket
import numpy as np
import time
class SensorClient:
def __init__(self, host='192.168.2.9', port=8888, size=1024):
self.host = host
self.port = port
self.size = size
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def get_readings(self):
self.s.connect((self.host, self.port))
readings = self.s.recv(self.size)
self.s.close()
# Turn our weird stringed list into an actual list.
readings = readings.decode('utf-8')
readings = readings[1:-1]
readings = readings.split(', ')
readings = [float(i) for i in readings]
# Numpy it.
return np.array([readings])
if __name__ == '__main__':
# Testing it out.
from becho import becho, bechonet
network = bechonet.BechoNet(
num_actions=6, num_inputs=3,
nodes_1=256, nodes_2=256, verbose=True,
load_weights=True,
weights_file='saved-models/sonar-and-ir-9750.h5')
pb = becho.ProjectBecho(
network, num_actions=6, num_inputs=3,
verbose=True, enable_training=False)
sensors = SensorClient()
while True:
# Get the reading.
readings = sensors.get_readings()
print(readings)
# Get the action.
action = pb.get_action(readings)
print("Doing action %d" % action)
time.sleep(0.5)
| Python | 0 |
a45d744a73c4ac54990854655dfec7e57df67eb4 | Add the device keyword to the array creation functions | numpy/_array_api/creation_functions.py | numpy/_array_api/creation_functions.py | def arange(start, /, *, stop=None, step=1, dtype=None, device=None):
from .. import arange
if device is not None:
# Note: Device support is not yet implemented on ndarray
raise NotImplementedError("Device support is not yet implemented")
return arange(start, stop=stop, step=step, dtype=dtype)
def empty(shape, /, *, dtype=None, device=None):
from .. import empty
if device is not None:
# Note: Device support is not yet implemented on ndarray
raise NotImplementedError("Device support is not yet implemented")
return empty(shape, dtype=dtype)
def empty_like(x, /, *, dtype=None, device=None):
from .. import empty_like
if device is not None:
# Note: Device support is not yet implemented on ndarray
raise NotImplementedError("Device support is not yet implemented")
return empty_like(x, dtype=dtype)
def eye(N, /, *, M=None, k=0, dtype=None, device=None):
from .. import eye
if device is not None:
# Note: Device support is not yet implemented on ndarray
raise NotImplementedError("Device support is not yet implemented")
return eye(N, M=M, k=k, dtype=dtype)
def full(shape, fill_value, /, *, dtype=None, device=None):
from .. import full
if device is not None:
# Note: Device support is not yet implemented on ndarray
raise NotImplementedError("Device support is not yet implemented")
return full(shape, fill_value, dtype=dtype)
def full_like(x, fill_value, /, *, dtype=None, device=None):
from .. import full_like
if device is not None:
# Note: Device support is not yet implemented on ndarray
raise NotImplementedError("Device support is not yet implemented")
return full_like(x, fill_value, dtype=dtype)
def linspace(start, stop, num, /, *, dtype=None, device=None, endpoint=True):
from .. import linspace
if device is not None:
# Note: Device support is not yet implemented on ndarray
raise NotImplementedError("Device support is not yet implemented")
return linspace(start, stop, num, dtype=dtype, endpoint=endpoint)
def ones(shape, /, *, dtype=None, device=None):
from .. import ones
if device is not None:
# Note: Device support is not yet implemented on ndarray
raise NotImplementedError("Device support is not yet implemented")
return ones(shape, dtype=dtype)
def ones_like(x, /, *, dtype=None, device=None):
from .. import ones_like
if device is not None:
# Note: Device support is not yet implemented on ndarray
raise NotImplementedError("Device support is not yet implemented")
return ones_like(x, dtype=dtype)
def zeros(shape, /, *, dtype=None, device=None):
from .. import zeros
if device is not None:
# Note: Device support is not yet implemented on ndarray
raise NotImplementedError("Device support is not yet implemented")
return zeros(shape, dtype=dtype)
def zeros_like(x, /, *, dtype=None, device=None):
from .. import zeros_like
if device is not None:
# Note: Device support is not yet implemented on ndarray
raise NotImplementedError("Device support is not yet implemented")
return zeros_like(x, dtype=dtype)
__all__ = ['arange', 'empty', 'empty_like', 'eye', 'full', 'full_like', 'linspace', 'ones', 'ones_like', 'zeros', 'zeros_like']
| def arange(start, /, *, stop=None, step=1, dtype=None):
from .. import arange
return arange(start, stop=stop, step=step, dtype=dtype)
def empty(shape, /, *, dtype=None):
from .. import empty
return empty(shape, dtype=dtype)
def empty_like(x, /, *, dtype=None):
from .. import empty_like
return empty_like(x, dtype=dtype)
def eye(N, /, *, M=None, k=0, dtype=None):
from .. import eye
return eye(N, M=M, k=k, dtype=dtype)
def full(shape, fill_value, /, *, dtype=None):
from .. import full
return full(shape, fill_value, dtype=dtype)
def full_like(x, fill_value, /, *, dtype=None):
from .. import full_like
return full_like(x, fill_value, dtype=dtype)
def linspace(start, stop, num, /, *, dtype=None, endpoint=True):
from .. import linspace
return linspace(start, stop, num, dtype=dtype, endpoint=endpoint)
def ones(shape, /, *, dtype=None):
from .. import ones
return ones(shape, dtype=dtype)
def ones_like(x, /, *, dtype=None):
from .. import ones_like
return ones_like(x, dtype=dtype)
def zeros(shape, /, *, dtype=None):
from .. import zeros
return zeros(shape, dtype=dtype)
def zeros_like(x, /, *, dtype=None):
from .. import zeros_like
return zeros_like(x, dtype=dtype)
__all__ = ['arange', 'empty', 'empty_like', 'eye', 'full', 'full_like', 'linspace', 'ones', 'ones_like', 'zeros', 'zeros_like']
| Python | 0.000004 |
8dcb778c62c3c6722e2f6dabfd97f6f75c349e62 | Set celery max tasks child to 1 | celery_cgi.py | celery_cgi.py | import os
import logging
from celery import Celery
from temp_config.set_environment import DeployEnv
runtime_env = DeployEnv()
runtime_env.load_deployment_environment()
redis_server = os.environ.get('REDIS_HOSTNAME')
redis_port = os.environ.get('REDIS_PORT')
celery_tasks = [
'hms_flask.modules.hms_controller',
'pram_flask.tasks'
]
redis = 'redis://' + redis_server + ':' + redis_port + '/0'
logging.info("Celery connecting to redis server: " + redis)
celery = Celery('flask_qed', broker=redis, backend=redis, include=celery_tasks)
celery.conf.update(
CELERY_ACCEPT_CONTENT=['json'],
CELERY_TASK_SERIALIZER='json',
CELERY_RESULT_SERIALIZER='json',
CELERY_IGNORE_RESULT=True,
CELERY_TRACK_STARTED=True,
worker_max_tasks_per_child = 1,
worker_max_memory_per_child = 50000
)
| import os
import logging
from celery import Celery
from temp_config.set_environment import DeployEnv
runtime_env = DeployEnv()
runtime_env.load_deployment_environment()
redis_server = os.environ.get('REDIS_HOSTNAME')
redis_port = os.environ.get('REDIS_PORT')
celery_tasks = [
'hms_flask.modules.hms_controller',
'pram_flask.tasks'
]
redis = 'redis://' + redis_server + ':' + redis_port + '/0'
logging.info("Celery connecting to redis server: " + redis)
celery = Celery('flask_qed', broker=redis, backend=redis, include=celery_tasks)
celery.conf.update(
CELERY_ACCEPT_CONTENT=['json'],
CELERY_TASK_SERIALIZER='json',
CELERY_RESULT_SERIALIZER='json',
CELERY_IGNORE_RESULT=True,
CELERY_TRACK_STARTED=True,
worker_max_memory_per_child = 50000
)
| Python | 0.999855 |
c82219ea0a651b01d7b9dd91286450e8ecab8fef | Make sure we clean up correctly after failed thrift connection | elasticsearch/connection/thrift.py | elasticsearch/connection/thrift.py | from __future__ import absolute_import
import time
try:
from .esthrift import Rest
from .esthrift.ttypes import Method, RestRequest
from thrift.transport import TTransport, TSocket, TSSLSocket
from thrift.protocol import TBinaryProtocol
from thrift.Thrift import TException
THRIFT_AVAILABLE = True
except ImportError:
THRIFT_AVAILABLE = False
from ..exceptions import ConnectionError, ImproperlyConfigured
from .pooling import PoolingConnection
class ThriftConnection(PoolingConnection):
"""
Connection using the `thrift` protocol to communicate with elasticsearch.
See https://github.com/elasticsearch/elasticsearch-transport-thrift for additional info.
"""
transport_schema = 'thrift'
def __init__(self, host='localhost', port=9500, framed_transport=False, use_ssl=False, **kwargs):
"""
:arg framed_transport: use `TTransport.TFramedTransport` instead of
`TTransport.TBufferedTransport`
"""
if not THRIFT_AVAILABLE:
raise ImproperlyConfigured("Thrift is not available.")
super(ThriftConnection, self).__init__(host=host, port=port, **kwargs)
self._framed_transport = framed_transport
self._tsocket_class = TSocket.TSocket
if use_ssl:
self._tsocket_class = TSSLSocket.TSSLSocket
self._tsocket_args = (host, port)
def _make_connection(self):
socket = self._tsocket_class(*self._tsocket_args)
socket.setTimeout(self.timeout * 1000.0)
if self._framed_transport:
transport = TTransport.TFramedTransport(socket)
else:
transport = TTransport.TBufferedTransport(socket)
protocol = TBinaryProtocol.TBinaryProtocolAccelerated(transport)
client = Rest.Client(protocol)
transport.open()
return client
def perform_request(self, method, url, params=None, body=None, timeout=None, ignore=()):
request = RestRequest(method=Method._NAMES_TO_VALUES[method.upper()], uri=url,
parameters=params, body=body)
start = time.time()
tclient = None
try:
tclient = self._get_connection()
response = tclient.execute(request)
duration = time.time() - start
except TException as e:
self.log_request_fail(method, url, body, time.time() - start, exception=e)
raise ConnectionError('N/A', str(e), e)
finally:
if tclient:
self._release_connection(tclient)
if not (200 <= response.status < 300) and response.status not in ignore:
self.log_request_fail(method, url, body, duration, response.status)
self._raise_error(response.status, response.body)
self.log_request_success(method, url, url, body, response.status,
response.body, duration)
return response.status, response.headers or {}, response.body
| from __future__ import absolute_import
import time
try:
from .esthrift import Rest
from .esthrift.ttypes import Method, RestRequest
from thrift.transport import TTransport, TSocket, TSSLSocket
from thrift.protocol import TBinaryProtocol
from thrift.Thrift import TException
THRIFT_AVAILABLE = True
except ImportError:
THRIFT_AVAILABLE = False
from ..exceptions import ConnectionError, ImproperlyConfigured
from .pooling import PoolingConnection
class ThriftConnection(PoolingConnection):
"""
Connection using the `thrift` protocol to communicate with elasticsearch.
See https://github.com/elasticsearch/elasticsearch-transport-thrift for additional info.
"""
transport_schema = 'thrift'
def __init__(self, host='localhost', port=9500, framed_transport=False, use_ssl=False, **kwargs):
"""
:arg framed_transport: use `TTransport.TFramedTransport` instead of
`TTransport.TBufferedTransport`
"""
if not THRIFT_AVAILABLE:
raise ImproperlyConfigured("Thrift is not available.")
super(ThriftConnection, self).__init__(host=host, port=port, **kwargs)
self._framed_transport = framed_transport
self._tsocket_class = TSocket.TSocket
if use_ssl:
self._tsocket_class = TSSLSocket.TSSLSocket
self._tsocket_args = (host, port)
def _make_connection(self):
socket = self._tsocket_class(*self._tsocket_args)
socket.setTimeout(self.timeout * 1000.0)
if self._framed_transport:
transport = TTransport.TFramedTransport(socket)
else:
transport = TTransport.TBufferedTransport(socket)
protocol = TBinaryProtocol.TBinaryProtocolAccelerated(transport)
client = Rest.Client(protocol)
transport.open()
return client
def perform_request(self, method, url, params=None, body=None, timeout=None, ignore=()):
request = RestRequest(method=Method._NAMES_TO_VALUES[method.upper()], uri=url,
parameters=params, body=body)
start = time.time()
try:
tclient = self._get_connection()
response = tclient.execute(request)
duration = time.time() - start
except TException as e:
self.log_request_fail(method, url, body, time.time() - start, exception=e)
raise ConnectionError('N/A', str(e), e)
finally:
self._release_connection(tclient)
if not (200 <= response.status < 300) and response.status not in ignore:
self.log_request_fail(method, url, body, duration, response.status)
self._raise_error(response.status, response.body)
self.log_request_success(method, url, url, body, response.status,
response.body, duration)
return response.status, response.headers or {}, response.body
| Python | 0 |
3d6fcb5c5ef05224f0129caf58507b555d17f35d | Fix indentation error in Flask | episode-2/flask/src/translation.py | episode-2/flask/src/translation.py | # -*- coding: utf-8 -*-
# Copyright 2016 IBM Corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from watson_developer_cloud import LanguageTranslationV2 as LanguageTranslationService
def getTranslationService():
return LanguageTranslationService(username='<your username key for the Watson language translation service>',
password='<your password key for the service>')
def identifyLanguage(app, data):
txt = data.encode("utf-8", "replace")
language_translation = getTranslationService()
langsdetected = language_translation.identify(txt)
app.logger.info(json.dumps(langsdetected, indent=2))
primarylang = langsdetected["languages"][0]
retData = {key: primarylang[key] for key in ('language', 'confidence')}
app.logger.info(json.dumps(retData, indent=2))
return retData
def checkForTranslation(app, fromlang, tolang):
supportedModels = []
lt = getTranslationService()
models = lt.list_models()
modelList = models.get("models")
supportedModels = [model['model_id'] for model in modelList
if fromlang == model['source']
and tolang == model['target']]
return supportedModels
def performTranslation(app, txt, primarylang, targetlang):
lt = getTranslationService()
translation = lt.translate(txt, source=primarylang, target=targetlang)
theTranslation = None
if translation and ("translations" in translation):
theTranslation = translation['translations'][0]['translation']
return theTranslation
| # -*- coding: utf-8 -*-
# Copyright 2016 IBM Corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from watson_developer_cloud import LanguageTranslationV2 as LanguageTranslationService
def getTranslationService():
return LanguageTranslationService(username='<your username key for the Watson language translation service>',
password='<your password key for the service>')
def identifyLanguage(app, data):
txt = data.encode("utf-8", "replace")
language_translation = getTranslationService()
langsdetected = language_translation.identify(txt)
app.logger.info(json.dumps(langsdetected, indent=2))
primarylang = langsdetected["languages"][0]
retData = {key: primarylang[key] for key in ('language', 'confidence')}
app.logger.info(json.dumps(retData, indent=2))
return retData
def checkForTranslation(app, fromlang, tolang):
supportedModels = []
lt = getTranslationService()
models = lt.list_models()
modelList = models.get("models")
supportedModels = [model['model_id'] for model in modelList
if fromlang == model['source']
and tolang == model['target']]
return supportedModels
def performTranslation(app, txt, primarylang, targetlang):
lt = getTranslationService()
translation = lt.translate(txt, source=primarylang, target=targetlang)
theTranslation = None
if translation and ("translations" in translation):
theTranslation = translation['translations'][0]['translation']
return theTranslation
| Python | 0.000002 |
4026d575cac94d98f8fa5467674020b18442359d | Update h-index.py | Python/h-index.py | Python/h-index.py | # Time: O(nlogn)
# Space: O(1)
# Given an array of citations (each citation is a non-negative integer)
# of a researcher, write a function to compute the researcher's h-index.
#
# According to the definition of h-index on Wikipedia:
# "A scientist has index h if h of his/her N papers have
# at least h citations each, and the other N − h papers have
# no more than h citations each."
#
# For example, given citations = [3, 0, 6, 1, 5],
# which means the researcher has 5 papers in total
# and each of them had received 3, 0, 6, 1, 5 citations respectively.
# Since the researcher has 3 papers with at least 3 citations each and
# the remaining two with no more than 3 citations each, his h-index is 3.
#
# Note: If there are several possible values for h, the maximum one is taken as the h-index.
#
class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
citations.sort(reverse=True)
h = 0
for i, x in enumerate(citations):
if x >= i + 1:
h += 1
else:
break
return h
# Time: O(nlogn)
# Space: O(n)
class Solution2(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
return sum(1 if x >= i + 1 else 0 for i, x in enumerate(sorted(citations, reverse=True)))
| # Time: O(nlogn)
# Space: O(1)
# Given an array of citations (each citation is a non-negative integer)
# of a researcher, write a function to compute the researcher's h-index.
#
# According to the definition of h-index on Wikipedia:
# "A scientist has index h if h of his/her N papers have
# at least h citations each, and the other N − h papers have
# no more than h citations each."
#
# For example, given citations = [3, 0, 6, 1, 5],
# which means the researcher has 5 papers in total
# and each of them had received 3, 0, 6, 1, 5 citations respectively.
# Since the researcher has 3 papers with at least 3 citations each and
# the remaining two with no more than 3 citations each, his h-index is 3.
#
# Note: If there are several possible values for h, the maximum one is taken as the h-index.
#
class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
citations.sort(reverse=True)
h = 0
for i, x in enumerate(citations):
if x >= i + 1:
h += 1
else:
break
return h
# Time: O(nlogn)
# Space: O(n)
class Solution2(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
sorted(citations, reverse=True)
h = 0
return sum(1 if x >= i + 1 else 0 for i, x in enumerate(sorted(citations, reverse=True)))
| Python | 0.000002 |
8deb3e45511950cc1a5d317f79f30bf59ed4821a | Update Changedate | changedate.py | changedate.py | """ Calcular Data a partir de uma quantidade de minutos """
def alterar_data(data_ent, op, minutos_ent):
""" Calcular nova data """
spl_Data_ent, spl_Hora_ent = data_ent.split(" ", 2)
spl_Dia_ent, spl_Mes_ent, spl_Ano_ent = spl_Data_ent.split("/", 3)
spl_Hora_ent, spl_Minu_ent = spl_Hora_ent.split(":", 2)
# transformar tudo em minutos
# converter horas em minutos totais
Minutos_Totais = (int(spl_Hora_ent) * 60) + int(spl_Minu_ent) + minutos_ent
print("Total de Minutos ", Minutos_Totais)
# 5415 / 60 minutos = 90.25 => separar inteiro de casas decimais 0.25 * 60 = 15
# HORAS_CONV_MINUTOS = MIN_TOT_E / 60
# 90h e 15 min
#I, D = divmod(HORAS_CONV_MINUTOS, 1)
#RESTO_MINUTOS = D * 60
# 90h / 24h = 3.75 => separar inteiro de casas decimais = 0.75 / 24
#TOTAL_DIAS = QTDE_TOTAL_HORAS / 24
#I, D = divmod(TOTAL_DIAS, 1)
# 3d 3.75 (0.75 * 24) = 18 h
#TOTAL_HORAS2 = D * 24
#print(int(I), " Dias", int(TOTAL_HORAS2), " horas", int(TOTAL_MINUTOS), " minutos")
if __name__ == ("__main__"):
alterar_data("31/12/2016 23:35","+", 4000)
| """ Calcular Data a partir de uma quantidade de minutos """
MINUTOSENTRADA = 4000
OPERADOR = "+"
DATA_E, HORA_E = "31/12/2016 23:35".split(" ", 2)
DIA_E, MES_E, ANO_E = DATA_E.split("/", 3)
HR_E, MINU_E = HORA_E.split(":", 2)
# transformar tudo em minutos
# converter horas em minutos
MIN_TOT_E = (int(HR_E) * 60) + int(MINU_E) + MINUTOSENTRADA
print("Total de Minutos ", MIN_TOT_E)
# 5415 / 60 minutos = 90.25 = .25 * 60
TOTAL_HORAS = MIN_TOT_E / 60
# 90h e 15 mine
I, D = divmod(TOTAL_HORAS, 1)
TOTAL_MINUTOS = D * 60
# 90h / 24h = 3.75 3 dias
TOTAL_DIAS = TOTAL_HORAS / 24
I, D = divmod(TOTAL_DIAS, 1)
# 3d 3.75 (0.75 * 24) = 18 h
TOTAL_HORAS2 = D * 24
print(int(I), " Dias", int(TOTAL_HORAS2), " horas", int(TOTAL_MINUTOS), " minutos")
# 3d 18h e 15min
# 4000 min / 60 min = No. de horas 66.66
# 66h e 40 min ... peguei a dízima e multipliquei por 66*60
# Então fica assim...
# 66 h / 24 h = No. de dias
# Agora pego o número de dias
# 2d 2.75 (dizima 0.75 * 24)
# 0,75 * 24 = 18 h
# 2D 18H 40M
| Python | 0.000001 |
62a2b5ab62a5c1080cdc30e3334cc62f4a51d6a9 | Make job mode API update change. | eurekaclinical/analytics/client.py | eurekaclinical/analytics/client.py | from eurekaclinical import APISession, API, Struct, construct_api_session_context_manager
class Job(Struct):
def __init__(self):
super(Job, self).__init__()
self.sourceConfigId = None
self.destinationId = None
self.dateRangePhenotypeKey = None
self.earliestDate = None
self.earliestDateSide = 'START'
self.latestDate = None
self.latestDateSide = 'START'
self.jobMode = 'UPDATE'
self.prompts = None
self.propositionIds = []
self.name = None
class Users(API):
def __init__(self, *args, **kwargs):
super(Users, self).__init__('/users/', *args, **kwargs)
def me(self):
return self._get(self.rest_endpoint + "me")
class Phenotypes(API):
def __init__(self, *args, **kwargs):
super(Phenotypes, self).__init__('/phenotypes/', *args, **kwargs)
class Concepts(API):
def __init__(self, *args, **kwargs):
super(Concepts, self).__init__('/concepts/', *args, **kwargs)
def get(self, key, summarize=False):
return self._get(self.rest_endpoint + key + "?summarize=" + str(summarize))
class Jobs(API):
def __init__(self, *args, **kwargs):
super(Jobs, self).__init__('/jobs/', *args, **kwargs)
def submit(self, job):
return self._post(self.rest_endpoint, job)
class AnalyticsSession(APISession):
def __init__(self, cas_session,
api_url='https://localhost:8000/eureka-webapp', verify_api_cert=True):
super(AnalyticsSession, self).__init__(cas_session, api_url=api_url, verify_api_cert=verify_api_cert)
self.__api_args = (cas_session, verify_api_cert, api_url)
@property
def users(self):
return Users(*self.__api_args)
@property
def phenotypes(self):
return Phenotypes(*self.__api_args)
@property
def concepts(self):
return Concepts(*self.__api_args)
@property
def jobs(self):
return Jobs(*self.__api_args)
get_session = construct_api_session_context_manager(AnalyticsSession)
| from eurekaclinical import APISession, API, Struct, construct_api_session_context_manager
class Job(Struct):
def __init__(self):
super(Job, self).__init__()
self.sourceConfigId = None
self.destinationId = None
self.dateRangePhenotypeKey = None
self.earliestDate = None
self.earliestDateSide = 'START'
self.latestDate = None
self.latestDateSide = 'START'
self.updateData = False
self.prompts = None
self.propositionIds = []
self.name = None
class Users(API):
def __init__(self, *args, **kwargs):
super(Users, self).__init__('/users/', *args, **kwargs)
def me(self):
return self._get(self.rest_endpoint + "me")
class Phenotypes(API):
def __init__(self, *args, **kwargs):
super(Phenotypes, self).__init__('/phenotypes/', *args, **kwargs)
class Concepts(API):
def __init__(self, *args, **kwargs):
super(Concepts, self).__init__('/concepts/', *args, **kwargs)
def get(self, key, summarize=False):
return self._get(self.rest_endpoint + key + "?summarize=" + str(summarize))
class Jobs(API):
def __init__(self, *args, **kwargs):
super(Jobs, self).__init__('/jobs/', *args, **kwargs)
def submit(self, job):
return self._post(self.rest_endpoint, job)
class AnalyticsSession(APISession):
def __init__(self, cas_session,
api_url='https://localhost:8000/eureka-webapp', verify_api_cert=True):
super(AnalyticsSession, self).__init__(cas_session, api_url=api_url, verify_api_cert=verify_api_cert)
self.__api_args = (cas_session, verify_api_cert, api_url)
@property
def users(self):
return Users(*self.__api_args)
@property
def phenotypes(self):
return Phenotypes(*self.__api_args)
@property
def concepts(self):
return Concepts(*self.__api_args)
@property
def jobs(self):
return Jobs(*self.__api_args)
get_session = construct_api_session_context_manager(AnalyticsSession)
| Python | 0 |
5294abf9253a077c0a23fe0e573174afd3728ac7 | fix caching in test | corehq/ex-submodules/casexml/apps/stock/tests/test_logistics_consumption.py | corehq/ex-submodules/casexml/apps/stock/tests/test_logistics_consumption.py | import uuid
from decimal import Decimal
from django.test import TestCase
from casexml.apps.case.models import CommCareCase
from casexml.apps.stock.models import StockReport, StockTransaction
from casexml.apps.stock.tests import ago
from casexml.apps.stock import const
from corehq.apps.commtrack.consumption import should_exclude_invalid_periods
from corehq.apps.commtrack.models import CommtrackConfig, ConsumptionConfig
from corehq.apps.domain.models import Domain
from corehq.apps.products.models import SQLProduct
class LogisticsConsumptionTest(TestCase):
@classmethod
def setUpClass(cls):
cls.domain = Domain(name='test')
cls.domain.save()
cls.case_id = uuid.uuid4().hex
CommCareCase(
_id=cls.case_id,
domain='fakedomain',
).save()
cls.product_id = uuid.uuid4().hex
SQLProduct(product_id=cls.product_id).save()
def create_transactions(self, domain=None):
report = StockReport.objects.create(
form_id=uuid.uuid4().hex,
date=ago(2),
type=const.REPORT_TYPE_BALANCE,
domain=domain
)
txn = StockTransaction(
report=report,
section_id=const.SECTION_TYPE_STOCK,
type=const.TRANSACTION_TYPE_STOCKONHAND,
case_id=self.case_id,
product_id=self.product_id,
stock_on_hand=Decimal(10),
)
txn.save()
report2 = StockReport.objects.create(
form_id=uuid.uuid4().hex,
date=ago(1),
type=const.REPORT_TYPE_BALANCE,
domain=domain
)
txn2 = StockTransaction(
report=report2,
section_id=const.SECTION_TYPE_STOCK,
type=const.TRANSACTION_TYPE_STOCKONHAND,
case_id=self.case_id,
product_id=self.product_id,
stock_on_hand=Decimal(30),
)
txn2.save()
def setUp(self):
StockTransaction.objects.all().delete()
StockReport.objects.all().delete()
def tearDown(self):
should_exclude_invalid_periods.clear(self.domain.name)
should_exclude_invalid_periods.clear(None)
def test_report_without_config(self):
self.create_transactions(self.domain.name)
self.assertEqual(StockTransaction.objects.all().count(), 3)
receipts = StockTransaction.objects.filter(type='receipts')
self.assertEqual(receipts.count(), 1)
self.assertEqual(receipts[0].quantity, 20)
def test_report_without_domain(self):
self.create_transactions()
self.assertEqual(StockTransaction.objects.all().count(), 3)
receipts = StockTransaction.objects.filter(type='receipts')
self.assertEqual(receipts.count(), 1)
self.assertEqual(receipts[0].quantity, 20)
def test_report_with_exclude_disabled(self):
commtrack_config = CommtrackConfig(domain=self.domain.name)
commtrack_config.consumption_config = ConsumptionConfig()
commtrack_config.save()
self.create_transactions(self.domain.name)
self.assertEqual(StockTransaction.objects.all().count(), 3)
self.assertEqual(StockTransaction.objects.filter(type='receipts').count(), 1)
commtrack_config.delete()
def test_report_with_exclude_enabled(self):
commtrack_config = CommtrackConfig(domain=self.domain.name)
commtrack_config.consumption_config = ConsumptionConfig(exclude_invalid_periods=True)
commtrack_config.save()
self.create_transactions(self.domain.name)
self.assertEqual(StockTransaction.objects.all().count(), 2)
self.assertEqual(StockTransaction.objects.filter(type='receipts').count(), 0)
commtrack_config.delete()
| import uuid
from decimal import Decimal
from django.test import TestCase
from casexml.apps.case.models import CommCareCase
from casexml.apps.stock.models import StockReport, StockTransaction
from casexml.apps.stock.tests import ago
from casexml.apps.stock import const
from corehq.apps.commtrack.models import CommtrackConfig, ConsumptionConfig
from corehq.apps.domain.models import Domain
from corehq.apps.products.models import SQLProduct
class LogisticsConsumptionTest(TestCase):
@classmethod
def setUpClass(cls):
cls.domain = Domain(name='test')
cls.domain.save()
cls.case_id = uuid.uuid4().hex
CommCareCase(
_id=cls.case_id,
domain='fakedomain',
).save()
cls.product_id = uuid.uuid4().hex
SQLProduct(product_id=cls.product_id).save()
def create_transactions(self, domain=None):
report = StockReport.objects.create(
form_id=uuid.uuid4().hex,
date=ago(2),
type=const.REPORT_TYPE_BALANCE,
domain=domain
)
txn = StockTransaction(
report=report,
section_id=const.SECTION_TYPE_STOCK,
type=const.TRANSACTION_TYPE_STOCKONHAND,
case_id=self.case_id,
product_id=self.product_id,
stock_on_hand=Decimal(10),
)
txn.save()
report2 = StockReport.objects.create(
form_id=uuid.uuid4().hex,
date=ago(1),
type=const.REPORT_TYPE_BALANCE,
domain=domain
)
txn2 = StockTransaction(
report=report2,
section_id=const.SECTION_TYPE_STOCK,
type=const.TRANSACTION_TYPE_STOCKONHAND,
case_id=self.case_id,
product_id=self.product_id,
stock_on_hand=Decimal(30),
)
txn2.save()
def setUp(self):
StockTransaction.objects.all().delete()
StockReport.objects.all().delete()
def test_report_without_config(self):
self.create_transactions(self.domain.name)
self.assertEqual(StockTransaction.objects.all().count(), 3)
receipts = StockTransaction.objects.filter(type='receipts')
self.assertEqual(receipts.count(), 1)
self.assertEqual(receipts[0].quantity, 20)
def test_report_without_domain(self):
self.create_transactions()
self.assertEqual(StockTransaction.objects.all().count(), 3)
receipts = StockTransaction.objects.filter(type='receipts')
self.assertEqual(receipts.count(), 1)
self.assertEqual(receipts[0].quantity, 20)
def test_report_with_exclude_disabled(self):
commtrack_config = CommtrackConfig(domain=self.domain.name)
commtrack_config.consumption_config = ConsumptionConfig()
commtrack_config.save()
self.create_transactions(self.domain.name)
self.assertEqual(StockTransaction.objects.all().count(), 3)
self.assertEqual(StockTransaction.objects.filter(type='receipts').count(), 1)
commtrack_config.delete()
def test_report_with_exclude_enabled(self):
commtrack_config = CommtrackConfig(domain=self.domain.name)
commtrack_config.consumption_config = ConsumptionConfig(exclude_invalid_periods=True)
commtrack_config.save()
self.create_transactions(self.domain.name)
self.assertEqual(StockTransaction.objects.all().count(), 2)
self.assertEqual(StockTransaction.objects.filter(type='receipts').count(), 0)
commtrack_config.delete()
| Python | 0.000001 |
11cc0c5f8aae526eddb372fbe339f649f2c654eb | Update pattern for inline comments to allow anything after '#' | poyo/patterns.py | poyo/patterns.py | # -*- coding: utf-8 -*-
INDENT = r"(?P<indent>^ *)"
VARIABLE = r"(?P<variable>.+):"
VALUE = r"(?P<value>((?P<q2>['\"]).*?(?P=q2))|[^#]+?)"
NEWLINE = r"$\n"
BLANK = r" +"
INLINE_COMMENT = r"( +#.*)?"
COMMENT = r"^ *#.*" + NEWLINE
BLANK_LINE = r"^[ \t]*" + NEWLINE
SECTION = INDENT + VARIABLE + INLINE_COMMENT + NEWLINE
SIMPLE = INDENT + VARIABLE + BLANK + VALUE + INLINE_COMMENT + NEWLINE
NULL = r"null|Null|NULL|~"
TRUE = r"true|True|TRUE"
FALSE = r"false|False|FALSE"
INT = r"[-+]?[0-9]+"
FLOAT = r"([-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?)"
STR = r"(?P<quotes>['\"]?).*(?P=quotes)"
| # -*- coding: utf-8 -*-
INDENT = r"(?P<indent>^ *)"
VARIABLE = r"(?P<variable>.+):"
VALUE = r"(?P<value>((?P<q2>['\"]).*?(?P=q2))|[^#]+?)"
NEWLINE = r"$\n"
BLANK = r" +"
INLINE_COMMENT = r"( +#\w*)?"
COMMENT = r"^ *#.*" + NEWLINE
BLANK_LINE = r"^[ \t]*" + NEWLINE
SECTION = INDENT + VARIABLE + INLINE_COMMENT + NEWLINE
SIMPLE = INDENT + VARIABLE + BLANK + VALUE + INLINE_COMMENT + NEWLINE
NULL = r"null|Null|NULL|~"
TRUE = r"true|True|TRUE"
FALSE = r"false|False|FALSE"
INT = r"[-+]?[0-9]+"
FLOAT = r"([-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?)"
STR = r"(?P<quotes>['\"]?).*(?P=quotes)"
| Python | 0 |
0f9b5bdba841d707e236bb8ed8df5ba4aa7806c2 | Allow a None value for os_config_path. | praw/settings.py | praw/settings.py | # This file is part of PRAW.
#
# PRAW is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# PRAW is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# PRAW. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
from praw.compat import configparser # pylint: disable-msg=E0611
def _load_configuration():
config = configparser.RawConfigParser()
module_dir = os.path.dirname(sys.modules[__name__].__file__)
if 'APPDATA' in os.environ: # Windows
os_config_path = os.environ['APPDATA']
elif 'XDG_CONFIG_HOME' in os.environ: # Modern Linux
os_config_path = os.environ['XDG_CONFIG_HOME']
elif 'HOME' in os.environ: # Legacy Linux
os_config_path = os.path.join(os.environ['HOME'], '.config')
else:
os_config_path = None
locations = [os.path.join(module_dir, 'praw.ini'),
'praw.ini']
if os_config_path is not None:
locations.insert(1,os.path.join(os_config_path, 'praw.ini'))
if not config.read(locations):
raise Exception('Could not find config file in any of: %s' % locations)
return config
CONFIG = _load_configuration()
| # This file is part of PRAW.
#
# PRAW is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# PRAW is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# PRAW. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
from praw.compat import configparser # pylint: disable-msg=E0611
def _load_configuration():
config = configparser.RawConfigParser()
module_dir = os.path.dirname(sys.modules[__name__].__file__)
if 'APPDATA' in os.environ: # Windows
os_config_path = os.environ['APPDATA']
elif 'XDG_CONFIG_HOME' in os.environ: # Modern Linux
os_config_path = os.environ['XDG_CONFIG_HOME']
else: # Legacy Linux
os_config_path = os.path.join(os.environ['HOME'], '.config')
locations = [os.path.join(module_dir, 'praw.ini'),
os.path.join(os_config_path, 'praw.ini'),
'praw.ini']
if not config.read(locations):
raise Exception('Could not find config file in any of: %s' % locations)
return config
CONFIG = _load_configuration()
| Python | 0 |
28c3f4e17a1f7a003d75353005cd96c854bd30d9 | replace lb:no_nsfw | cogs/nekos.py | cogs/nekos.py | """
The MIT License (MIT)
Copyright (c) 2018 tilda
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
# noinspection PyPackageRequirements
import discord
import json
# noinspection PyPackageRequirements
from discord.ext import commands
# noinspection PyPackageRequirements
import utils.errors
from cogs.utils.plainreq import get_req
from cogs.utils.endpoints import nekos
class Animemes:
def __init__(self, bot):
self.bot = bot
self.config = json.load(open('config.json'))
@commands.command()
async def neko(self, ctx):
"""Shows a neko"""
async with get_req(ctx.bot.session, nekos['sfw']) as neko:
if neko.status == 200:
img = await neko.json()
neko_em = discord.Embed(colour=0x690E8)
neko_em.set_image(url=img['neko'])
neko_em.set_footer(text='source: nekos.life')
await ctx.send(embed=neko_em)
else:
raise utils.errors.ServiceError(f'dude rip (http {neko.status})')
@commands.command()
async def lneko(self, ctx):
"""NSFW: Shows a random lewd neko pic
Disable this command by putting "[no_nsfw]" in your channel topic.
"""
if ctx.channel.is_nsfw():
if '[no_nsfw]' in ctx.channel.topic:
raise utils.errors.NSFWException()
else:
async with get_req(ctx.bot.session, nekos['nsfw']) as lneko:
if lneko.status == 200:
img = await lneko.json()
# noinspection PyPep8Naming
lneko_em = discord.Embed(colour=0x690E8)
lneko_em.set_image(url=img['neko'])
lneko_em.set_footer(text='source: nekos.life')
await ctx.send(embed=lneko_em)
else:
raise utils.errors.ServiceError(f'dude rip (http {lneko.status})')
else:
raise utils.errors.NSFWException('you really think you can do this'
'in a non nsfw channel? lol')
def setup(bot):
bot.add_cog(Animemes(bot))
| """
The MIT License (MIT)
Copyright (c) 2018 tilda
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
# noinspection PyPackageRequirements
import discord
import json
# noinspection PyPackageRequirements
from discord.ext import commands
# noinspection PyPackageRequirements
import utils.errors
from cogs.utils.plainreq import get_req
from cogs.utils.endpoints import nekos
class Animemes:
def __init__(self, bot):
self.bot = bot
self.config = json.load(open('config.json'))
@commands.command()
async def neko(self, ctx):
"""Shows a neko"""
async with get_req(ctx.bot.session, nekos['sfw']) as neko:
if neko.status == 200:
img = await neko.json()
neko_em = discord.Embed(colour=0x690E8)
neko_em.set_image(url=img['neko'])
neko_em.set_footer(text='source: nekos.life')
await ctx.send(embed=neko_em)
else:
raise utils.errors.ServiceError(f'dude rip (http {neko.status})')
@commands.command()
async def lneko(self, ctx):
"""NSFW: Shows a random lewd neko pic
Disable this command by putting "[lb:no_nsfw]" in your channel topic.
"""
if ctx.channel.is_nsfw():
if '[lb:no_nsfw]' in ctx.channel.topic:
raise utils.errors.NSFWException()
else:
async with get_req(ctx.bot.session, nekos['nsfw']) as lneko:
if lneko.status == 200:
img = await lneko.json()
# noinspection PyPep8Naming
lneko_em = discord.Embed(colour=0x690E8)
lneko_em.set_image(url=img['neko'])
lneko_em.set_footer(text='source: nekos.life')
await ctx.send(embed=lneko_em)
else:
raise utils.errors.ServiceError(f'dude rip (http {lneko.status})')
else:
raise utils.errors.NSFWException('you really think you can do this'
'in a non nsfw channel? lol')
def setup(bot):
bot.add_cog(Animemes(bot))
| Python | 0.002582 |
a307b6a059e1da4fc415296016280e5149bbd061 | Update radio.py | cogs/radio.py | cogs/radio.py | from .utils import config, checks, formats
import discord
from discord.ext import commands
import discord.utils
from .utils.api.pycopy import Copy
import random, json, asyncio
from urllib.parse import unquote
class Radio:
"""The radio-bot related commands."""
def __init__(self, bot):
self.bot = bot
if not discord.opus.is_loaded():
discord.opus.load_opus('/usr/local/lib/libopus.so') #FreeBSD path
self.player = None
self.stopped = True
self.q = asyncio.Queue()
self.play_next_song = asyncio.Event()
self.current_song = None
copy_creds = self.load_copy_creds()
self.copycom = Copy(copy_creds['login'], copy_creds['passwd'])
self.songs = []
self.update_song_list()
def load_copy_creds(self):
with open('copy_creds.json') as f:
return json.load(f)
@property
def is_playing(self):
return self.player is not None and self.player.is_playing() and not self.stopped
def toggle_next_song(self):
if not self.stopped:
self.bot.loop.call_soon_threadsafe(self.play_next_song.set)
def update_song_list(self):
self.songs = self.copycom.list_files('radio/')
@commands.command()
async def join(self, *, channel : discord.Channel = None):
"""Join voice channel.
"""
if channel is None or channel.type is not discord.ChannelType.voice:
await self.bot.say('Cannot find a voice channel by that name. {0}'.format(channel.type))
return
await self.bot.join_voice_channel(channel)
@commands.command(pass_context=True)
async def leave(self):
"""Leave voice channel.
"""
await ctx.invoke(self.stop)
await self.bot.voice.disconnect()
@commands.command()
async def pause(self):
"""Pause.
"""
if self.player is not None:
self.player.pause()
@commands.command()
async def resume(self):
"""Resume playing.
"""
if self.player is not None and not self.is_playing():
self.player.resume()
@commands.command()
async def skip(self):
"""Skip song and play next.
"""
if self.player is not None and self.is_playing():
self.player.stop()
self.toggle_next_song()
@commands.command()
async def stop():
"""Stop playing song.
"""
if self.is_playing():
self.stopped = True
self.player.stop()
@commands.command(pass_context=True)
async def play(self, ctx):
"""Start playing song from queue.
"""
if self.player is not None:
if not self.is_playing():
await ctx.invoke(self.resume)
return
else:
await self.bot.say('Already playing a song')
return
while True:
if not self.bot.is_voice_connected():
await ctx.invoke(self.join, channel=ctx.message.author.voice_channel)
continue
if self.q.empty():
await self.q.put(random.choice(self.songs))
self.play_next_song.clear()
self.current = await self.q.get()
self.player = self.bot.voice.create_ffmpeg_player(
self.copycom.direct_link('radio/' + self.current),
after=self.toggle_next_song,
#options="-loglevel debug -report",
headers = dict(self.copycom.session.headers))
self.stopped = False
self.player.start()
fmt = 'Playing song "{0}"'
song_name = unquote(self.current.split('/')[-1])
await self.bot.say(fmt.format(song_name))
self.bot.change_status(discord.Game(name=song_name))
await self.play_next_song.wait()
def setup(bot):
bot.add_cog(Radio(bot))
| from .utils import config, checks, formats
import discord
from discord.ext import commands
import discord.utils
from .utils.api.pycopy import Copy
import random, json, asyncio
from urllib.parse import unquote
class Radio:
"""The radio-bot related commands."""
def __init__(self, bot):
self.bot = bot
if not discord.opus.is_loaded():
discord.opus.load_opus('/usr/local/lib/libopus.so') #FreeBSD path
self.player = None
self.stopped = True
self.q = asyncio.Queue()
self.play_next_song = asyncio.Event()
self.current_song = None
copy_creds = self.load_copy_creds()
self.copycom = Copy(copy_creds['login'], copy_creds['passwd'])
self.songs = []
self.update_song_list()
def load_copy_creds(self):
with open('copy_creds.json') as f:
return json.load(f)
@property
def is_playing(self):
return self.player is not None and self.player.is_playing() and not self.stopped
def toggle_next_song(self):
if not self.stopped:
self.bot.loop.call_soon_threadsafe(self.play_next_song.set)
def update_song_list(self):
self.songs = self.copycom.list_files('radio/')
@commands.command()
async def join(self, *, channel : discord.Channel = None):
"""Join voice channel.
"""
if channel is None or channel.type is not discord.ChannelType.voice:
await self.bot.say('Cannot find a voice channel by that name. {0}'.format(channel.type))
return
await self.bot.join_voice_channel(channel)
@commands.command(pass_context=True)
async def leave(self):
"""Leave voice channel.
"""
await ctx.invoke(self.stop)
await self.bot.voice.disconnect()
@commands.command()
async def pause(self):
"""Pause.
"""
if self.player is not None:
self.player.pause()
@commands.command()
async def resume(self):
"""Resume playing.
"""
if self.player is not None and not self.is_playing():
self.player.resume()
@commands.command()
async def skip(self):
"""Skip song and play next.
"""
if self.player is not None and self.is_playing():
self.player.stop()
self.toggle_next_song()
@commands.command()
async def stop():
"""Stop playing song.
"""
if self.is_playing():
self.stopped = True
self.player.stop()
@commands.command(pass_context=True)
async def play(self, ctx):
"""Start playing song from queue.
"""
if self.player is not None:
if not self.is_playing():
await ctx.invoke(self.resume)
return
else:
await self.bot.say('Already playing a song')
return
while True:
if not self.bot.is_voice_connected():
await ctx.invoke(self.join, channel=ctx.message.author.voice_channel)
continue
if self.q.empty():
await self.q.put(random.choice(self.songs))
self.play_next_song.clear()
self.current = await self.q.get()
self.player = self.bot.voice.create_ffmpeg_player(
self.copycom.direct_link('radio/' + self.current),
after=self.toggle_next_song,
#options="-loglevel debug -report",
headers = dict(self.copycom.session.headers))
self.stopped = False
self.player.start()
fmt = 'Playing song "{0}"'
song_name = unquote(self.current.split('/')[-1])
await bot.say(fmt.format(song_name))
self.bot.change_status(discord.Game(name=song_name))
await self.play_next_song.wait()
def setup(bot):
bot.add_cog(Radio(bot))
| Python | 0.000001 |
d84a4efcf880bb668b2721af3f4ce18220e8baab | Use np.genfromtext to handle missing values | xvistaprof/reader.py | xvistaprof/reader.py | #!/usr/bin/env python
# encoding: utf-8
"""
Reader for XVISTA .prof tables.
"""
import numpy as np
from astropy.table import Table
from astropy.io import registry
def xvista_table_reader(filename):
dt = [('R', np.float), ('SB', np.float), ('SB_err', np.float),
('ELL', np.float), ('PA', np.float), ('EMAG', np.float),
('ELLMAG', np.float), ('ELLMAG_err', np.float), ('XC', np.float),
('YC', np.float), ('FRACONT', np.float), ('A1', np.float),
('A2', np.float), ('A4', np.float), ('CIRCMAG', np.float)]
data = np.genfromtxt(filename, dtype=np.dtype(dt), skiprows=15,
missing_values='*', filling_values=np.nan)
return Table(data)
registry.register_reader('xvistaprof', Table, xvista_table_reader)
| #!/usr/bin/env python
# encoding: utf-8
"""
Reader for XVISTA .prof tables.
"""
import numpy as np
from astropy.table import Table
from astropy.io import registry
def xvista_table_reader(filename):
dt = [('R', np.float), ('SB', np.float), ('SB_err', np.float),
('ELL', np.float), ('PA', np.float), ('EMAG', np.float),
('ELLMAG', np.float), ('ELLMAG_err', np.float), ('XC', np.float),
('YC', np.float), ('FRACONT', np.float), ('A1', np.float),
('A2', np.float), ('A4', np.float), ('CIRCMAG', np.float)]
data = np.loadtxt(filename, dtype=np.dtype(dt), skiprows=15)
return Table(data)
registry.register_reader('xvistaprof', Table, xvista_table_reader)
| Python | 0.000022 |
0dde9454d05a6d5533454fbac8996c560d007c67 | make a proper hook/task split in cython. | yaku/tools/cython.py | yaku/tools/cython.py | import os
import sys
from yaku.task_manager \
import \
extension, get_extension_hook
from yaku.task \
import \
Task
from yaku.compiled_fun \
import \
compile_fun
from yaku.utils \
import \
ensure_dir, find_program
import yaku.errors
@extension(".pyx")
def cython_hook(self, node):
self.sources.append(node.change_ext(".c"))
return cython_task(self, node)
def cython_task(self, node):
out = node.change_ext(".c")
target = node.parent.declare(out.name)
ensure_dir(target.name)
task = Task("cython", inputs=[node], outputs=[target])
task.gen = self
task.env_vars = []
task.env = self.env
self.env["CYTHON_INCPATH"] = ["-I%s" % p for p in
self.env["CYTHON_CPPPATH"]]
task.func = compile_fun("cython", "cython ${SRC} -o ${TGT} ${CYTHON_INCPATH}",
False)[0]
return [task]
def configure(ctx):
sys.stderr.write("Looking for cython... ")
if detect(ctx):
sys.stderr.write("yes\n")
else:
sys.stderr.write("no!\n")
raise yaku.errors.ToolNotFound()
ctx.env["CYTHON_CPPPATH"] = []
def detect(ctx):
if find_program("cython") is None:
return False
else:
return True
| import os
import sys
from yaku.task_manager \
import \
extension, get_extension_hook
from yaku.task \
import \
Task
from yaku.compiled_fun \
import \
compile_fun
from yaku.utils \
import \
ensure_dir, find_program
import yaku.errors
@extension(".pyx")
def cython_task(self, node):
out = node.change_ext(".c")
target = node.parent.declare(out.name)
ensure_dir(target.name)
task = Task("cython", inputs=[node], outputs=[target])
task.gen = self
task.env_vars = []
task.env = self.env
self.env["CYTHON_INCPATH"] = ["-I%s" % p for p in
self.env["CYTHON_CPPPATH"]]
task.func = compile_fun("cython", "cython ${SRC} -o ${TGT} ${CYTHON_INCPATH}",
False)[0]
return [task]
def configure(ctx):
sys.stderr.write("Looking for cython... ")
if detect(ctx):
sys.stderr.write("yes\n")
else:
sys.stderr.write("no!\n")
raise yaku.errors.ToolNotFound()
ctx.env["CYTHON_CPPPATH"] = []
def detect(ctx):
if find_program("cython") is None:
return False
else:
return True
| Python | 0 |
af96c316f485ebed2ad342aa2ea720d8b699f649 | bump version | ydcommon/__init__.py | ydcommon/__init__.py | """
YD Technology common libraries
"""
VERSION = (0, 1, 2)
__version__ = '.'.join((str(each) for each in VERSION[:4]))
def get_version():
"""
Returns shorter version (digit parts only) as string.
"""
version = '.'.join((str(each) for each in VERSION[:3]))
if len(VERSION) > 3:
version += str(VERSION[3])
return version
| """
YD Technology common libraries
"""
VERSION = (0, 1, 1)
__version__ = '.'.join((str(each) for each in VERSION[:4]))
def get_version():
"""
Returns shorter version (digit parts only) as string.
"""
version = '.'.join((str(each) for each in VERSION[:3]))
if len(VERSION) > 3:
version += str(VERSION[3])
return version
| Python | 0 |
de48a47cf813177e824026a994a5a814f5cc1a2d | fix socket.TCP_KEEPIDLE error on Mac OS | routeros_api/api_socket.py | routeros_api/api_socket.py | import socket
from routeros_api import exceptions
try:
import errno
except ImportError:
errno = None
EINTR = getattr(errno, 'EINTR', 4)
def get_socket(hostname, port, timeout=15.0):
api_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
api_socket.settimeout(timeout)
while True:
try:
api_socket.connect((hostname, port))
except socket.error as e:
if e.args[0] != EINTR:
raise exceptions.RouterOsApiConnectionError(e)
else:
break
set_keepalive(api_socket, after_idle_sec=10)
return SocketWrapper(api_socket)
# http://stackoverflow.com/a/14855726
def set_keepalive(sock, after_idle_sec=1, interval_sec=3, max_fails=5):
"""Set TCP keepalive on an open socket.
It activates after 1 second (after_idle_sec) of idleness,
then sends a keepalive ping once every 3 seconds (interval_sec),
and closes the connection after 5 failed ping (max_fails), or 15 seconds
"""
if hasattr(socket, "SO_KEEPALIVE"):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
if hasattr(socket, "TCP_KEEPIDLE"):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)
if hasattr(socket, "TCP_KEEPINTVL"):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)
if hasattr(socket, "TCP_KEEPCNT"):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails)
class DummySocket(object):
def close(self):
pass
def settimeout(self, timeout):
pass
class SocketWrapper(object):
def __init__(self, socket):
self.socket = socket
def send(self, bytes):
return self.socket.sendall(bytes)
def receive(self, length):
while True:
try:
return self._receive_and_check_connection(length)
except socket.error as e:
if e.args[0] == EINTR:
continue
else:
raise
def _receive_and_check_connection(self, length):
bytes = self.socket.recv(length)
if bytes:
return bytes
else:
raise exceptions.RouterOsApiConnectionClosedError
def close(self):
return self.socket.close()
def settimeout(self, timeout):
self.socket.settimeout(timeout)
| import socket
from routeros_api import exceptions
try:
import errno
except ImportError:
errno = None
EINTR = getattr(errno, 'EINTR', 4)
def get_socket(hostname, port, timeout=15.0):
api_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
api_socket.settimeout(timeout)
while True:
try:
api_socket.connect((hostname, port))
except socket.error as e:
if e.args[0] != EINTR:
raise exceptions.RouterOsApiConnectionError(e)
else:
break
set_keepalive(api_socket, after_idle_sec=10)
return SocketWrapper(api_socket)
# http://stackoverflow.com/a/14855726
def set_keepalive(sock, after_idle_sec=1, interval_sec=3, max_fails=5):
"""Set TCP keepalive on an open socket.
It activates after 1 second (after_idle_sec) of idleness,
then sends a keepalive ping once every 3 seconds (interval_sec),
and closes the connection after 5 failed ping (max_fails), or 15 seconds
"""
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails)
class DummySocket(object):
def close(self):
pass
def settimeout(self, timeout):
pass
class SocketWrapper(object):
def __init__(self, socket):
self.socket = socket
def send(self, bytes):
return self.socket.sendall(bytes)
def receive(self, length):
while True:
try:
return self._receive_and_check_connection(length)
except socket.error as e:
if e.args[0] == EINTR:
continue
else:
raise
def _receive_and_check_connection(self, length):
bytes = self.socket.recv(length)
if bytes:
return bytes
else:
raise exceptions.RouterOsApiConnectionClosedError
def close(self):
return self.socket.close()
def settimeout(self, timeout):
self.socket.settimeout(timeout)
| Python | 0 |
5a31ed001626937772a30ab46b94fe2b4bb5cfb8 | allow 2013 candidates | fecreader/summary_data/management/commands/add_candidates.py | fecreader/summary_data/management/commands/add_candidates.py | from django.core.management.base import BaseCommand, CommandError
from ftpdata.models import Candidate
from summary_data.models import Candidate_Overlay
from summary_data.utils.overlay_utils import make_candidate_overlay_from_masterfile
election_year = 2014
cycle = str(election_year)
class Command(BaseCommand):
help = "Add new candidates"
requires_model_validation = False
def handle(self, *args, **options):
candidates = Candidate.objects.filter(cycle=cycle, cand_election_year__in=[2013,2014])
# We'll miss folks who put the wrong election year in their filing, but...
for candidate in candidates:
# will doublecheck that it doesn't already exist before creating it
make_candidate_overlay_from_masterfile(candidate.cand_id, election_year=candidate.cand_election_year)
| from django.core.management.base import BaseCommand, CommandError
from ftpdata.models import Candidate
from summary_data.models import Candidate_Overlay
from summary_data.utils.overlay_utils import make_candidate_overlay_from_masterfile
election_year = 2014
cycle = str(election_year)
class Command(BaseCommand):
help = "Add new candidates"
requires_model_validation = False
def handle(self, *args, **options):
candidates = Candidate.objects.filter(cycle=cycle, cand_election_year__in=[2013,2014])
# We'll miss folks who put the wrong election year in their filing, but...
for candidate in candidates:
# will doublecheck that it doesn't already exist before creating it
make_candidate_overlay_from_masterfile(candidate.cand_id, cand_election_year=candidate.cand_election_year)
| Python | 0.000005 |
bf4a197618bf09a164f03a53cd6998bcd6ee8196 | Fix function name | google/cloud/security/common/data_access/violation_format.py | google/cloud/security/common/data_access/violation_format.py | # Copyright 2017 Google 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.
"""Provides formatting functions for violations"""
import json
def format_violation(violation):
"""Format the policy violation data into a tuple.
Also flattens the RuleViolation, since it consists of the resource,
rule, and members that don't meet the rule criteria.
Various properties of RuleViolation may also have values that exceed the
declared column length, so truncate as necessary to prevent MySQL errors.
Args:
violation (namedtuple): The Policy RuleViolation. This is a named
tumple with the following attributes 'resource_type','resource_id',
'rule_name', 'violation_type' and 'violation_data'
Yields:
tuple: A tuple of the rule violation properties.
"""
resource_type = violation.resource_type
if resource_type:
resource_type = resource_type[:255]
resource_id = violation.resource_id
if resource_id:
resource_id = str(resource_id)[:255]
rule_name = violation.rule_name
if rule_name:
rule_name = rule_name[:255]
yield (resource_type,
resource_id,
rule_name,
violation.rule_index,
violation.violation_type,
json.dumps(violation.violation_data))
def format_groups_violation(violation):
"""Format the groups violation data into a tuple.
Args:
violation (namedtuple): The groups violation. This is a named tuple
with the following attributes 'member_email','parent.member_email',
'violated_rule_names'
Yields:
tuple: A tuple of the violation properties.
"""
member_email = violation.member_email
if member_email:
member_email = member_email[:255]
group_email = violation.parent.member_email
if group_email:
group_email = group_email[:255]
violated_rule_names = json.dumps(violation.violated_rule_names)
yield (member_email,
group_email,
violated_rule_names)
| # Copyright 2017 Google 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.
"""Provides formatting functions for violations"""
import json
def format_policy_violation(violation):
"""Format the policy violation data into a tuple.
Also flattens the RuleViolation, since it consists of the resource,
rule, and members that don't meet the rule criteria.
Various properties of RuleViolation may also have values that exceed the
declared column length, so truncate as necessary to prevent MySQL errors.
Args:
violation (namedtuple): The Policy RuleViolation. This is a named
tumple with the following attributes 'resource_type','resource_id',
'rule_name', 'violation_type' and 'violation_data'
Yields:
tuple: A tuple of the rule violation properties.
"""
resource_type = violation.resource_type
if resource_type:
resource_type = resource_type[:255]
resource_id = violation.resource_id
if resource_id:
resource_id = str(resource_id)[:255]
rule_name = violation.rule_name
if rule_name:
rule_name = rule_name[:255]
yield (resource_type,
resource_id,
rule_name,
violation.rule_index,
violation.violation_type,
json.dumps(violation.violation_data))
def format_groups_violation(violation):
"""Format the groups violation data into a tuple.
Args:
violation (namedtuple): The groups violation. This is a named tuple
with the following attributes 'member_email','parent.member_email',
'violated_rule_names'
Yields:
tuple: A tuple of the violation properties.
"""
member_email = violation.member_email
if member_email:
member_email = member_email[:255]
group_email = violation.parent.member_email
if group_email:
group_email = group_email[:255]
violated_rule_names = json.dumps(violation.violated_rule_names)
yield (member_email,
group_email,
violated_rule_names)
| Python | 0.999896 |
17b9ccbcf940c653c2ee0994eefec87ca2961b75 | Fix extension scraper on Python 3.x | Release/Product/Python/PythonTools/ExtensionScraper.py | Release/Product/Python/PythonTools/ExtensionScraper.py | # ############################################################################
#
# Copyright (c) Microsoft Corporation.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of this distribution. If
# you cannot locate the Apache License, Version 2.0, please send an email to
# vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
# by the terms of the Apache License, Version 2.0.
#
# You must not remove this notice, or any other, from this software.
#
# ###########################################################################
import imp
import sys
from os import path
try:
# disable error reporting in our process, bad extension modules can crash us, and we don't
# want a bunch of Watson boxes popping up...
import ctypes
ctypes.windll.kernel32.SetErrorMode(3) # SEM_FAILCRITICALERRORS / SEM_NOGPFAULTERRORBOX
except:
pass
# Expects either:
# scrape [filename] [output_path]
# Scrapes the file and saves the analysis to the specified filename, exits w/ nonzero exit code if anything goes wrong.
if len(sys.argv) == 4:
if sys.argv[1] == 'scrape':
filename = sys.argv[2]
mod_name = path.splitext(path.basename(filename))[0]
try:
module = imp.load_dynamic(mod_name, filename)
except ImportError:
e = sys.exc_info()[1]
print e
sys.exit(1)
import PythonScraper
analysis = PythonScraper.generate_module(module)
PythonScraper.write_analysis(sys.argv[3], analysis)
| # ############################################################################
#
# Copyright (c) Microsoft Corporation.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of this distribution. If
# you cannot locate the Apache License, Version 2.0, please send an email to
# vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
# by the terms of the Apache License, Version 2.0.
#
# You must not remove this notice, or any other, from this software.
#
# ###########################################################################
import imp
import sys
from os import path
try:
# disable error reporting in our process, bad extension modules can crash us, and we don't
# want a bunch of Watson boxes popping up...
import ctypes
ctypes.windll.kernel32.SetErrorMode(3) # SEM_FAILCRITICALERRORS / SEM_NOGPFAULTERRORBOX
except:
pass
# Expects either:
# scrape [filename] [output_path]
# Scrapes the file and saves the analysis to the specified filename, exits w/ nonzero exit code if anything goes wrong.
if len(sys.argv) == 4:
if sys.argv[1] == 'scrape':
filename = sys.argv[2]
mod_name = path.splitext(path.basename(filename))[0]
try:
module = imp.load_dynamic(mod_name, filename)
except ImportError, e:
print e
sys.exit(1)
import PythonScraper
analysis = PythonScraper.generate_module(module)
PythonScraper.write_analysis(sys.argv[3], analysis)
| Python | 0.000001 |
9780274756ef4bc2966a0f8290ca28bd3c1e8163 | update dev version after 0.31.1 tag [skip ci] | py/desisim/_version.py | py/desisim/_version.py | __version__ = '0.31.1.dev1940'
| __version__ = '0.31.1'
| Python | 0 |
bc905d9d01060fdaff2765f64e810b4eb927820e | fix arcseciv typo | py/legacypipe/units.py | py/legacypipe/units.py |
def get_units_for_columns(cols, bands=[], extras=None):
deg = 'deg'
degiv = '1/deg^2'
arcsec = 'arcsec'
arcseciv = '1/arcsec^2'
flux = 'nanomaggy'
fluxiv = '1/nanomaggy^2'
pm = 'mas/yr'
pmiv = '1/(mas/yr)^2'
unitmap = dict(
ra=deg, dec=deg, ra_ivar=degiv, dec_ivar=degiv,
ebv='mag',
shape_r=arcsec,
shape_r_ivar=arcseciv)
unitmap.update(pmra=pm, pmdec=pm, pmra_ivar=pmiv, pmdec_ivar=pmiv,
parallax='mas', parallax_ivar='1/mas^2')
unitmap.update(gaia_phot_g_mean_mag='mag',
gaia_phot_bp_mean_mag='mag',
gaia_phot_rp_mean_mag='mag')
# units used in forced phot.
unitmap.update(exptime='sec',
flux=flux, flux_ivar=fluxiv,
apflux=flux, apflux_ivar=fluxiv,
psfdepth=fluxiv, galdepth=fluxiv,
sky='nanomaggy/arcsec^2',
psfsize=arcsec,
fwhm='pixels',
ccdrarms=arcsec, ccddecrms=arcsec,
skyrms='counts/sec',
dra=arcsec, ddec=arcec,
dra_ivar=arcseciv, ddec_ivar=arcseciv)
# Fields that have band suffixes
funits = dict(
flux=flux, flux_ivar=fluxiv,
apflux=flux, apflux_ivar=fluxiv, apflux_resid=flux,
apflux_blobresid=flux,
psfdepth=fluxiv, galdepth=fluxiv, psfsize=arcsec,
fiberflux=flux, fibertotflux=flux,
lc_flux=flux, lc_flux_ivar=fluxiv,
)
for b in bands:
unitmap.update([('%s_%s' % (k, b), v)
for k,v in funits.items()])
if extras is not None:
unitmap.update(extras)
# Create a list of units aligned with 'cols'
units = [unitmap.get(c, '') for c in cols]
return units
|
def get_units_for_columns(cols, bands=[], extras=None):
deg = 'deg'
degiv = '1/deg^2'
arcsec = 'arcsec'
arcseciv = '1/arcsec^2'
flux = 'nanomaggy'
fluxiv = '1/nanomaggy^2'
pm = 'mas/yr'
pmiv = '1/(mas/yr)^2'
unitmap = dict(
ra=deg, dec=deg, ra_ivar=degiv, dec_ivar=degiv,
ebv='mag',
shape_r=arcsec,
shape_r_ivar=arcsec_iv)
unitmap.update(pmra=pm, pmdec=pm, pmra_ivar=pmiv, pmdec_ivar=pmiv,
parallax='mas', parallax_ivar='1/mas^2')
unitmap.update(gaia_phot_g_mean_mag='mag',
gaia_phot_bp_mean_mag='mag',
gaia_phot_rp_mean_mag='mag')
# units used in forced phot.
unitmap.update(exptime='sec',
flux=flux, flux_ivar=fluxiv,
apflux=flux, apflux_ivar=fluxiv,
psfdepth=fluxiv, galdepth=fluxiv,
sky='nanomaggy/arcsec^2',
psfsize=arcsec,
fwhm='pixels',
ccdrarms=arcsec, ccddecrms=arcsec,
skyrms='counts/sec',
dra=arcsec, ddec=arcec,
dra_ivar=arcsec_iv, ddec_ivar=arcsec_iv)
# Fields that have band suffixes
funits = dict(
flux=flux, flux_ivar=fluxiv,
apflux=flux, apflux_ivar=fluxiv, apflux_resid=flux,
apflux_blobresid=flux,
psfdepth=fluxiv, galdepth=fluxiv, psfsize=arcsec,
fiberflux=flux, fibertotflux=flux,
lc_flux=flux, lc_flux_ivar=fluxiv,
)
for b in bands:
unitmap.update([('%s_%s' % (k, b), v)
for k,v in funits.items()])
if extras is not None:
unitmap.update(extras)
# Create a list of units aligned with 'cols'
units = [unitmap.get(c, '') for c in cols]
return units
| Python | 0.018115 |
edc13c1309d550a3acc5b833d0efedaf7be4045e | Fix several off-by-one errors in split_tex_string() and add regression tests. | pybtex/bibtex/utils.py | pybtex/bibtex/utils.py | # Copyright (C) 2007, 2008, 2009 Andrey Golovizin
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def bibtex_len(s):
"""Return the number of characters in s, taking TeX' special chars into accoount.
"""
#FIXME stub
return len(s)
def split_name_list(string):
"""
Split a list of names, separated by ' and '.
>>> split_name_list('Johnson and Peterson')
['Johnson', 'Peterson']
>>> split_name_list('Armand and Peterson')
['Armand', 'Peterson']
>>> split_name_list('Armand and anderssen')
['Armand', 'anderssen']
>>> split_name_list('What a Strange{ }and Bizzare Name! and Peterson')
['What a Strange{ }and Bizzare Name!', 'Peterson']
>>> split_name_list('What a Strange and{ }Bizzare Name! and Peterson')
['What a Strange and{ }Bizzare Name!', 'Peterson']
"""
return split_tex_string(string, ' and ')
def split_tex_string(string, sep=' ', strip=True):
"""Split a string using the given separator, ignoring separators at brace level > 0.
>>> split_tex_string('')
[]
>>> split_tex_string('a')
['a']
>>> split_tex_string('on a')
['on', 'a']
"""
brace_level = 0
name_start = 0
result = []
string_len = len(string)
sep_len = len(sep)
pos = 0
for pos, char in enumerate(string):
if char == '{':
brace_level += 1
elif char == '}':
brace_level -= 1
elif (
brace_level == 0 and
string[pos:pos + len(sep)].lower() == sep and
pos > 0 and
pos + len(sep) < string_len
):
result.append(string[name_start:pos])
name_start = pos + len(sep)
if name_start < string_len:
result.append(string[name_start:])
if strip:
return [part.strip() for part in result]
else:
return result
| # Copyright (C) 2007, 2008, 2009 Andrey Golovizin
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def bibtex_len(s):
"""Return the number of characters in s, taking TeX' special chars into accoount.
"""
#FIXME stub
return len(s)
def split_name_list(string):
"""
Split a list of names, separated by ' and '.
>>> split_name_list('Johnson and Peterson')
['Johnson', 'Peterson']
>>> split_name_list('Armand and Peterson')
['Armand', 'Peterson']
>>> split_name_list('Armand and anderssen')
['Armand', 'anderssen']
>>> split_name_list('What a Strange{ }and Bizzare Name! and Peterson')
['What a Strange{ }and Bizzare Name!', 'Peterson']
>>> split_name_list('What a Strange and{ }Bizzare Name! and Peterson')
['What a Strange and{ }Bizzare Name!', 'Peterson']
"""
return split_tex_string(string, ' and ')
def split_tex_string(string, sep=' ', strip=True):
"""Split a string using the given separator, ignoring separators at brace level > 0."""
brace_level = 0
name_start = 0
result = []
end = len(string) - 1
sep_len = len(sep)
for pos, char in enumerate(string):
if char == '{':
brace_level += 1
elif char == '}':
brace_level -= 1
elif (
brace_level == 0 and
string[pos:pos + len(sep)].lower() == sep and
pos > 0 and
pos + len(sep) < end
):
result.append(string[name_start:pos])
name_start = pos + len(sep)
result.append(string[name_start:])
if strip:
return [part.strip() for part in result]
else:
return result
| Python | 0 |
d883d551f74bbfa0c0ee0db6b94aa98a3af41fca | Expanded NUMERIC_MISSING_VALUES to have 64 values | pybufrkit/constants.py | pybufrkit/constants.py | """
pybufrkit.constants
~~~~~~~~~~~~~~~~~~~
Various constants used in the module.
"""
from __future__ import absolute_import
from __future__ import print_function
import sys
import os
# Set the base directory accordingly for PyInstaller
# noinspection PyUnresolvedReferences,PyProtectedMember
BASE_DIR = sys._MEIPASS if getattr(sys, 'frozen', False) else os.path.dirname(__file__)
# Default directory to read the definition JSON files
DEFAULT_DEFINITIONS_DIR = os.path.join(BASE_DIR, 'definitions')
# Default directory to load the BUFR tables
DEFAULT_TABLES_DIR = os.path.join(BASE_DIR, 'tables')
NBITS_PER_BYTE = 8
MESSAGE_START_SIGNATURE = b'BUFR'
MESSAGE_STOP_SIGNATURE = b'7777'
PARAMETER_TYPE_UNEXPANDED_DESCRIPTORS = 'unexpanded_descriptors'
PARAMETER_TYPE_TEMPLATE_DATA = 'template_data'
BITPOS_START = 'bitpos_start'
# A list of numbers that corresponds to missing values for a number of bits up to 64
NUMERIC_MISSING_VALUES = [2 ** i - 1 for i in range(65)]
# Number of bits for represent number of bits used for difference
NBITS_FOR_NBITS_DIFF = 6
UNITS_STRING = 'CCITT IA5'
UNITS_FLAG_TABLE = 'FLAG TABLE'
UNITS_CODE_TABLE = 'CODE TABLE'
UNITS_COMMON_CODE_TABLE_C1 = 'Common CODE TABLE C-1'
INDENT_CHARS = ' '
| """
pybufrkit.constants
~~~~~~~~~~~~~~~~~~~
Various constants used in the module.
"""
from __future__ import absolute_import
from __future__ import print_function
import sys
import os
# Set the base directory accordingly for PyInstaller
# noinspection PyUnresolvedReferences,PyProtectedMember
BASE_DIR = sys._MEIPASS if getattr(sys, 'frozen', False) else os.path.dirname(__file__)
# Default directory to read the definition JSON files
DEFAULT_DEFINITIONS_DIR = os.path.join(BASE_DIR, 'definitions')
# Default directory to load the BUFR tables
DEFAULT_TABLES_DIR = os.path.join(BASE_DIR, 'tables')
NBITS_PER_BYTE = 8
MESSAGE_START_SIGNATURE = b'BUFR'
MESSAGE_STOP_SIGNATURE = b'7777'
PARAMETER_TYPE_UNEXPANDED_DESCRIPTORS = 'unexpanded_descriptors'
PARAMETER_TYPE_TEMPLATE_DATA = 'template_data'
BITPOS_START = 'bitpos_start'
# A list of numbers that corresponds to missing values for a number of bits up to 32
NUMERIC_MISSING_VALUES = [2 ** i - 1 for i in range(33)]
# Number of bits for represent number of bits used for difference
NBITS_FOR_NBITS_DIFF = 6
UNITS_STRING = 'CCITT IA5'
UNITS_FLAG_TABLE = 'FLAG TABLE'
UNITS_CODE_TABLE = 'CODE TABLE'
UNITS_COMMON_CODE_TABLE_C1 = 'Common CODE TABLE C-1'
INDENT_CHARS = ' '
| Python | 0.999172 |
a1dd37c9127501ad440c7777d14fb28b1b59b85b | Add list guests function | characters.py | characters.py | from adventurelib import Item, Bag, when
class Man(Item):
subject_pronoun = 'he'
object_pronoun = 'him'
class Woman(Item):
subject_pronoun = 'she'
object_pronoun = 'her'
dr_black = the_victim = Man('Dr. Black', 'Dr Black', 'the victim')
dr_black.def_name = 'the victim'
dr_black.description = """\
Dr. Black was the much beloved host and owner of Albermore Manor. His untimely
death has come as a shock and surprise to most of tonight's guests."""
miss_scarlet = Woman('Miss Scarlet')
miss_scarlet.def_name = 'Miss Scarlet'
miss_scarlet.description = """\
Miss Scarlet is well liked by the younger gentlemen at tonight's gathering.
She is mistrusted by some and seems to have quite the salacious reputation."""
col_mustard = Man('Colonel Mustard', 'Col. Mustard', 'Col Mustard')
col_mustard.def_name = 'Colonel Mustard'
col_mustard.description = """\
The Colonel is a stern man who accepts no "nonsense". His long and esteemed
military career has left him with"""
mrs_white = Woman('Mrs. White', 'Mrs White')
mrs_white.def_name = 'Mrs. White'
rev_green = Man(
'Reverend Green', 'Rev. Green', 'Rev Green', 'Mr. Green', 'Mr Green')
rev_green.def_name = 'Reverend Green'
mrs_peacock = Woman('Mrs. Peacock', 'Mrs Peacock')
mrs_peacock.def_name = 'Mrs. Peacock'
prof_plum = Man('Professor Plum', 'Prof. Plum', 'Prof Plum')
prof_plum.def_name = 'Prefessor Plum'
guests = Bag([
miss_scarlet, col_mustard, mrs_white, rev_green, mrs_peacock, prof_plum
])
@when('list guests')
def list_rooms():
print("A nearby guest list for tonight's gathering has the following names:")
for c in guests:
print(c)
if __name__ == '__main__':
assert prof_plum == guests.find('Prof. Plum')
assert prof_plum != guests.find('Plum')
| from adventurelib import Item, Bag
class Man(Item):
subject_pronoun = 'he'
object_pronoun = 'him'
class Woman(Item):
subject_pronoun = 'she'
object_pronoun = 'her'
dr_black = the_victim = Man('Dr. Black', 'Dr Black', 'the victim')
dr_black.def_name = 'the victim'
dr_black.description = """\
Dr. Black was the much beloved host and owner of Tudor Close. His untimely
death has come as a shock and surprise to most of tonight's guests."""
miss_scarlet = Woman('Miss Scarlet')
miss_scarlet.def_name = 'Miss Scarlet'
miss_scarlet.description = """\
Miss Scarlet is well liked by the younger gentlemen at tonight's gathering.
She is mistrusted by some and seems to have quite the salacious reputation."""
col_mustard = Man('Colonel Mustard', 'Col. Mustard', 'Col Mustard')
col_mustard.def_name = 'Colonel Mustard'
col_mustard.description = """\
The Colonel is a stern man who accepts no "nonsense". His long and esteemed
military career has left him with"""
mrs_white = Woman('Mrs. White', 'Mrs White')
mrs_white.def_name = 'Mrs. White'
rev_green = Man(
'Reverend Green', 'Rev. Green', 'Rev Green', 'Mr. Green', 'Mr Green')
rev_green.def_name = 'Reverend Green'
mrs_peacock = Woman('Mrs. Peacock', 'Mrs Peacock')
mrs_peacock.def_name = 'Mrs. Peacock'
prof_plum = Man('Professor Plum', 'Prof. Plum', 'Prof Plum')
prof_plum.def_name = 'Prefessor Plum'
everyone = Bag([
miss_scarlet, col_mustard, mrs_white, rev_green, mrs_peacock, prof_plum
])
if __name__ == '__main__':
assert prof_plum == everyone.find('Prof. Plum')
assert prof_plum != everyone.find('Plum')
| Python | 0 |
02ebf235704ea6c61969a20ff86717c796dd5e06 | Fix typo: get_destination_queues should be get_queue | queue_util/consumer.py | queue_util/consumer.py | """Listens to 1 (just one!) queue and consumes messages from it endlessly.
We set up a consumer with two things:
1) The name of the source queue (`source_queue_name`)
2) A callable that will process
The `handle_data` method must process the data. It can return nothing or a
sequence of `queue_name, data` pairs.
If it returns the latter, then the data will be sent to the given `queue_name`.
e.g.
def handle_data(data):
new_data = do_some_calc(data)
# Forward the new_data to another queue.
#
yield ("next_target", new_data)
"""
import logging
import kombu
class Consumer(object):
def __init__(self, source_queue_name, handle_data, rabbitmq_host, serializer=None, compression=None):
self.serializer = serializer
self.compression = compression
self.queue_cache = {}
# Connect to the source queue.
#
self.broker = kombu.BrokerConnection(rabbitmq_host)
self.source_queue = self.get_queue(source_queue_name, serializer=serializer, compression=compression)
# The handle_data method will be applied to each item in the queue.
#
self.handle_data = handle_data
def get_queue(self, queue_name, serializer=None, compression=None):
kwargs = {}
# Use 'defaults' if no args were supplied for serializer/compression.
#
serializer = serializer or self.serializer
if serializer:
kwargs["serializer"] = serializer
compression = compression or self.compression
if compression:
kwargs["compression"] = compression
# The cache key is the name and connection args.
# This is so that (if needed) a fresh connection can be made with
# different serializer/compression args.
#
cache_key = (queue_name, serializer, compression,)
if cache_key not in self.queue_cache:
self.queue_cache[cache_key] = self.broker.SimpleQueue(queue_name, **kwargs)
return self.queue_cache[cache_key]
def run_forever(self):
"""Keep running (unless we get a Ctrl-C).
"""
while True:
try:
message = self.source_queue.get(block=True)
data = message.payload
new_messages = self.handle_data(data)
except KeyboardInterrupt:
logging.info("Caught Ctrl-C. Byee!")
# Break out of our loop.
#
break
else:
# Queue up the new messages (if any).
#
if new_messages:
for queue_name, data in new_messages:
destination_queue = self.get_queue(queue_name)
destination_queue.put(data)
# We're done with the original message.
#
message.ack()
| """Listens to 1 (just one!) queue and consumes messages from it endlessly.
We set up a consumer with two things:
1) The name of the source queue (`source_queue_name`)
2) A callable that will process
The `handle_data` method must process the data. It can return nothing or a
sequence of `queue_name, data` pairs.
If it returns the latter, then the data will be sent to the given `queue_name`.
e.g.
def handle_data(data):
new_data = do_some_calc(data)
# Forward the new_data to another queue.
#
yield ("next_target", new_data)
"""
import logging
import kombu
class Consumer(object):
def __init__(self, source_queue_name, handle_data, rabbitmq_host, serializer=None, compression=None):
self.serializer = serializer
self.compression = compression
self.queue_cache = {}
# Connect to the source queue.
#
self.broker = kombu.BrokerConnection(rabbitmq_host)
self.source_queue = self.get_queue(source_queue_name, serializer=serializer, compression=compression)
# The handle_data method will be applied to each item in the queue.
#
self.handle_data = handle_data
def get_queue(self, queue_name, serializer=None, compression=None):
kwargs = {}
# Use 'defaults' if no args were supplied for serializer/compression.
#
serializer = serializer or self.serializer
if serializer:
kwargs["serializer"] = serializer
compression = compression or self.compression
if compression:
kwargs["compression"] = compression
# The cache key is the name and connection args.
# This is so that (if needed) a fresh connection can be made with
# different serializer/compression args.
#
cache_key = (queue_name, serializer, compression,)
if cache_key not in self.queue_cache:
self.queue_cache[cache_key] = self.broker.SimpleQueue(queue_name, **kwargs)
return self.queue_cache[cache_key]
def run_forever(self):
"""Keep running (unless we get a Ctrl-C).
"""
while True:
try:
message = self.source_queue.get(block=True)
data = message.payload
new_messages = self.handle_data(data)
except KeyboardInterrupt:
logging.info("Caught Ctrl-C. Byee!")
# Break out of our loop.
#
break
else:
# Queue up the new messages (if any).
#
if new_messages:
for queue_name, data in new_messages:
destination_queue = self.get_destination_queues(queue_name)
destination_queue.put(data)
# We're done with the original message.
#
message.ack()
| Python | 0.999999 |
919d67e6f46d4f991cc5caa5893beebfe94e0d9e | Add hash mock | cli/crypto.py | cli/crypto.py | from ctypes import *
import base64
import os
def generate_hex_sstr():
publicKey64 = "Not implemente"
privateKey64 = "Not implemente"
return (publicKey64,privateKey64)
def hash(msg):
return "Not implemente" | from ctypes import *
import base64
import os
def generate_hex_sstr():
publicKey64 = "Not implemente"
privateKey64 = "Not implemente"
return (publicKey64,privateKey64)
| Python | 0.000004 |
d262bcf59c9779a387e9f7d213030c958b85d891 | fix sur les phrase | sara_flexbe_states/src/sara_flexbe_states/StoryboardSetStoryKey.py | sara_flexbe_states/src/sara_flexbe_states/StoryboardSetStoryKey.py | #!/usr/bin/env python
from flexbe_core import EventState, Logger
import rospy
from vizbox.msg import Story
class StoryboardSetStoryFromAction(EventState):
"""
set_story
-- titre string the title
-- actionList string[][] the steps
<= done what's suppose to be written is written
"""
def __init__(self):
"""set the story"""
super(StoryboardSetStoryFromAction, self).__init__(outcomes=['done'], input_keys=['titre', 'actionList'])
self.pub = rospy.Publisher("/story", Story)
def execute(self, userdata):
"""execute what needs to be executed"""
self.msg = Story()
self.msg.title = userdata.titre
story = []
for action in userdata.actionList:
print(action[0].lower())
if action[0].lower() == "move":
story.append("Move to the "+action[1])
elif action[0].lower() == "find":
story.append("Find the " + action[1])
elif action[0].lower() == "findPerson":
if action[1] == "":
story.append("Find a person")
else
story.append("Find " + action[1])
elif action[0].lower() == "guide":
story.append("Guide to " + action[1])
elif action[0].lower() == "pick":
story.append("Pick the " + action[1])
elif action[0].lower() == "give":
if action[1] == "":
story.append("Give to a person")
else
story.append("Give to " + action[1])
elif action[0].lower() == "say":
story.append("Talk")
elif action[0].lower() == "ask":
story.append("Ask a question")
elif action[0].lower() == "follow":
story.append("Follow " + action[1])
elif action[0].lower() == "count":
story.append("Count the number of " + action[1])
elif action[0].lower() == "place":
story.append("Place on the " + action[1])
elif action[0].lower() == "answer":
story.append("Answer a question")
else:
print("nothing")
print( str(story))
self.msg.storyline = story
self.pub.publish(self.msg)
Logger.loginfo('Success to publish the story')
return 'done'
| #!/usr/bin/env python
from flexbe_core import EventState, Logger
import rospy
from vizbox.msg import Story
class StoryboardSetStoryFromAction(EventState):
"""
set_story
-- titre string the title
-- actionList string[][] the steps
<= done what's suppose to be written is written
"""
def __init__(self):
"""set the story"""
super(StoryboardSetStoryFromAction, self).__init__(outcomes=['done'], input_keys=['titre', 'actionList'])
self.pub = rospy.Publisher("/story", Story)
def execute(self, userdata):
"""execute what needs to be executed"""
self.msg = Story()
self.msg.title = userdata.titre
story = []
for action in userdata.actionList:
print(action[0].lower())
if action[0].lower() == "move":
story.append("Move to the "+action[1])
elif action[0].lower() == "find":
story.append("Find the " + action[1])
elif action[0].lower() == "findPerson":
story.append("Find " + action[1])
elif action[0].lower() == "guide":
story.append("Guide to " + action[1])
elif action[0].lower() == "pick":
story.append("Pick the " + action[1])
elif action[0].lower() == "give":
story.append("Give to " + action[1])
elif action[0].lower() == "say":
story.append("Say something")
elif action[0].lower() == "ask":
story.append("Ask a question")
elif action[0].lower() == "follow":
story.append("Follow " + action[1])
elif action[0].lower() == "count":
story.append("Count the number of " + action[1])
elif action[0].lower() == "place":
story.append("Place on the " + action[1])
elif action[0].lower() == "answer":
story.append("Answer a question")
else:
print("nothing")
print( str(story))
self.msg.storyline = story
self.pub.publish(self.msg)
Logger.loginfo('Success to publish the story')
return 'done'
| Python | 0.007946 |
73873d47de67be9ab2b954c2a14c58fb3423fb3b | remove unused imports | txdarn/resources/support.py | txdarn/resources/support.py | import hashlib
import datetime
import functools
import pkgutil
import eliot
from twisted.web import resource, template, http
from .. import encoding, compat
from . import headers
DEFAULT_CACHEABLE_POLICY = headers.CachePolicy(
cacheDirectives=(headers.PUBLIC,
headers.MAX_AGE(headers.ONE_YEAR)),
expiresOffset=headers.ONE_YEAR)
DEFAULT_UNCACHEABLE_POLICY = headers.CachePolicy(
cacheDirectives=(headers.NO_STORE,
headers.NO_CACHE(),
headers.MUST_REVALIDATE,
headers.MAX_AGE(0)),
expiresOffset=None)
class SlashIgnoringResource(resource.Resource):
def getChild(self, name, request):
if not (name or request.postpath):
return self
return resource.Resource.getChild(self, name, request)
class PolicyApplyingResource(resource.Resource):
def __init__(self, policies):
self.policies = policies
def applyPolicies(self, request):
for policy in self.policies:
request = policy.apply(request)
return request
class Greeting(SlashIgnoringResource):
@encoding.contentType(b'text/plain')
def render_GET(self, request):
return b'Welcome to SockJS!\n'
class IFrameElement(template.Element):
loader = template.XMLString(pkgutil.get_data('txdarn',
'content/iframe.xml'))
def __init__(self, sockJSURL):
self.sockJSURL = sockJSURL
@template.renderer
def sockjsLocation(self, request, tag):
tag.attributes[b'src'] = self.sockJSURL
return tag(b'')
# we have to manually insert these two attributes because
# twisted.template (predictably) does not maintain attribute
# order. unfortunately, the official sockjs-protocol test does a
# simple regex match against this page and so expects these to be
# a specific order. tag.attributes is an OrderedDict, so exploit
# that here to enforce attribute ordering.
@template.renderer
def xUACompatible(self, request, tag):
tag.attributes[b'http-equiv'] = b'X-UA-Compatible'
tag.attributes[b'content'] = b'IE=edge'
return tag()
@template.renderer
def contentType(self, request, tag):
tag.attributes[b'http-equiv'] = b'Content-Type'
tag.attributes[b'content'] = b'text/html; charset=UTF-8'
return tag()
class IFrameResource(PolicyApplyingResource):
iframe = None
etag = None
doctype = b'<!DOCTYPE html>'
def __init__(self,
sockJSURL,
policies=(DEFAULT_CACHEABLE_POLICY,
headers.AccessControlPolicy(methods=(b'GET',
b'OPTIONS'),
maxAge=2000000)),
_render=functools.partial(template.flattenString,
request=None)):
PolicyApplyingResource.__init__(self, policies)
self.element = IFrameElement(sockJSURL)
renderingDeferred = _render(root=self.element)
def _cbSetTemplate(iframe):
self.iframe = b'\n'.join([self.doctype, iframe])
renderingDeferred.addCallback(_cbSetTemplate)
renderingDeferred.addErrback(eliot.writeFailure)
if not self.iframe:
raise RuntimeError("Could not render iframe!")
hashed = hashlib.sha256(self.iframe).hexdigest()
self.etag = compat.networkString(hashed)
@encoding.contentType(b'text/html')
def render_GET(self, request):
if request.setETag(self.etag) is http.CACHED:
return b''
request = self.applyPolicies(request)
return self.iframe
class InfoResource(PolicyApplyingResource, SlashIgnoringResource):
def __init__(self,
policies=(DEFAULT_CACHEABLE_POLICY,
headers.AccessControlPolicy(methods=(b'GET',
b'OPTIONS'),
maxAge=2000000)),
_render=compat.asJSON,
_now=datetime.datetime.utcnow):
PolicyApplyingResource.__init__(self, policies)
self._render = _render
self._now = _now
@encoding.contentType(b'application/json')
def render_GET(self, request):
self._render({})
| import hashlib
import datetime
import functools
import pkgutil
from wsgiref.handlers import format_date_time
import eliot
from twisted.web import resource, template, http
from twisted.python.constants import Names, ValueConstant
from .. import encoding, compat
from . import headers
DEFAULT_CACHEABLE_POLICY = headers.CachePolicy(
cacheDirectives=(headers.PUBLIC,
headers.MAX_AGE(headers.ONE_YEAR)),
expiresOffset=headers.ONE_YEAR)
DEFAULT_UNCACHEABLE_POLICY = headers.CachePolicy(
cacheDirectives=(headers.NO_STORE,
headers.NO_CACHE(),
headers.MUST_REVALIDATE,
headers.MAX_AGE(0)),
expiresOffset=None)
class SlashIgnoringResource(resource.Resource):
def getChild(self, name, request):
if not (name or request.postpath):
return self
return resource.Resource.getChild(self, name, request)
class PolicyApplyingResource(resource.Resource):
def __init__(self, policies):
self.policies = policies
def applyPolicies(self, request):
for policy in self.policies:
request = policy.apply(request)
return request
class Greeting(SlashIgnoringResource):
@encoding.contentType(b'text/plain')
def render_GET(self, request):
return b'Welcome to SockJS!\n'
class IFrameElement(template.Element):
loader = template.XMLString(pkgutil.get_data('txdarn',
'content/iframe.xml'))
def __init__(self, sockJSURL):
self.sockJSURL = sockJSURL
@template.renderer
def sockjsLocation(self, request, tag):
tag.attributes[b'src'] = self.sockJSURL
return tag(b'')
# we have to manually insert these two attributes because
# twisted.template (predictably) does not maintain attribute
# order. unfortunately, the official sockjs-protocol test does a
# simple regex match against this page and so expects these to be
# a specific order. tag.attributes is an OrderedDict, so exploit
# that here to enforce attribute ordering.
@template.renderer
def xUACompatible(self, request, tag):
tag.attributes[b'http-equiv'] = b'X-UA-Compatible'
tag.attributes[b'content'] = b'IE=edge'
return tag()
@template.renderer
def contentType(self, request, tag):
tag.attributes[b'http-equiv'] = b'Content-Type'
tag.attributes[b'content'] = b'text/html; charset=UTF-8'
return tag()
class IFrameResource(PolicyApplyingResource):
iframe = None
etag = None
doctype = b'<!DOCTYPE html>'
def __init__(self,
sockJSURL,
policies=(DEFAULT_CACHEABLE_POLICY,
headers.AccessControlPolicy(methods=(b'GET',
b'OPTIONS'),
maxAge=2000000)),
_render=functools.partial(template.flattenString,
request=None)):
PolicyApplyingResource.__init__(self, policies)
self.element = IFrameElement(sockJSURL)
renderingDeferred = _render(root=self.element)
def _cbSetTemplate(iframe):
self.iframe = b'\n'.join([self.doctype, iframe])
renderingDeferred.addCallback(_cbSetTemplate)
renderingDeferred.addErrback(eliot.writeFailure)
if not self.iframe:
raise RuntimeError("Could not render iframe!")
hashed = hashlib.sha256(self.iframe).hexdigest()
self.etag = compat.networkString(hashed)
@encoding.contentType(b'text/html')
def render_GET(self, request):
if request.setETag(self.etag) is http.CACHED:
return b''
request = self.applyPolicies(request)
return self.iframe
class InfoResource(PolicyApplyingResource, SlashIgnoringResource):
def __init__(self,
policies=(DEFAULT_CACHEABLE_POLICY,
headers.AccessControlPolicy(methods=(b'GET',
b'OPTIONS'),
maxAge=2000000)),
_render=compat.asJSON,
_now=datetime.datetime.utcnow):
PolicyApplyingResource.__init__(self, policies)
self._render = _render
self._now = _now
@encoding.contentType(b'application/json')
def render_GET(self, request):
self._render({})
| Python | 0.000001 |
747013feb65b7c9621234a4f2c808b00f0e6787f | Fix config passing when master pillar is turned off | salt/transport/__init__.py | salt/transport/__init__.py | # -*- coding: utf-8 -*-
'''
Encapsulate the different transports available to Salt. Currently this is only ZeroMQ.
'''
import salt.payload
import salt.auth
class Channel(object):
@staticmethod
def factory(opts, **kwargs):
# Default to ZeroMQ for now
ttype = 'zeromq'
if 'transport_type' in opts:
ttype = opts['transport_type']
elif 'transport_type' in opts.get('pillar', {}).get('master', {}):
ttype = opts['pillar']['master']['transport_type']
if ttype == 'zeromq':
return ZeroMQChannel(opts, **kwargs)
else:
raise Exception("Channels are only defined for ZeroMQ")
# return NewKindOfChannel(opts, **kwargs)
class ZeroMQChannel(Channel):
'''
Encapsulate sending routines to ZeroMQ.
ZMQ Channels default to 'crypt=aes'
'''
def __init__(self, opts, **kwargs):
self.opts = opts
# crypt defaults to 'aes'
self.crypt = kwargs['crypt'] if 'crypt' in kwargs else 'aes'
self.serial = salt.payload.Serial(opts)
if self.crypt != 'clear':
self.auth = salt.crypt.SAuth(opts)
if 'master_uri' in kwargs:
master_uri = kwargs['master_uri']
else:
master_uri = opts['master_uri']
self.sreq = salt.payload.SREQ(master_uri)
def crypted_transfer_decode_dictentry(self, load, dictkey=None, tries=3, timeout=60):
ret = self.sreq.send('aes', self.auth.crypticle.dumps(load), tries, timeout)
key = self.auth.get_keys()
aes = key.private_decrypt(ret['key'], 4)
pcrypt = salt.crypt.Crypticle(self.opts, aes)
return pcrypt.loads(ret[dictkey])
def _crypted_transfer(self, load, tries=3, timeout=60):
'''
In case of authentication errors, try to renegotiate authentication
and retry the method.
Indeed, we can fail too early in case of a master restart during a
minion state execution call
'''
def _do_transfer():
return self.auth.crypticle.loads(
self.sreq.send(self.crypt,
self.auth.crypticle.dumps(load),
tries,
timeout)
)
try:
return _do_transfer()
except salt.crypt.AuthenticationError:
self.auth = salt.crypt.SAuth(self.opts)
return _do_transfer()
def _uncrypted_transfer(self, load, tries=3, timeout=60):
return self.sreq.send(self.crypt, load, tries, timeout)
def send(self, load, tries=3, timeout=60):
if self.crypt != 'clear':
return self._crypted_transfer(load, tries, timeout)
else:
return self._uncrypted_transfer(load, tries, timeout)
# Do we ever do non-crypted transfers?
| # -*- coding: utf-8 -*-
'''
Encapsulate the different transports available to Salt. Currently this is only ZeroMQ.
'''
import salt.payload
import salt.auth
class Channel(object):
@staticmethod
def factory(opts, **kwargs):
# Default to ZeroMQ for now
ttype = 'zeromq'
if 'transport_type' in opts:
ttype = opts['transport_type']
elif 'transport_type' in opts['pillar']['master']:
ttype = opts['pillar']['master']['transport_type']
if ttype == 'zeromq':
return ZeroMQChannel(opts, **kwargs)
else:
raise Exception("Channels are only defined for ZeroMQ")
# return NewKindOfChannel(opts, **kwargs)
class ZeroMQChannel(Channel):
'''
Encapsulate sending routines to ZeroMQ.
ZMQ Channels default to 'crypt=aes'
'''
def __init__(self, opts, **kwargs):
self.opts = opts
# crypt defaults to 'aes'
self.crypt = kwargs['crypt'] if 'crypt' in kwargs else 'aes'
self.serial = salt.payload.Serial(opts)
if self.crypt != 'clear':
self.auth = salt.crypt.SAuth(opts)
if 'master_uri' in kwargs:
master_uri = kwargs['master_uri']
else:
master_uri = opts['master_uri']
self.sreq = salt.payload.SREQ(master_uri)
def crypted_transfer_decode_dictentry(self, load, dictkey=None, tries=3, timeout=60):
ret = self.sreq.send('aes', self.auth.crypticle.dumps(load), tries, timeout)
key = self.auth.get_keys()
aes = key.private_decrypt(ret['key'], 4)
pcrypt = salt.crypt.Crypticle(self.opts, aes)
return pcrypt.loads(ret[dictkey])
def _crypted_transfer(self, load, tries=3, timeout=60):
'''
In case of authentication errors, try to renegotiate authentication
and retry the method.
Indeed, we can fail too early in case of a master restart during a
minion state execution call
'''
def _do_transfer():
return self.auth.crypticle.loads(
self.sreq.send(self.crypt,
self.auth.crypticle.dumps(load),
tries,
timeout)
)
try:
return _do_transfer()
except salt.crypt.AuthenticationError:
self.auth = salt.crypt.SAuth(self.opts)
return _do_transfer()
def _uncrypted_transfer(self, load, tries=3, timeout=60):
return self.sreq.send(self.crypt, load, tries, timeout)
def send(self, load, tries=3, timeout=60):
if self.crypt != 'clear':
return self._crypted_transfer(load, tries, timeout)
else:
return self._uncrypted_transfer(load, tries, timeout)
# Do we ever do non-crypted transfers?
| Python | 0 |
2159a35811cac75b0c68677fc41443aa8eac6e5b | Stop conn_join from overriding channel restrictions | txircd/modules/conn_join.py | txircd/modules/conn_join.py | from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.handleCommand("JOIN", None, [channel])
return True
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.conn_join = None
def spawn(self):
self.conn_join = Autojoin().hook(self.ircd)
return {
"actions": {
"welcome": self.conn_join.joinOnConnect
}
} | from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel))
return True
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.conn_join = None
def spawn(self):
self.conn_join = Autojoin().hook(self.ircd)
return {
"actions": {
"welcome": self.conn_join.joinOnConnect
}
} | Python | 0 |
493e48ddb52889fcb282b7747e0f5a9c2b541005 | Remove internal variables/properties with the reserved words | salt/utils/asynchronous.py | salt/utils/asynchronous.py | # -*- coding: utf-8 -*-
'''
Helpers/utils for working with tornado asynchronous stuff
'''
from __future__ import absolute_import, print_function, unicode_literals
import tornado.ioloop
import tornado.concurrent
import contextlib
from salt.utils import zeromq
@contextlib.contextmanager
def current_ioloop(io_loop):
'''
A context manager that will set the current ioloop to io_loop for the context
'''
orig_loop = tornado.ioloop.IOLoop.current()
io_loop.make_current()
try:
yield
finally:
orig_loop.make_current()
class SyncWrapper(object):
'''
A wrapper to make Async classes synchronous
This is uses as a simple wrapper, for example:
asynchronous = AsyncClass()
# this method would reguarly return a future
future = asynchronous.async_method()
sync = SyncWrapper(async_factory_method, (arg1, arg2), {'kwarg1': 'val'})
# the sync wrapper will automatically wait on the future
ret = sync.async_method()
'''
def __init__(self, method, args=tuple(), kwargs=None):
if kwargs is None:
kwargs = {}
self.io_loop = zeromq.ZMQDefaultLoop()
kwargs['io_loop'] = self.io_loop
with current_ioloop(self.io_loop):
self.asynchronous = method(*args, **kwargs)
def __getattribute__(self, key):
try:
return object.__getattribute__(self, key)
except AttributeError as ex:
if key == 'asynchronous':
raise ex
attr = getattr(self.asynchronous, key)
if hasattr(attr, '__call__'):
def wrap(*args, **kwargs):
# Overload the ioloop for the func call-- since it might call .current()
with current_ioloop(self.io_loop):
ret = attr(*args, **kwargs)
if isinstance(ret, tornado.concurrent.Future):
ret = self._block_future(ret)
return ret
return wrap
else:
return attr
def _block_future(self, future):
self.io_loop.add_future(future, lambda future: self.io_loop.stop())
self.io_loop.start()
return future.result()
def __del__(self):
'''
On deletion of the asynchronous wrapper, make sure to clean up the asynchronous stuff
'''
if hasattr(self, 'asynchronous'):
if hasattr(self.asynchronous, 'close'):
# Certain things such as streams should be closed before
# their associated io_loop is closed to allow for proper
# cleanup.
self.asynchronous.close()
del self.asynchronous
self.io_loop.close()
del self.io_loop
elif hasattr(self, 'io_loop'):
self.io_loop.close()
del self.io_loop
| # -*- coding: utf-8 -*-
'''
Helpers/utils for working with tornado async stuff
'''
from __future__ import absolute_import, print_function, unicode_literals
import tornado.ioloop
import tornado.concurrent
import contextlib
from salt.utils import zeromq
@contextlib.contextmanager
def current_ioloop(io_loop):
'''
A context manager that will set the current ioloop to io_loop for the context
'''
orig_loop = tornado.ioloop.IOLoop.current()
io_loop.make_current()
try:
yield
finally:
orig_loop.make_current()
class SyncWrapper(object):
'''
A wrapper to make Async classes synchronous
This is uses as a simple wrapper, for example:
async = AsyncClass()
# this method would reguarly return a future
future = async.async_method()
sync = SyncWrapper(async_factory_method, (arg1, arg2), {'kwarg1': 'val'})
# the sync wrapper will automatically wait on the future
ret = sync.async_method()
'''
def __init__(self, method, args=tuple(), kwargs=None):
if kwargs is None:
kwargs = {}
self.io_loop = zeromq.ZMQDefaultLoop()
kwargs['io_loop'] = self.io_loop
with current_ioloop(self.io_loop):
self.async = method(*args, **kwargs)
def __getattribute__(self, key):
try:
return object.__getattribute__(self, key)
except AttributeError as ex:
if key == 'async':
raise ex
attr = getattr(self.async, key)
if hasattr(attr, '__call__'):
def wrap(*args, **kwargs):
# Overload the ioloop for the func call-- since it might call .current()
with current_ioloop(self.io_loop):
ret = attr(*args, **kwargs)
if isinstance(ret, tornado.concurrent.Future):
ret = self._block_future(ret)
return ret
return wrap
else:
return attr
def _block_future(self, future):
self.io_loop.add_future(future, lambda future: self.io_loop.stop())
self.io_loop.start()
return future.result()
def __del__(self):
'''
On deletion of the async wrapper, make sure to clean up the async stuff
'''
if hasattr(self, 'async'):
if hasattr(self.async, 'close'):
# Certain things such as streams should be closed before
# their associated io_loop is closed to allow for proper
# cleanup.
self.async.close()
del self.async
self.io_loop.close()
del self.io_loop
elif hasattr(self, 'io_loop'):
self.io_loop.close()
del self.io_loop
| Python | 0.000001 |
142538049bd1bf8ae92c80060435965104ec54bb | Add ability to use the pattern ((args, kwargs), callable) when specifying schema | scrapi/base/transformer.py | scrapi/base/transformer.py | from __future__ import unicode_literals
import abc
import logging
logger = logging.getLogger(__name__)
class BaseTransformer(object):
__metaclass__ = abc.ABCMeta
def transform(self, doc):
return self._transform(self.schema, doc)
def _transform(self, schema, doc):
transformed = {}
for key, value in schema.items():
if isinstance(value, dict):
transformed[key] = self._transform(value, doc)
elif isinstance(value, list) or isinstance(value, tuple):
transformed[key] = self._transform_iter(value, doc)
elif isinstance(value, basestring):
transformed[key] = self._transform_string(value, doc)
return transformed
def _transform_iter(self, l, doc):
docs = []
if isinstance(l[0], tuple) and len(l) == 2:
return self._transform_arg_kwargs(l, doc)
for value in l:
if isinstance(value, basestring):
docs.append(self._transform_string(value, doc))
elif callable(value):
return value(*[res for res in docs])
def _transform_arg_kwargs(self, l, doc):
if len(l[0]) == 1:
if isinstance(l[0][0], dict):
kwargs = l[0][0]
args = []
elif isinstance(l[0][0], tuple) or isinstance(l[0][0], list):
args = l[0][0]
kwargs = {}
else:
raise ValueError("((args, kwargs), callable) pattern not matched, {} does not define args or kwargs correctly".format(l))
else:
args = l[0][0]
kwargs = l[0][1]
fn = l[1]
return fn(
*[self._transform_string(arg, doc) for arg in args],
**{key: self._transform_string(value, doc) for key, value in kwargs.items()}
)
@abc.abstractmethod
def _transform_string(self, string, doc):
raise NotImplementedError
@abc.abstractproperty
def name(self):
raise NotImplementedError
@abc.abstractproperty
def schema(self):
raise NotImplementedError
class XMLTransformer(BaseTransformer):
__metaclass__ = abc.ABCMeta
def _transform_string(self, string, doc):
val = doc.xpath(string, namespaces=self.namespaces)
return '' if not val else unicode(val[0]) if len(val) == 1 else [unicode(v) for v in val]
@abc.abstractproperty
def namespaces(self):
raise NotImplementedError
| from __future__ import unicode_literals
import abc
import logging
logger = logging.getLogger(__name__)
class BaseTransformer(object):
__metaclass__ = abc.ABCMeta
def transform(self, doc):
return self._transform(self.schema, doc)
def _transform(self, schema, doc):
transformed = {}
for key, value in schema.items():
if isinstance(value, dict):
transformed[key] = self._transform(value, doc)
elif isinstance(value, list) or isinstance(value, tuple):
transformed[key] = self._transform_iter(value, doc)
elif isinstance(value, basestring):
transformed[key] = self._transform_string(value, doc)
return transformed
def _transform_iter(self, l, doc):
docs = []
for value in l:
if isinstance(value, basestring):
docs.append(self._transform_string(value, doc))
elif callable(value):
return value(*[res for res in docs])
@abc.abstractmethod
def _transform_string(self, string, doc):
raise NotImplementedError
@abc.abstractproperty
def name(self):
raise NotImplementedError
@abc.abstractproperty
def schema(self):
raise NotImplementedError
class XMLTransformer(BaseTransformer):
__metaclass__ = abc.ABCMeta
def _transform_string(self, string, doc):
val = doc.xpath(string, namespaces=self.namespaces)
return '' if not val else unicode(val[0]) if len(val) == 1 else [unicode(v) for v in val]
@abc.abstractproperty
def namespaces(self):
raise NotImplementedError
| Python | 0.000015 |
465c1c1c9d7c102b4d35eb8c228565dbf8d35910 | simplify the code | util/remaining-gnu-error.py | util/remaining-gnu-error.py | #!/usr/bin/env python3
# This script lists the GNU failing tests by size
# Just like with util/run-gnu-test.sh, we expect the gnu sources
# to be in ../
import urllib.request
import urllib
import os
import glob
import json
base = "../gnu/tests/"
urllib.request.urlretrieve(
"https://raw.githubusercontent.com/uutils/coreutils-tracking/main/gnu-full-result.json",
"result.json",
)
types = ("/*/*.sh", "/*/*.pl", "/*/*.xpl")
tests = []
for files in types:
tests.extend(glob.glob(base + files))
# sort by size
list_of_files = sorted(tests, key=lambda x: os.stat(x).st_size)
with open("result.json", "r") as json_file:
data = json.load(json_file)
for d in data:
for e in data[d]:
# Not all the tests are .sh files, rename them if not.
script = e.replace(".log", ".sh")
a = f"{base}{d}{script}"
if not os.path.exists(a):
a = a.replace(".sh", ".pl")
if not os.path.exists(a):
a = a.replace(".pl", ".xpl")
# the tests pass, we don't care anymore
if data[d][e] == "PASS":
list_of_files.remove(a)
# Remove the factor tests and reverse the list (bigger first)
tests = list(filter(lambda k: "factor" not in k, list_of_files))
for f in reversed(tests):
print("%s: %s" % (f, os.stat(f).st_size))
print("")
print("%s tests remaining" % len(tests))
| #!/usr/bin/env python3
# This script lists the GNU failing tests by size
# Just like with util/run-gnu-test.sh, we expect the gnu sources
# to be in ../
import urllib.request
import urllib
import os
import glob
import json
base = "../gnu/tests/"
urllib.request.urlretrieve(
"https://raw.githubusercontent.com/uutils/coreutils-tracking/main/gnu-full-result.json",
"result.json",
)
tests = glob.glob(base + "/*/*.sh")
tests_pl = glob.glob(base + "/*/*.pl")
tests_xpl = glob.glob(base + "/*/*.xpl")
tests = tests + tests_pl + tests_xpl
# sort by size
list_of_files = sorted(tests, key=lambda x: os.stat(x).st_size)
with open("result.json", "r") as json_file:
data = json.load(json_file)
for d in data:
for e in data[d]:
# Not all the tests are .sh files, rename them if not.
script = e.replace(".log", ".sh")
a = f"{base}{d}{script}"
if not os.path.exists(a):
a = a.replace(".sh", ".pl")
if not os.path.exists(a):
a = a.replace(".pl", ".xpl")
# the tests pass, we don't care anymore
if data[d][e] == "PASS":
try:
list_of_files.remove(a)
except ValueError:
# Ignore the error
pass
# Remove the factor tests and reverse the list (bigger first)
tests = list(filter(lambda k: "factor" not in k, list_of_files))
for f in reversed(tests):
print("%s: %s" % (f, os.stat(f).st_size))
print("")
print("%s tests remaining" % len(tests))
| Python | 0.000677 |
b2a4967e956c07831516d90411f16d9f46a62cfb | Update script for py3 and cross-platform TMPDIR access | scripts/avogadro-remote.py | scripts/avogadro-remote.py | #!/usr/bin/python
from __future__ import print_function
import sys
import json
import time
import socket
import struct
import tempfile
class Connection:
def __init__(self, name = "avogadro"):
# create socket
self.sock = socket.socket(socket.AF_UNIX,
socket.SOCK_STREAM)
# connect
self.sock.connect(tempfile.gettempdir() + '/' + name)
def send_json(self, obj):
self.send_message(json.dumps(obj))
def send_message(self, msg):
sz = len(msg)
hdr = struct.pack('>I', sz)
pkt = hdr + msg.encode('ascii')
self.sock.send(pkt)
def recv_message(self, size = 1024):
pkt = self.sock.recv(size)
return pkt[4:]
def recv_json(self):
msg = self.recv_message()
try:
return json.loads(msg)
except Exception as e:
print('error: ' + str(e))
return {}
def close(self):
# close socket
self.sock.close()
if __name__ == '__main__':
conn = Connection()
method = sys.argv[1]
if method == 'openFile':
conn.send_json(
{
'jsonrpc' : '2.0',
'id' : 0,
'method' : 'openFile',
'params' : {
'fileName' : str(sys.argv[2])
}
}
)
elif method == 'kill':
conn.send_json(
{
'jsonrpc' : '2.0',
'id' : 0,
'method' : 'kill'
}
)
else:
print('unknown method: ' + method)
conn.close()
sys.exit(-1)
print('reply: ' + str(conn.recv_message()))
conn.close()
| #!/usr/bin/python
import sys
import json
import time
import socket
import struct
class Connection:
def __init__(self, name = "avogadro"):
# create socket
self.sock = socket.socket(socket.AF_UNIX,
socket.SOCK_STREAM)
# connect
self.sock.connect("/tmp/" + name)
def send_json(self, obj):
self.send_message(json.dumps(obj))
def send_message(self, msg):
sz = len(msg)
hdr = struct.pack('>I', sz)
pkt = hdr + msg
self.sock.send(pkt)
def recv_message(self, size = 1024):
pkt = self.sock.recv(size)
return pkt[4:]
def recv_json(self):
msg = self.recv_message()
try:
return json.loads(msg)
except Exception as e:
print 'error: ' + str(e)
return {}
def close(self):
# close socket
self.sock.close()
if __name__ == '__main__':
conn = Connection()
method = sys.argv[1]
if method == 'openFile':
conn.send_json(
{
'jsonrpc' : '2.0',
'id' : 0,
'method' : 'openFile',
'params' : {
'fileName' : str(sys.argv[2])
}
}
)
elif method == 'kill':
conn.send_json(
{
'jsonrpc' : '2.0',
'id' : 0,
'method' : 'kill'
}
)
else:
print 'unknown method: ' + method
sys.exit(-1)
conn.close()
print 'reply: ' + str(conn.recv_message())
conn.close()
| Python | 0 |
0b038b8348de12eab4396cbae69095ff54407075 | update SHEF soilm code to MV for ISUSM | scripts/isuag/isusm2rr5.py | scripts/isuag/isusm2rr5.py | """Create the RR5 SHEF product that the Weather Bureau Desires
Run from RUN_20_AFTER.sh
"""
import subprocess
import datetime
import os
import tempfile
import numpy as np
from pyiem.util import get_dbconn
from pyiem.tracker import loadqc
def mt(prefix, tmpf, depth, q):
"""Properly encode a value at depth into SHEF"""
if tmpf is None or "soil4" in q or np.isnan(tmpf):
return ""
val = float(depth)
val += abs(tmpf) / 1000.0
if tmpf < 0:
val = 0 - val
return "/%s %.3f" % (prefix, val)
def generate_rr5():
"""Create the RR5 Data"""
qcdict = loadqc()
data = (
"\n\n\n"
": Iowa State University Soil Moisture Network\n"
": Data contact Daryl Herzmann akrherz@iastate.edu\n"
": File generated %s UTC\n"
) % (datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M"),)
pgconn = get_dbconn("iem", user="nobody")
cursor = pgconn.cursor()
cursor.execute(
"""
SELECT id, valid, tmpf, c1tmpf, c2tmpf, c3tmpf, c4tmpf,
c2smv, c3smv, c4smv, phour
from current c JOIN stations t
on (t.iemid = c.iemid) WHERE t.network = 'ISUSM' and
valid > (now() - '90 minutes'::interval)
"""
)
for row in cursor:
q = qcdict.get(row[0], dict())
if "tmpf" in q or row[2] is None:
tmpf = "M"
else:
tmpf = "%.1f" % (row[2],)
if "precip" in q or row[10] is None:
precip = "M"
else:
precip = "%.2f" % (row[10],)
data += (".A %s %s C DH%s/TA %s%s%s%s%s\n" ".A1 %s%s%s/PPHRP %s\n") % (
row[0],
row[1].strftime("%Y%m%d"),
row[1].strftime("%H%M"),
tmpf,
mt("TV", row[3], "4", q),
mt("TV", row[4], "12", q),
mt("TV", row[5], "24", q),
mt("TV", row[6], "50", q),
mt("MV", max([0, 0 if row[7] is None else row[7]]), "12", q),
mt("MV", max([0, 0 if row[8] is None else row[8]]), "24", q),
mt("MV", max([0, 0 if row[9] is None else row[9]]), "50", q),
precip,
)
return data
def main():
"""Go Main Go"""
rr5data = generate_rr5()
# print rr5data
(tmpfd, tmpfn) = tempfile.mkstemp()
os.write(tmpfd, rr5data.encode("utf-8"))
os.close(tmpfd)
subprocess.call(
("/home/ldm/bin/pqinsert -p 'SUADSMRR5DMX.dat' %s") % (tmpfn,),
shell=True,
)
os.unlink(tmpfn)
def test_mt():
"""Conversion of values to SHEF encoded values"""
assert mt("TV", 4, 40, dict()) == "/TV 40.004"
assert mt("TV", -4, 40, dict()) == "/TV -40.004"
assert mt("TV", 104, 40, dict()) == "/TV 40.104"
if __name__ == "__main__":
main()
| """Create the RR5 SHEF product that the Weather Bureau Desires
Run from RUN_20_AFTER.sh
"""
import subprocess
import datetime
import os
import unittest
import tempfile
import numpy as np
from pyiem.util import get_dbconn
from pyiem.tracker import loadqc
def mt(prefix, tmpf, depth, q):
"""Properly encode a value at depth into SHEF"""
if tmpf is None or "soil4" in q or np.isnan(tmpf):
return ""
val = float(depth)
val += abs(tmpf) / 1000.0
if tmpf < 0:
val = 0 - val
return "/%s %.3f" % (prefix, val)
def generate_rr5():
"""Create the RR5 Data"""
qcdict = loadqc()
data = (
"\n\n\n"
": Iowa State University Soil Moisture Network\n"
": Data contact Daryl Herzmann akrherz@iastate.edu\n"
": File generated %s UTC\n"
) % (datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M"),)
pgconn = get_dbconn("iem", user="nobody")
cursor = pgconn.cursor()
cursor.execute(
"""
SELECT id, valid, tmpf, c1tmpf, c2tmpf, c3tmpf, c4tmpf,
c2smv, c3smv, c4smv, phour
from current c JOIN stations t
on (t.iemid = c.iemid) WHERE t.network = 'ISUSM' and
valid > (now() - '90 minutes'::interval)
"""
)
for row in cursor:
q = qcdict.get(row[0], dict())
if "tmpf" in q or row[2] is None:
tmpf = "M"
else:
tmpf = "%.1f" % (row[2],)
if "precip" in q or row[10] is None:
precip = "M"
else:
precip = "%.2f" % (row[10],)
data += (".A %s %s C DH%s/TA %s%s%s%s%s\n" ".A1 %s%s%s/PPHRP %s\n") % (
row[0],
row[1].strftime("%Y%m%d"),
row[1].strftime("%H%M"),
tmpf,
mt("TV", row[3], "4", q),
mt("TV", row[4], "12", q),
mt("TV", row[5], "24", q),
mt("TV", row[6], "50", q),
mt("MW", max([0, 0 if row[7] is None else row[7]]), "12", q),
mt("MW", max([0, 0 if row[8] is None else row[8]]), "24", q),
mt("MW", max([0, 0 if row[9] is None else row[9]]), "50", q),
precip,
)
return data
def main():
"""Go Main Go"""
rr5data = generate_rr5()
# print rr5data
(tmpfd, tmpfn) = tempfile.mkstemp()
os.write(tmpfd, rr5data.encode("utf-8"))
os.close(tmpfd)
subprocess.call(
("/home/ldm/bin/pqinsert -p 'SUADSMRR5DMX.dat' %s") % (tmpfn,),
shell=True,
)
os.unlink(tmpfn)
if __name__ == "__main__":
main()
class MyTest(unittest.TestCase):
"""Test out our functions"""
def test_mt(self):
"""Conversion of values to SHEF encoded values"""
self.assertEquals(mt("TV", 4, 40, dict()), "/TV 40.004")
self.assertEquals(mt("TV", -4, 40, dict()), "/TV -40.004")
self.assertEquals(mt("TV", 104, 40, dict()), "/TV 40.104")
| Python | 0 |
5489fe0abc5dda3b6d41bee368cd0b9727459af3 | Add search urls for projects | projects/urls.py | projects/urls.py | from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add-project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit-project'),
url(r'^edit_status/(?P<project_id>\d+)/$', 'edit_status', name='edit-status'),
url(r'^archive/$', 'projects_archive', name='projects-archive'),
url(r'^archive/review/(?P<project_id>\d+)/$', 'show_project', name='show-project'),
url(r'^archive/review/versions/(?P<project_id>\d+)/$', 'show_project_versions', name='show-project-versions'),
url(r'^archive/(?P<year>\d{4})/(?P<month>\d{,2})/$', 'projects_year_month', name='projects-year-month'),
url(r'^search/user/(?P<searched_creator>\d*)/$', 'projects_by_creator', name='projects-by-creator'),
url(r'^search/status/(?P<searched_status>.*)/$', 'projects_by_status', name='projects-by-status'),
url(r'^search/name/(?P<searched_name>.*)/$', 'projects_by_name', name='projects-by-name'),
url(r'^search/(?P<searched_name>\d*)/(?P<searched_status>.*)/(?P<searched_creator>.*)/$', 'projects_complex_search', name='projects-complex-search'),
)
| from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add-project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit-project'),
url(r'^edit_status/(?P<project_id>\d+)/$', 'edit_status', name='edit-status'),
url(r'^archive/$', 'projects_archive', name='projects-archive'),
url(r'^archive/review/(?P<project_id>\d+)/$', 'show_project', name='show-project'),
url(r'^archive/review/versions/(?P<project_id>\d+)/$', 'show_project_versions', name='show-project-versions'),
url(r'^archive/(?P<year>\d{4})/(?P<month>\d{,2})/$', 'projects_year_month', name='projects-year-month'),
)
| Python | 0 |
35b0af0fafb117e3cc613d3073602902fadb9c5c | Add daily-view to worker | server/worker/functions.py | server/worker/functions.py | import logging
import time
from django.db import connection
from server.models import SensorValue, Threshold, Notification
import functions
logger = logging.getLogger('worker')
def check_thresholds():
for threshold in Threshold.objects.all():
try:
latest_sensorvalue = SensorValue.objects.filter(
sensor=threshold.sensor).latest('timestamp')
if threshold.min_value is not None:
if latest_sensorvalue.value < threshold.min_value:
message = 'Threshold "%s" triggered (%s < %s)' % (
threshold.name, latest_sensorvalue.value, threshold.min_value)
Notification(threshold=threshold, message=message,
category=Notification.Danger, show_manager=threshold.show_manager).save()
logger.debug(message)
if threshold.max_value is not None:
if latest_sensorvalue.value > threshold.max_value:
message = 'Threshold "%s" triggered (%s > %s)' % (
threshold.name, latest_sensorvalue.value, threshold.max_value)
Notification(threshold=threshold, message=message,
category=Notification.Danger, show_manager=threshold.show_manager).save()
logger.debug(message)
except SensorValue.DoesNotExist:
logger.debug('No SensorValue found for Sensor #%s' %
threshold.sensor_id)
def refresh_views():
logger.debug('Trigger views refresh')
cursor = connection.cursor()
cursor.execute('''REFRESH MATERIALIZED VIEW server_sensorvaluehourly;''')
cursor.execute('''REFRESH MATERIALIZED VIEW server_sensorvaluedaily;''')
cursor.execute(
'''REFRESH MATERIALIZED VIEW server_sensorvaluemonthlysum;''')
cursor.execute(
'''REFRESH MATERIALIZED VIEW server_sensorvaluemonthlyavg;''')
logger.debug('Successfully refreshed views') | import logging
import time
from django.db import connection
from server.models import SensorValue, Threshold, Notification
import functions
logger = logging.getLogger('worker')
def check_thresholds():
for threshold in Threshold.objects.all():
try:
latest_sensorvalue = SensorValue.objects.filter(
sensor=threshold.sensor).latest('timestamp')
if threshold.min_value is not None:
if latest_sensorvalue.value < threshold.min_value:
message = 'Threshold "%s" triggered (%s < %s)' % (
threshold.name, latest_sensorvalue.value, threshold.min_value)
Notification(threshold=threshold, message=message,
category=Notification.Danger, show_manager=threshold.show_manager).save()
logger.debug(message)
if threshold.max_value is not None:
if latest_sensorvalue.value > threshold.max_value:
message = 'Threshold "%s" triggered (%s > %s)' % (
threshold.name, latest_sensorvalue.value, threshold.max_value)
Notification(threshold=threshold, message=message,
category=Notification.Danger, show_manager=threshold.show_manager).save()
logger.debug(message)
except SensorValue.DoesNotExist:
logger.debug('No SensorValue found for Sensor #%s' %
threshold.sensor_id)
def refresh_views():
logger.debug('Trigger views refresh')
cursor = connection.cursor()
cursor.execute('''REFRESH MATERIALIZED VIEW server_sensorvaluehourly;''')
cursor.execute(
'''REFRESH MATERIALIZED VIEW server_sensorvaluemonthlysum;''')
cursor.execute(
'''REFRESH MATERIALIZED VIEW server_sensorvaluemonthlyavg;''')
logger.debug('Successfully refreshed views')
| Python | 0.000001 |
13bb0a7ea546fed050b68c73730384c168370ac3 | Add typing for plogger. | ptest/plogger.py | ptest/plogger.py | import logging
import sys
from datetime import datetime
from . import config
class PConsole:
def __init__(self, out):
self.out = out
def write(self, msg: str):
self.out.write(str(msg))
def write_line(self, msg: str):
self.out.write(str(msg) + "\n")
pconsole = PConsole(sys.stdout)
pconsole_err = PConsole(sys.stderr)
class PReporter:
def __init__(self):
pass
def debug(self, msg: str, screenshot: bool = False):
self.__log(logging.DEBUG, msg, screenshot)
def info(self, msg: str, screenshot: bool = False):
self.__log(logging.INFO, msg, screenshot)
def warn(self, msg: str, screenshot: bool = False):
self.__log(logging.WARN, msg, screenshot)
def error(self, msg: str, screenshot: bool = False):
self.__log(logging.ERROR, msg, screenshot)
def critical(self, msg: str, screenshot: bool = False):
self.__log(logging.CRITICAL, msg, screenshot)
def __log(self, level: int, msg: str, screenshot: bool):
from . import test_executor, screen_capturer
try:
running_test_fixture = test_executor.current_executor().get_property("running_test_fixture")
except AttributeError as e:
pconsole.write_line("[%s] %s" % (logging.getLevelName(level), msg))
else:
log = {"time": str(datetime.now()), "level": logging.getLevelName(level).lower(), "message": str(msg)}
if screenshot and not config.get_option("disable_screenshot"):
log["screenshots"] = screen_capturer.take_screenshots()
running_test_fixture.logs.append(log)
if config.get_option("verbose"):
# output to pconsole
message = "[%s] %s" % (running_test_fixture.full_name, msg)
pconsole.write_line(message)
preporter = PReporter()
| import logging
import sys
from datetime import datetime
from . import config
class PConsole:
def __init__(self, out):
self.out = out
def write(self, msg):
self.out.write(str(msg))
def write_line(self, msg):
self.out.write(str(msg) + "\n")
pconsole = PConsole(sys.stdout)
pconsole_err = PConsole(sys.stderr)
class PReporter:
def __init__(self):
pass
def debug(self, msg, screenshot=False):
self.__log(logging.DEBUG, msg, screenshot)
def info(self, msg, screenshot=False):
self.__log(logging.INFO, msg, screenshot)
def warn(self, msg, screenshot=False):
self.__log(logging.WARN, msg, screenshot)
def error(self, msg, screenshot=False):
self.__log(logging.ERROR, msg, screenshot)
def critical(self, msg, screenshot=False):
self.__log(logging.CRITICAL, msg, screenshot)
def __log(self, level, msg, screenshot):
from . import test_executor, screen_capturer
try:
running_test_fixture = test_executor.current_executor().get_property("running_test_fixture")
except AttributeError as e:
pconsole.write_line("[%s] %s" % (logging.getLevelName(level), msg))
else:
log = {"time": str(datetime.now()), "level": logging.getLevelName(level).lower(), "message": str(msg)}
if screenshot and not config.get_option("disable_screenshot"):
log["screenshots"] = screen_capturer.take_screenshots()
running_test_fixture.logs.append(log)
if config.get_option("verbose"):
# output to pconsole
message = "[%s] %s" % (running_test_fixture.full_name, msg)
pconsole.write_line(message)
preporter = PReporter()
| Python | 0 |
3b5b3afbc66f60df45f0458ffdd0d37b9a7c50d0 | Add homemade fast width/height reader for JPEG files | ptoolbox/tags.py | ptoolbox/tags.py | # -*- coding: utf-8 -*-
import struct
from datetime import datetime
TAG_WIDTH = 'EXIF ExifImageWidth'
TAG_HEIGHT = 'EXIF ExifImageLength'
TAG_DATETIME = 'Image DateTime'
def jpeg_size(path):
"""Get image size.
Structure of JPEG file is:
ffd8 [ffXX SSSS DD DD ...] [ffYY SSSS DDDD ...] (S is 16bit size, D the data)
We look for the SOF0 header 0xffc0; its structure is
[ffc0 SSSS PPHH HHWW ...] where PP is 8bit precision, HHHH 16bit height, WWWW width
"""
with open(path, 'rb') as f:
_, header_type, size = struct.unpack('>HHH', f.read(6))
while header_type != 0xffc0:
f.seek(size - 2, 1)
header_type, size = struct.unpack('>HH', f.read(4))
bpi, height, width = struct.unpack('>BHH', f.read(5))
return width, height
def parse_time(tags):
tag = tags.get(TAG_DATETIME, None)
if not tag:
raise KeyError(TAG_DATETIME)
return datetime.strptime(str(tag), "%Y:%m:%d %H:%M:%S")
def parse_width(tags):
tag = tags.get(TAG_WIDTH, None)
if not tag:
raise KeyError(TAG_WIDTH)
return int(str(tag), 10)
def parse_height(tags):
tag = tags.get(TAG_HEIGHT, None)
if not tag:
raise KeyError(TAG_HEIGHT)
return int(str(tag), 10)
| # -*- coding: utf-8 -*-
from datetime import datetime
TAG_WIDTH = 'EXIF ExifImageWidth'
TAG_HEIGHT = 'EXIF ExifImageLength'
TAG_DATETIME = 'Image DateTime'
def parse_time(tags):
tag = tags.get(TAG_DATETIME, None)
if not tag:
raise KeyError(TAG_DATETIME)
return datetime.strptime(str(tag), "%Y:%m:%d %H:%M:%S")
def parse_width(tags):
tag = tags.get(TAG_WIDTH, None)
if not tag:
raise KeyError(TAG_WIDTH)
return int(str(tag), 10)
def parse_height(tags):
tag = tags.get(TAG_HEIGHT, None)
if not tag:
raise KeyError(TAG_HEIGHT)
return int(str(tag), 10)
| Python | 0 |
7a64ac255f53e85f888093daac83b3c0fabcf15e | Update ESPEC_tests.py | ESPEC_tests.py | ESPEC_tests.py | # -*- coding: utf-8 -*-
"""ESPEC_tests.py: Simple test routine for pyESPEC library
__author__ = "Jason M. Battle"
__copyright__ = "Copyright 2016, Jason M. Battle"
__license__ = "MIT"
__email__ = "jason.battle@gmail.com"
"""
from ESPEC import SH241
if __name__ == '__main__':
test = SH241()
test.OpenChannel()
if test.GetMode() == 'OFF':
test.SetPowerOn()
# Read Commands
test.GetROMVersion()
test.GetIntStatus()
test.GetIntMask()
test.GetAlarmStat()
test.GetKeyProtStat()
test.GetType()
test.GetMode()
test.GetCondition()
test.GetTemp()
test.GetHumid()
test.GetRefrigeCtl()
test.GetRelayStat()
test.GetHeaterStat()
test.GetProgStat()
test.GetProgData()
test.GetProgStepData(1)
# Write Commands
test.SetIntMask(0b01000000)
test.ResetIntStatus()
test.SetKeyProtectOn()
test.SetKeyProtectOff()
test.SetPowerOff()
test.SetPowerOn()
test.SetTemp(25.0)
test.SetHighTemp(155.0)
test.SetLowTemp(-45.0)
test.SetHumid(50.0)
test.SetHighHumid(100)
test.SetLowHumid(0)
test.SetHumidOff()
test.SetRefrigeCtl(9)
test.SetRelayOn(1)
test.SetRelayOff(1)
test.SetModeOff()
test.SetModeStandby()
test.SetModeConstant()
test.ProgramWrite()
test.SetModeProgram()
test.ProgramAdvance()
test.ProgramEnd()
test.SetModeStandby()
test.ProgramErase()
test.SetModeOff()
test.CloseChannel()
| # -*- coding: utf-8 -*-
"""ESPEC_tests.py: Simple test routine for pyESPEC library
__author__ = "Jason M. Battle"
__copyright__ = "Copyright 2016, Jason M. Battle"
__license__ = "MIT"
__email__ = "jason.battle@gmail.com"
"""
from ESPEC import SH241
if __name__ == '__main__':
test = SH241()
test.OpenChannel()
if test.GetMode() == 'OFF':
test.SetPowerOn()
# Read Commands
test.GetROMVersion()
test.GetIntStatus()
test.GetIntMask()
test.GetAlarmStat()
test.GetKeyProtStat()
test.GetType()
test.GetMode()
test.GetCondition()
test.GetTemp()
test.GetHumid()
test.GetRefrigeCtl()
test.GetRelayStat()
test.GetHeaterStat()
test.GetProgStat()
test.GetProgData()
test.GetProgStepData(1)
# Write Commands
test.SetIntMask(0b01000000)
test.ResetIntStatus()
test.SetKeyProtectOn()
test.SetKeyProtectOff()
test.SetPowerOff()
test.SetPowerOn()
test.SetTemp(25.0)
test.SetHighTemp(155.0)
test.SetLowTemp(-45.0)
test.SetHumid(50.0)
test.SetHighHumid(100)
test.SetLowHumid(0)
test.SetHumidOff()
test.SetRefrigeCtl(9)
test.SetRelayOn(1)
test.SetRelayOff(1)
test.SetModeOff()
test.SetModeStandby()
test.SetModeConstant()
test.ProgramWrite()
test.SetModeProgram()
test.ProgramAdvance()
test.ProgramEnd()
test.SetModeStandby()
test.ProgramErase()
test.SetModeOff()
test.CloseChannel()
| Python | 0 |
d177977ed4da7168e1d04b5420e224bb3b75a4fc | Use StringIO from six & remove trailing space in test file | src/azure/cli/tests/test_commands.py | src/azure/cli/tests/test_commands.py | import os
import sys
import unittest
import re
import vcr
import logging
from six import add_metaclass, StringIO
try:
import unittest.mock as mock
except ImportError:
import mock
from azure.cli.main import main as cli
from command_specs import TEST_SPECS
logging.basicConfig()
vcr_log = logging.getLogger('vcr')
vcr_log.setLevel(logging.ERROR)
VCR_CASSETTE_DIR = os.path.join(os.path.dirname(__file__), 'recordings')
FILTER_HEADERS = [
'authorization',
'client-request-id',
'x-ms-client-request-id',
'x-ms-correlation-request-id',
'x-ms-ratelimit-remaining-subscription-reads',
'x-ms-request-id',
'x-ms-routing-request-id',
'x-ms-gateway-service-instanceid',
'x-ms-ratelimit-remaining-tenant-reads',
'x-ms-served-by',
]
def before_record_request(request):
request.uri = re.sub('/subscriptions/([^/]+)/', '/subscriptions/00000000-0000-0000-0000-000000000000/', request.uri)
return request
def before_record_response(response):
def remove_entries(the_dict, entries):
for key in entries:
if key in the_dict:
del the_dict[key]
remove_entries(response['headers'], FILTER_HEADERS)
return response
my_vcr = vcr.VCR(
cassette_library_dir=VCR_CASSETTE_DIR,
before_record_request=before_record_request,
before_record_response=before_record_response
)
class TestSequenceMeta(type):
def __new__(mcs, name, bases, dict):
def gen_test(test_name, command, expected_result):
def load_subscriptions_mock(self):
return [{"id": "00000000-0000-0000-0000-000000000000", "user": "example@example.com", "access_token": "access_token", "state": "Enabled", "name": "Example", "active": True}];
@mock.patch('azure.cli._profile.Profile.load_subscriptions', load_subscriptions_mock)
@my_vcr.use_cassette('%s.yaml'%test_name, filter_headers=FILTER_HEADERS)
def test(self):
io = StringIO()
cli(command.split(), file=io)
actual_result = io.getvalue()
io.close()
self.assertEqual(actual_result, expected_result)
return test
for module_name, test_specs in TEST_SPECS:
for test_spec_item in test_specs:
test_name = 'test_%s' % test_spec_item['test_name']
full_test_name = '%s.%s'%(module_name, test_name)
dict[test_name] = gen_test(full_test_name, test_spec_item['command'], test_spec_item['expected_result'])
return type.__new__(mcs, name, bases, dict)
@add_metaclass(TestSequenceMeta)
class TestCommands(unittest.TestCase):
pass
if __name__ == '__main__':
unittest.main()
| import os
import sys
import unittest
import re
import vcr
import logging
from six import add_metaclass
try:
import unittest.mock as mock
except ImportError:
import mock
try:
# Python 3
from io import StringIO
except ImportError:
# Python 2
from StringIO import StringIO
from azure.cli.main import main as cli
from command_specs import TEST_SPECS
logging.basicConfig()
vcr_log = logging.getLogger('vcr')
vcr_log.setLevel(logging.ERROR)
VCR_CASSETTE_DIR = os.path.join(os.path.dirname(__file__), 'recordings')
FILTER_HEADERS = [
'authorization',
'client-request-id',
'x-ms-client-request-id',
'x-ms-correlation-request-id',
'x-ms-ratelimit-remaining-subscription-reads',
'x-ms-request-id',
'x-ms-routing-request-id',
'x-ms-gateway-service-instanceid',
'x-ms-ratelimit-remaining-tenant-reads',
'x-ms-served-by',
]
def before_record_request(request):
request.uri = re.sub('/subscriptions/([^/]+)/', '/subscriptions/00000000-0000-0000-0000-000000000000/', request.uri)
return request
def before_record_response(response):
def remove_entries(the_dict, entries):
for key in entries:
if key in the_dict:
del the_dict[key]
remove_entries(response['headers'], FILTER_HEADERS)
return response
my_vcr = vcr.VCR(
cassette_library_dir=VCR_CASSETTE_DIR,
before_record_request=before_record_request,
before_record_response=before_record_response
)
class TestSequenceMeta(type):
def __new__(mcs, name, bases, dict):
def gen_test(test_name, command, expected_result):
def load_subscriptions_mock(self):
return [{"id": "00000000-0000-0000-0000-000000000000", "user": "example@example.com", "access_token": "access_token", "state": "Enabled", "name": "Example", "active": True}];
@mock.patch('azure.cli._profile.Profile.load_subscriptions', load_subscriptions_mock)
@my_vcr.use_cassette('%s.yaml'%test_name, filter_headers=FILTER_HEADERS)
def test(self):
with StringIO() as io:
cli(command.split(), file=io)
self.assertEqual(io.getvalue(), expected_result)
return test
for module_name, test_specs in TEST_SPECS:
for test_spec_item in test_specs:
test_name = 'test_%s' % test_spec_item['test_name']
full_test_name = '%s.%s'%(module_name, test_name)
dict[test_name] = gen_test(full_test_name, test_spec_item['command'], test_spec_item['expected_result'])
return type.__new__(mcs, name, bases, dict)
@add_metaclass(TestSequenceMeta)
class TestCommands(unittest.TestCase):
pass
if __name__ == '__main__':
unittest.main()
| Python | 0 |
72d905e1e4098cf929213f59662c0c3090fd93cf | remove debug print | pyast/dump/js.py | pyast/dump/js.py | import json
import pyast
from collections import OrderedDict
import sys
if sys.version >= '3':
basestring = str
else:
pass
def _dump_node_name(node):
return node.__class__.__name__.lower()
def _dump_node(node, name=None, indent=0):
if isinstance(node, basestring):
return node
elif isinstance(node, bool):
return node
struct = OrderedDict({'type': None})
if isinstance(node, pyast.Node):
struct['type'] = _dump_node_name(node)
for field in node._fields:
struct[field] = _dump_node(getattr(node, field))
elif isinstance(node, pyast.TypedList):
struct = []
for elem in node:
struct.append(_dump_node(elem))
elif isinstance(node, pyast.TypedDict):
struct = {}
for elem, key in node.items():
struct[key] =_dump_node(elem)
return struct
def dump(ast):
struct = _dump_node(ast)
o = json.dumps(struct, indent=2)
return o
| import json
import pyast
from collections import OrderedDict
import sys
if sys.version >= '3':
basestring = str
else:
pass
def _dump_node_name(node):
return node.__class__.__name__.lower()
def _dump_node(node, name=None, indent=0):
if isinstance(node, basestring):
return node
elif isinstance(node, bool):
return node
struct = OrderedDict({'type': None})
if isinstance(node, pyast.Node):
struct['type'] = _dump_node_name(node)
for field in node._fields:
struct[field] = _dump_node(getattr(node, field))
elif isinstance(node, pyast.TypedList):
struct = []
for elem in node:
struct.append(_dump_node(elem))
elif isinstance(node, pyast.TypedDict):
struct = {}
for elem, key in node.items():
struct[key] =_dump_node(elem)
return struct
def dump(ast):
struct = _dump_node(ast)
print(json)
o = json.dumps(struct, indent=2)
return o
| Python | 0.000008 |
c46e472755c7b7dd450626e136f31a29ca9a5321 | Fix a regression in accessing the username for the session. | rbtools/utils/users.py | rbtools/utils/users.py | from __future__ import unicode_literals
import getpass
import logging
import sys
from six.moves import input
from rbtools.api.errors import AuthorizationError
from rbtools.commands import CommandError
def get_authenticated_session(api_client, api_root, auth_required=False):
"""Return an authenticated session.
None will be returned if the user is not authenticated, unless the
'auth_required' parameter is True, in which case the user will be prompted
to login.
"""
session = api_root.get_session(expand='user')
if not session.authenticated:
if not auth_required:
return None
logging.warning('You are not authenticated with the Review Board '
'server at %s, please login.' % api_client.url)
sys.stderr.write('Username: ')
username = input()
password = getpass.getpass(b'Password: ')
api_client.login(username, password)
try:
session = session.get_self()
except AuthorizationError:
raise CommandError('You are not authenticated.')
return session
def get_user(api_client, api_root, auth_required=False):
"""Return the user resource for the current session."""
session = get_authenticated_session(api_client, api_root, auth_required)
if session:
return session.user
return None
def get_username(api_client, api_root, auth_required=False):
"""Return the username for the current session."""
user = get_user(api_client, api_root, auth_required)
if user:
return user.username
return None
| from __future__ import unicode_literals
import getpass
import logging
import sys
from six.moves import input
from rbtools.api.errors import AuthorizationError
from rbtools.commands import CommandError
def get_authenticated_session(api_client, api_root, auth_required=False):
"""Return an authenticated session.
None will be returned if the user is not authenticated, unless the
'auth_required' parameter is True, in which case the user will be prompted
to login.
"""
session = api_root.get_session(expand='user')
if not session.authenticated:
if not auth_required:
return None
logging.warning('You are not authenticated with the Review Board '
'server at %s, please login.' % api_client.url)
sys.stderr.write('Username: ')
username = input()
password = getpass.getpass(b'Password: ')
api_client.login(username, password)
try:
session = session.get_self()
except AuthorizationError:
raise CommandError('You are not authenticated.')
return session
def get_user(api_client, api_root, auth_required=False):
"""Return the user resource for the current session."""
session = get_authenticated_session(api_client, api_root, auth_required)
if session:
return session.user
def get_username(api_client, api_root, auth_required=False):
"""Return the username for the current session."""
session = get_authenticated_session(api_client, api_root, auth_required)
if session:
return session.links.user.title
| Python | 0.003157 |
2beb589edc2f7b57be0d6a559e2f29471490bc91 | FIX py2 support! | pyfaker/utils.py | pyfaker/utils.py | import re
import random
import os
import json
from string import Formatter
class BaseFake(object):
pass
class CallFormatter(Formatter):
def get_field(self, field_name, *args, **kwargs):
obj, used_key = Formatter.get_field(self, field_name, *args, **kwargs)
return obj(), used_key
'''
class CallFormatter(Formatter):
def get_field(field_name, *args, **kwargs):
used_key = Formatter.get_field(field_name, *args, **kwargs)
return (used_key[0](),) + used_key[1:]
class CallFormatter(Formatter):
def get_field(self, field_name, *args, **kwargs):
if kwargs is None:
kwargs = kwargs.update(args[1])
else:
kwargs.update(args[1])
obj, used_key = Formatter.get_field(self, field_name, args[0:1], kwargs)
return obj(kwargs['cls']()), used_key
'''
call_fmt = CallFormatter()
def get_locales():
def curpath():
pth, _ = os.path.split(os.path.abspath(__file__))
return pth
fpath = os.path.join(curpath(), 'locales.json')
with open(fpath, 'r') as f:
return json.load(f)
_all_locales = get_locales()
def to_camel(s):
"""returns string to camel caps
Example
to_camel('foo_bar') == 'FooBar'
"""
try:
return str(s.title().replace('_', '')) # assume the titles are ascii, else class name fail
except Exception: # TODO specify which kind of error
raise ValueError(
"%s doesn't convert to a good string for a class name" % s)
def update_loc(loc1, loc2):
loc1.update(loc2)
'''
def format_(s, current, fake_=None):
namespace = dict(current.__dict__, **{'cls': current}) # and fake_ ?
# first replace #s with digits then fill in rest using _locals
def callback(matchobj):
return '%s' % random.randrange(10)
s = re.sub(r'#', callback, s)
return s
fmt = CallFormatter()
return fmt.format(s, **namespace)
'''
| import re
import random
import os
import json
from string import Formatter
class BaseFake(object):
pass
class CallFormatter(Formatter):
def get_field(self, field_name, *args, **kwargs):
obj, used_key = Formatter.get_field(self, field_name, *args, **kwargs)
return obj(), used_key
'''
class CallFormatter(Formatter):
def get_field(field_name, *args, **kwargs):
used_key = Formatter.get_field(field_name, *args, **kwargs)
return (used_key[0](),) + used_key[1:]
class CallFormatter(Formatter):
def get_field(self, field_name, *args, **kwargs):
if kwargs is None:
kwargs = kwargs.update(args[1])
else:
kwargs.update(args[1])
obj, used_key = Formatter.get_field(self, field_name, args[0:1], kwargs)
return obj(kwargs['cls']()), used_key
'''
call_fmt = CallFormatter()
def get_locales():
def curpath():
pth, _ = os.path.split(os.path.abspath(__file__))
return pth
fpath = os.path.join(curpath(), 'locales.json')
with open(fpath, 'r') as f:
return json.load(f)
_all_locales = get_locales()
def to_camel(s):
"""returns string to camel caps
Example
to_camel('foo_bar') == 'FooBar'
"""
try:
return s.title().replace('_', '') # assume the titles are ascii, else class name fail
except Exception: # TODO specify which kind of error
raise ValueError(
"%s doesn't convert to a good string for a class name" % s)
def update_loc(loc1, loc2):
loc1.update(loc2)
'''
def format_(s, current, fake_=None):
namespace = dict(current.__dict__, **{'cls': current}) # and fake_ ?
# first replace #s with digits then fill in rest using _locals
def callback(matchobj):
return '%s' % random.randrange(10)
s = re.sub(r'#', callback, s)
return s
fmt = CallFormatter()
return fmt.format(s, **namespace)
'''
| Python | 0 |
24d886b97e6ce1636e95f3c1bde7c889cf622a7c | Change string to byte conversion | pyglet/compat.py | pyglet/compat.py | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Compatibility tools
Various tools for simultaneous Python 2.x and Python 3.x support
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import sys
import itertools
if sys.version_info[0] == 2:
if sys.version_info[1] < 6:
#Pure Python implementation from
#http://docs.python.org/library/itertools.html#itertools.izip_longest
def izip_longest(*args, **kwds):
# izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
fillvalue = kwds.get('fillvalue')
def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
yield counter() # yields the fillvalue, or raises IndexError
fillers = itertools.repeat(fillvalue)
iters = [itertools.chain(it, sentinel(), fillers) for it in args]
try:
for tup in itertools.izip(*iters):
yield tup
except IndexError:
pass
else:
izip_longest = itertools.izip_longest
else:
izip_longest = itertools.zip_longest
if sys.version_info[0] >= 3:
import io
def asbytes(s):
if isinstance(s, bytes):
return s
elif isinstance(s, str):
return bytes(ord(c) for c in s)
else:
return bytes(s)
def asstr(s):
if isinstance(s, str):
return s
return s.decode("utf-8")
bytes_type = bytes
BytesIO = io.BytesIO
else:
import StringIO
asbytes = str
asstr = str
bytes_type = str
BytesIO = StringIO.StringIO
| # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Compatibility tools
Various tools for simultaneous Python 2.x and Python 3.x support
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import sys
import itertools
if sys.version_info[0] == 2:
if sys.version_info[1] < 6:
#Pure Python implementation from
#http://docs.python.org/library/itertools.html#itertools.izip_longest
def izip_longest(*args, **kwds):
# izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
fillvalue = kwds.get('fillvalue')
def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
yield counter() # yields the fillvalue, or raises IndexError
fillers = itertools.repeat(fillvalue)
iters = [itertools.chain(it, sentinel(), fillers) for it in args]
try:
for tup in itertools.izip(*iters):
yield tup
except IndexError:
pass
else:
izip_longest = itertools.izip_longest
else:
izip_longest = itertools.zip_longest
if sys.version_info[0] >= 3:
import io
def asbytes(s):
if isinstance(s, bytes):
return s
return s.encode("utf-8")
def asstr(s):
if isinstance(s, str):
return s
return s.decode("utf-8")
bytes_type = bytes
BytesIO = io.BytesIO
else:
import StringIO
asbytes = str
asstr = str
bytes_type = str
BytesIO = StringIO.StringIO
| Python | 0.000358 |
be3f26c6f3401290e1bee726f0977cab78bdd61c | Allow unset viewport in lg_earth::client | lg_earth/src/lg_earth/client.py | lg_earth/src/lg_earth/client.py | import os
import shutil
import threading
import xml.etree.ElementTree as ET
from xml.dom import minidom
from tempfile import gettempdir as systmp
import rospy
from lg_common.msg import ApplicationState, WindowGeometry
from lg_common import ManagedApplication, ManagedWindow
from client_config import ClientConfig
TOOLBAR_HEIGHT = 22
class Client:
def __init__(self):
geometry = ManagedWindow.get_viewport_geometry()
if geometry is not None:
geometry.y -= TOOLBAR_HEIGHT
geometry.height += TOOLBAR_HEIGHT
earth_window = ManagedWindow(
geometry=geometry,
w_class='Googleearth-bin',
w_name='Google Earth',
w_instance=self._get_instance()
)
cmd = ['/opt/google/earth/free/googleearth-bin']
args, geplus_config, layers_config, kml_content, view_content = \
self._get_config()
cmd.extend(args)
self.earth_proc = ManagedApplication(cmd, window=earth_window)
self._make_dir()
os.mkdir(self._get_dir() + '/.googleearth')
os.mkdir(self._get_dir() + '/.googleearth/Cache')
if rospy.get_param('~show_google_logo', True):
pass
else:
self._touch_file((self._get_dir() + '/.googleearth/' + 'localdbrootproto'))
os.mkdir(self._get_dir() + '/.config')
os.mkdir(self._get_dir() + '/.config/Google')
self._render_config(geplus_config,
'.config/Google/GoogleEarthPlus.conf')
self._render_config(layers_config,
'.config/Google/GECommonSettings.conf')
self._render_file(kml_content,
'.googleearth/myplaces.kml')
self._render_file(view_content,
'.googleearth/cached_default_view.kml')
os.environ['HOME'] = self._get_dir()
os.environ['BROWSER'] = '/dev/null'
if os.getenv('DISPLAY') is None:
os.environ['DISPLAY'] = ':0'
os.environ['LD_LIBRARY_PATH'] += ':/opt/google/earth/free'
def _touch_file(self, fname):
if os.path.exists(fname):
os.utime(fname, None)
else:
open(fname, 'a').close()
def _get_instance(self):
return '_earth_instance_' + rospy.get_name().strip('/')
def _get_dir(self):
return os.path.normpath(systmp() + '/' + self._get_instance())
def _make_dir(self):
self._clean_dir()
os.mkdir(self._get_dir())
assert os.path.exists(self._get_dir())
rospy.on_shutdown(self._clean_dir)
def _clean_dir(self):
try:
shutil.rmtree(self._get_dir())
except OSError:
pass
def _get_config(self):
config = ClientConfig(self._get_dir(), self._get_instance())
return config.get_config()
def _render_file(self, content, path):
with open(self._get_dir() + '/' + path, 'w') as f:
f.write(content)
def _render_config(self, config, path):
with open(self._get_dir() + '/' + path, 'w') as f:
for section, settings in config.iteritems():
f.write('[' + section + ']\n')
for k, v in settings.iteritems():
r = str(v).lower() if isinstance(v, bool) else str(v)
f.write(k + '=' + r + '\n')
f.write('\n')
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
| import os
import shutil
import threading
import xml.etree.ElementTree as ET
from xml.dom import minidom
from tempfile import gettempdir as systmp
import rospy
from lg_common.msg import ApplicationState, WindowGeometry
from lg_common import ManagedApplication, ManagedWindow
from client_config import ClientConfig
TOOLBAR_HEIGHT = 22
class Client:
def __init__(self):
geometry = ManagedWindow.get_viewport_geometry()
geometry.y -= TOOLBAR_HEIGHT
geometry.height += TOOLBAR_HEIGHT
earth_window = ManagedWindow(
geometry=geometry,
w_class='Googleearth-bin',
w_name='Google Earth',
w_instance=self._get_instance()
)
cmd = ['/opt/google/earth/free/googleearth-bin']
args, geplus_config, layers_config, kml_content, view_content = \
self._get_config()
cmd.extend(args)
self.earth_proc = ManagedApplication(cmd, window=earth_window)
self._make_dir()
os.mkdir(self._get_dir() + '/.googleearth')
os.mkdir(self._get_dir() + '/.googleearth/Cache')
if rospy.get_param('~show_google_logo', True):
pass
else:
self._touch_file((self._get_dir() + '/.googleearth/' + 'localdbrootproto'))
os.mkdir(self._get_dir() + '/.config')
os.mkdir(self._get_dir() + '/.config/Google')
self._render_config(geplus_config,
'.config/Google/GoogleEarthPlus.conf')
self._render_config(layers_config,
'.config/Google/GECommonSettings.conf')
self._render_file(kml_content,
'.googleearth/myplaces.kml')
self._render_file(view_content,
'.googleearth/cached_default_view.kml')
os.environ['HOME'] = self._get_dir()
os.environ['BROWSER'] = '/dev/null'
if os.getenv('DISPLAY') is None:
os.environ['DISPLAY'] = ':0'
os.environ['LD_LIBRARY_PATH'] += ':/opt/google/earth/free'
def _touch_file(self, fname):
if os.path.exists(fname):
os.utime(fname, None)
else:
open(fname, 'a').close()
def _get_instance(self):
return '_earth_instance_' + rospy.get_name().strip('/')
def _get_dir(self):
return os.path.normpath(systmp() + '/' + self._get_instance())
def _make_dir(self):
self._clean_dir()
os.mkdir(self._get_dir())
assert os.path.exists(self._get_dir())
rospy.on_shutdown(self._clean_dir)
def _clean_dir(self):
try:
shutil.rmtree(self._get_dir())
except OSError:
pass
def _get_config(self):
config = ClientConfig(self._get_dir(), self._get_instance())
return config.get_config()
def _render_file(self, content, path):
with open(self._get_dir() + '/' + path, 'w') as f:
f.write(content)
def _render_config(self, config, path):
with open(self._get_dir() + '/' + path, 'w') as f:
for section, settings in config.iteritems():
f.write('[' + section + ']\n')
for k, v in settings.iteritems():
r = str(v).lower() if isinstance(v, bool) else str(v)
f.write(k + '=' + r + '\n')
f.write('\n')
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
| Python | 0.000001 |
cf644a17bd8c2abe436a37159bdf3eec7d2a358d | Remove premature optimization | luigi/tasks/quickgo/load_annotations.py | luigi/tasks/quickgo/load_annotations.py | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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 tasks.utils.pgloader import PGLoader
from tasks.ontologies import Ontologies
from .quickgo_data import QuickGoData
CONTROL_FILE = """
LOAD CSV
FROM '{filename}'
WITH ENCODING ISO-8859-14
HAVING FIELDS ({fields})
INTO {db_url}
TARGET COLUMNS ({columns})
SET
search_path = '{search_path}'
WITH
fields escaped by double-quote,
fields terminated by ','
BEFORE LOAD DO
$$
create table if not exists {load_table} (
rna_id varchar(50),
qualifier varchar(30),
assigned_by varchar(50),
extensions jsonb,
ontology_term_id varchar(15),
evidence_code varchar(15)
);
$$,
$$
truncate table {load_table};
$$
AFTER LOAD DO
$$
INSERT INTO {final_table} (
rna_id,
qualifier,
assigned_by,
extensions,
ontology_term_id,
evidence_code
) (
SELECT
rna_id,
qualifier,
assigned_by,
extensions,
ontology_term_id,
evidence_code
FROM {load_table}
)
ON CONFLICT (rna_id, qualifier, assigned_by, ontology_term_id, evidence_code)
DO UPDATE
SET
rna_id = excluded.rna_id,
qualifier = excluded.qualifier,
assigned_by = excluded.assigned_by,
extensions = excluded.extensions,
ontology_term_id = excluded.ontology_term_id,
evidence_code = excluded.evidence_code
;
$$,
$$
DROP TABLE {load_table};
$$
;
"""
class QuickGoLoadAnnotations(PGLoader):
def requires(self):
return [
QuickGoData(),
Ontologies(),
]
def control_file(self):
output = self.requires()[0].output()
table = 'go_term_annotations'
load_table = 'load_' + table
fields = ', '.join(output.annotations.headers)
return CONTROL_FILE.format(
filename=output.annotations.filename,
fields=fields,
columns=fields,
final_table=table,
load_table=load_table,
db_url=self.db_url(table=load_table),
search_path=self.db_search_path(),
)
| # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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 tasks.utils.pgloader import PGLoader
from tasks.ontologies import Ontologies
from .quickgo_data import QuickGoData
CONTROL_FILE = """
LOAD CSV
FROM '{filename}'
WITH ENCODING ISO-8859-14
HAVING FIELDS ({fields})
INTO {db_url}
TARGET COLUMNS ({columns})
SET
search_path = '{search_path}'
WITH
fields escaped by double-quote,
fields terminated by ','
BEFORE LOAD DO
$$
create table if not exists {load_table} (
rna_id varchar(50),
qualifier varchar(30),
assigned_by varchar(50),
extensions jsonb,
ontology_term_id varchar(15),
evidence_code varchar(15)
);
$$,
$$
truncate table {load_table};
$$
AFTER LOAD DO
$$
INSERT INTO {final_table} (
rna_id,
qualifier,
assigned_by,
extensions,
ontology_term_id,
evidence_code
) (
SELECT
rna_id,
qualifier,
assigned_by,
extensions,
ontology_term_id,
evidence_code
FROM {load_table}
)
ON CONFLICT (rna_id, qualifier, assigned_by, ontology_term_id, evidence_code)
DO UPDATE
SET
extensions = excluded.extensions
;
$$,
$$
DROP TABLE {load_table};
$$
;
"""
class QuickGoLoadAnnotations(PGLoader):
def requires(self):
return [
QuickGoData(),
Ontologies(),
]
def control_file(self):
output = self.requires()[0].output()
table = 'go_term_annotations'
load_table = 'load_' + table
fields = ', '.join(output.annotations.headers)
return CONTROL_FILE.format(
filename=output.annotations.filename,
fields=fields,
columns=fields,
final_table=table,
load_table=load_table,
db_url=self.db_url(table=load_table),
search_path=self.db_search_path(),
)
| Python | 0.000015 |
625839a284085e92855b52aaa4abbf0f30d66bb2 | pretty_output().header | qaamus/qaamus.py | qaamus/qaamus.py | import unittest
import requests
from bs4 import BeautifulSoup
from ind_ara_parser import IndAraParser
class pretty_output(object):
def __init__(self, dict_obj):
self.dict_obj = dict_obj
@property
def header(self):
return "-= Arti dari {ind_utama} =-".format(
ind_utama=self.dict_obj.get("utama").get("ind"))
class PrettyOutputTestCase(unittest.TestCase):
def setUp(self):
self.dict_ = {'utama': {"ind": "ind_utama",
"ara": "ara_utama",
"footer": "footer"},
'berhubungan': [
{"ind": "ind_pertama",
"ara": "ara_pertama"},
{"ind": "ind_kedua",
"ara": "ara_kedua"}
]
}
def test_pretty_output_header(self):
po = pretty_output(self.dict_).header
expected = "-= Arti dari ind_utama =-"
self.assertEqual(po, expected)
class Qaamus:
def terjemah(self, layanan, query):
"""
Return terjemahan tergantung dengan **layanan** apa yang dia pilih,
dan **query** apa yang dia pakai.
Adapun *layanan* di [Qaamus](qaamus.com) saat ini terdapat 3 layanan:
* Indonesia Arab
* Angka
* Terjemah nama
Sedangkan *query* adalah query pencarian anda"""
if layanan == "idar":
url = self.build_idar_url(query)
soup = self._make_soup(url)
parser = IndAraParser(soup)
return {"utama": parser.get_arti_master(),
"berhubungan": parser.get_all_arti_berhub(self._make_soup)}
def _make_soup(self, url):
"""Return BeautifulSoup object."""
resp = requests.get(url)
return BeautifulSoup(resp.content)
def build_idar_url(self, query):
"""Return url pencarian sesuai dengan *query* yang dimasukkan."""
query = "+".join(query.split(" "))
url = "http://qaamus.com/indonesia-arab/{query}/1".format(
query=query)
return url
class QaamusTest(unittest.TestCase):
def test_building_idar_url(self):
q = Qaamus()
expected_url = "http://qaamus.com/indonesia-arab/capai/1"
this_url = q.build_idar_url("capai")
self.assertEqual(this_url, expected_url)
def test_building_idar_url_with_multiple_words(self):
q = Qaamus()
expected_url = "http://qaamus.com/indonesia-arab/mobil+ambulan+bagus/1"
this_url = q.build_idar_url("mobil ambulan bagus")
self.assertEqual(this_url, expected_url)
def idar(query):
return Qaamus().terjemah("idar", query)
if __name__ == "__main__":
print(idar("memukul"))
unittest.main()
| import unittest
import requests
from bs4 import BeautifulSoup
from ind_ara_parser import IndAraParser
class Qaamus:
def terjemah(self, layanan, query):
"""
Return terjemahan tergantung dengan **layanan** apa yang dia pilih,
dan **query** apa yang dia pakai.
Adapun *layanan* di [Qaamus](qaamus.com) saat ini terdapat 3 layanan:
* Indonesia Arab
* Angka
* Terjemah nama
Sedangkan *query* adalah query pencarian anda"""
if layanan == "idar":
url = self.build_idar_url(query)
soup = self._make_soup(url)
parser = IndAraParser(soup)
return {"utama": parser.get_arti_master(),
"berhubungan": parser.get_all_arti_berhub(self._make_soup)}
def _make_soup(self, url):
"""Return BeautifulSoup object."""
resp = requests.get(url)
return BeautifulSoup(resp.content)
def build_idar_url(self, query):
"""Return url pencarian sesuai dengan *query* yang dimasukkan."""
query = "+".join(query.split(" "))
url = "http://qaamus.com/indonesia-arab/" + query + "/1"
return url
class QaamusTest(unittest.TestCase):
def test_building_idar_url(self):
q = Qaamus()
expected_url = "http://qaamus.com/indonesia-arab/capai/1"
this_url = q.build_idar_url("capai")
self.assertEqual(this_url, expected_url)
def test_building_idar_url_with_multiple_words(self):
q = Qaamus()
expected_url = "http://qaamus.com/indonesia-arab/mobil+ambulan+bagus/1"
this_url = q.build_idar_url("mobil ambulan bagus")
self.assertEqual(this_url, expected_url)
def idar(query):
return Qaamus().terjemah("idar", query)
if __name__ == "__main__":
print(idar("memukul"))
unittest.main()
| Python | 0.999995 |
23ab13f192b58f8b550aa2e16d5861e14535698a | Add slot fot empty_patch in cli pop command | quilt/cli/pop.py | quilt/cli/pop.py | # vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implementation of the quilt patch system
#
# Copyright (C) 2012 Björn Ricks <bjoern.ricks@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library 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
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
import os
from quilt.cli.meta import Command
from quilt.pop import Pop
class PopCommand(Command):
usage = "%prog pop [-a] [patch]"
name = "pop"
def add_args(self, parser):
parser.add_option("-a", "--all", help="remove all applied patches",
action="store_true")
def run(self, options, args):
pop = Pop(os.getcwd(), self.get_pc_dir())
pop.unapplying.connect(self.unapplying)
pop.unapplied.connect(self.unapplied)
pop.empty_patch.connect(self.empty_patch)
if options.all:
pop.unapply_all()
elif not args:
pop.unapply_top_patch()
else:
pop.unapply_patch(args[0])
def unapplying(self, patch):
print "Removing patch %s" % patch.get_name()
def unapplied(self, patch):
if not patch:
print "No patches applied"
else:
print "Now at patch %s" % patch.get_name()
def empty_patch(self, patch):
print "Patch %s appears to be empty, removing" % patch.get_name()
| # vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implementation of the quilt patch system
#
# Copyright (C) 2012 Björn Ricks <bjoern.ricks@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library 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
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
import os
from quilt.cli.meta import Command
from quilt.pop import Pop
class PopCommand(Command):
usage = "%prog pop [-a] [patch]"
name = "pop"
def add_args(self, parser):
parser.add_option("-a", "--all", help="remove all applied patches",
action="store_true")
def run(self, options, args):
pop = Pop(os.getcwd(), self.get_pc_dir())
pop.unapplying.connect(self.unapplying)
pop.unapplied.connect(self.unapplied)
if options.all:
pop.unapply_all()
elif not args:
pop.unapply_top_patch()
else:
pop.unapply_patch(args[0])
def unapplying(self, patch):
print "Removing patch %s" % patch.get_name()
def unapplied(self, patch):
if not patch:
print "No patches applied"
else:
print "Now at patch %s" % patch.get_name()
| Python | 0 |
2c386cc3e81caffd906b68a6d527bd8bdd1d5ae5 | Replace nltk.model.NgramModel with nltk.ngrams | marmot/features/lm_feature_extractor.py | marmot/features/lm_feature_extractor.py | from nltk import ngrams, word_tokenize
#from nltk.model import NgramModel
from marmot.features.feature_extractor import FeatureExtractor
from marmot.util.simple_corpus import SimpleCorpus
# Class that extracts various LM features
# Calling an external LM is very slow, so a new lm is constructed with nltk
class LMFeatureExtractor(FeatureExtractor):
def __init__(self, corpus_file, order=3):
self.order = order
self.lm = [ set() for i in range(order) ]
for line in open(corpus_file):
words = word_tokenize(line[:-1].decode('utf-8'))
for i in range(1,order):
self.lm[i] = self.lm[i].union( ngrams( words, i+1 ) )
self.lm[0] = self.lm[0].union(words)
def check_lm(self, ngram, side='left'):
for i in range(self.order, 0, -1):
if side == 'left':
cur_ngram = ngram[len(ngram)-i:]
elif side == 'right':
cur_ngram = ngram[:i]
if tuple(cur_ngram) in self.lm[i-1]:
return i
return 0
# returns a set of features related to LM
# currently extracting: highest order ngram including the word and its LEFT context,
# highest order ngram including the word and its RIGHT context
def get_features(self, context_obj):
left_ngram = self.check_lm( context_obj['target'][:context_obj['index']+1], side='left' )
right_ngram = self.check_lm( context_obj['target'][context_obj['index']:], side='right' )
return (left_ngram, right_ngram)
| from nltk.model import NgramModel
from marmot.features.feature_extractor import FeatureExtractor
from marmot.util.simple_corpus import SimpleCorpus
def check_lm_recursive(words, lm, low_order='left'):
if len(words) < lm._n:
return check_lm_recursive(words, lm._backoff, low_order=low_order)
if tuple(words) in lm._ngrams:
return lm._n
elif lm._n > 1:
if low_order == 'left':
return check_lm_recursive(words[1:], lm._backoff, low_order=low_order)
elif low_order == 'right':
return check_lm_recursive(words[:-1], lm._backoff, low_order=low_order)
else:
return 0
# Class that extracts various LM features
# Calling an external LM is very slow, so a new lm is constructed with nltk
class LMFeatureExtractor(FeatureExtractor):
def __init__(self, corpus_file, order=3):
# load the corpus
corp = SimpleCorpus(corpus_file)
# nltk LM requires all words in one list
all_words = [w for sent in [line for line in corp.get_texts()] for w in sent]
self.lm = NgramModel(order, all_words)
def check_lm_recursive(words, lm, low_order='left'):
if len(words) < lm._n:
return check_lm_recursive(words, lm._backoff, low_order=low_order)
if tuple(words) in lm._ngrams:
return lm._n
elif lm._n > 1:
if low_order == 'left':
return check_lm_recursive(words[1:], lm._backoff, low_order=low_order)
elif low_order == 'right':
return check_lm_recursive(words[:-1], lm._backoff, low_order=low_order)
else:
return 0
# returns a set of features related to LM
# currently extracting: highest order ngram including the word and its LEFT context,
# highest order ngram including the word and its RIGHT context
def get_features(self, context_obj):
left_ngram = check_lm_recursive(context_obj['target'][max(0, context_obj['index']-self.lm._n):context_obj['index']], self.lm, low_order='left')
right_ngram = check_lm_recursive(context_obj['target'][context_obj['index']:min(len(context_obj['target']),context_obj['index']+self.lm._n)], self.lm, low_order='right')
return (left_ngram, right_ngram)
| Python | 0.999998 |
5d393ff5c007bafb731aaf703a5225081b99f69a | Align the add/remove URL with the filter URL | cotracker/cotracker/urls.py | cotracker/cotracker/urls.py | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
from checkouts.views import (
PilotList,
PilotDetail,
AirstripList,
AirstripDetail,
BaseList,
BaseAttachedDetail,
BaseUnattachedDetail,
FilterFormView,
CheckoutUpdateFormView,
)
admin.autodiscover()
urlpatterns = patterns('',
url(r'^emerald/', include(admin.site.urls)),
)
urlpatterns += patterns('',
url(
regex=r'^pilots/$',
view=PilotList.as_view(),
name='pilot_list',
),
url(
regex=r'^pilots/(?P<username>\w+)/$',
view=PilotDetail.as_view(),
name='pilot_detail',
),
url(
regex=r'^airstrips/$',
view=AirstripList.as_view(),
name='airstrip_list',
),
url(
regex=r'^airstrips/(?P<ident>\w+)/$',
view=AirstripDetail.as_view(),
name='airstrip_detail',
),
url(
regex=r'^bases/$',
view=BaseList.as_view(),
name='base_list',
),
url(
regex=r'^bases/(?P<ident>\w+)/attached/$',
view=BaseAttachedDetail.as_view(),
name='base_attached_detail',
),
url(
regex=r'^bases/(?P<ident>\w+)/unattached/$',
view=BaseUnattachedDetail.as_view(),
name='base_unattached_detail',
),
url(
regex=r'^checkouts/$',
view=FilterFormView.as_view(),
name='checkout_filter',
),
url(
regex=r'^checkouts/edit/$',
view=CheckoutUpdateFormView.as_view(),
name='checkout_update',
),
)
if settings.SERVE_STATIC:
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT,})
)
| from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
from checkouts.views import (
PilotList,
PilotDetail,
AirstripList,
AirstripDetail,
BaseList,
BaseAttachedDetail,
BaseUnattachedDetail,
FilterFormView,
CheckoutUpdateFormView,
)
admin.autodiscover()
urlpatterns = patterns('',
url(r'^emerald/', include(admin.site.urls)),
)
urlpatterns += patterns('',
url(
regex=r'^pilots/$',
view=PilotList.as_view(),
name='pilot_list',
),
url(
regex=r'^pilots/(?P<username>\w+)/$',
view=PilotDetail.as_view(),
name='pilot_detail',
),
url(
regex=r'^airstrips/$',
view=AirstripList.as_view(),
name='airstrip_list',
),
url(
regex=r'^airstrips/(?P<ident>\w+)/$',
view=AirstripDetail.as_view(),
name='airstrip_detail',
),
url(
regex=r'^bases/$',
view=BaseList.as_view(),
name='base_list',
),
url(
regex=r'^bases/(?P<ident>\w+)/attached/$',
view=BaseAttachedDetail.as_view(),
name='base_attached_detail',
),
url(
regex=r'^bases/(?P<ident>\w+)/unattached/$',
view=BaseUnattachedDetail.as_view(),
name='base_unattached_detail',
),
url(
regex=r'^checkouts/$',
view=FilterFormView.as_view(),
name='checkout_filter',
),
url(
regex=r'^update/$',
view=CheckoutUpdateFormView.as_view(),
name='checkout_update',
),
)
if settings.SERVE_STATIC:
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT,})
)
| Python | 0.00003 |
a40ae461472559e2b8740ff1be0b1205254520a1 | Add a manager to centralize webhook API calls | shopify/webhooks/models.py | shopify/webhooks/models.py | from __future__ import unicode_literals
import logging
import uuid
from django.contrib.sites.models import Site
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
import requests
from .utils import shopify_api
logger = logging.getLogger(__name__)
class WebhookManager(models.Manager):
def register(self):
for webhook in self.all():
webhook.register()
def remove(self):
for webhook in self.all():
webhook.remove()
@python_2_unicode_compatible
class Webhook(models.Model):
TOPIC_CHOICES = (
('orders/create', 'Order creation'),
('orders/delete', 'Order deletion'),
('orders/updated', 'Order update'),
('orders/paid', 'Order payment'),
('orders/cancelled', 'Order cancellation'),
('orders/fulfilled', 'Order fulfillment'),
('carts/create', 'Cart creation'),
('carts/update', 'Cart update'),
('checkouts/create', 'Checkout creation'),
('checkouts/update', 'Checkout update'),
('checkouts/delete', 'Checkout deletion'),
('refunds/create', 'Refund create'),
('products/create', 'Product creation'),
('products/update', 'Product update'),
('products/delete', 'Product deletion'),
('collections/create', 'Collection creation'),
('collections/update', 'Collection update'),
('collections/delete', 'Collection deletion'),
('customer_groups/create', 'Customer group creation'),
('customer_groups/update', 'Customer group update'),
('customer_groups/delete', 'Customer group deletion'),
('customers/create', 'Customer creation'),
('customers/enable', 'Customer enable'),
('customers/disable', 'Customer disable'),
('customers/update', 'Customer update'),
('customers/delete', 'Customer deletion'),
('fulfillments/create', 'Fulfillment creation'),
('fulfillments/update', 'Fulfillment update'),
('shop/update', 'Shop update'),
)
objects = WebhookManager()
# Automatically generated GUID for the local webhook. This
# GUID is also used to construct a unique URL.
id = models.CharField(primary_key=True, default=uuid.uuid4,
max_length=36, editable=False)
# An accepted event that will trigger the webhook
topic = models.CharField(max_length=32, choices=TOPIC_CHOICES)
# A unique Shopify ID for the webhook
webhook_id = models.IntegerField(editable=False)
def __str__(self):
return self.path
def save(self, *args, **kwargs):
if not self.webhook_id:
self.register()
super(Webhook, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
if self.webhook_id:
self.remove()
super(Webhook, self).delete(*args, **kwargs)
@property
def path(self):
return "/%s/%s/" % (self.topic, self.id)
def get_absolute_url(self):
base = 'https://%s' % Site.objects.get_current().domain
return base + self.path
def register(self):
payload = {'webhook': {'topic': self.topic,
'address': self.get_absolute_url(),
'format': 'json'}}
try:
resp = requests.post(shopify_api('/admin/webhooks.json'),
json=payload)
resp.raise_for_status()
webhook_id = resp.json()['webhook']['id']
except requests.exceptions.RequestException:
logger.error("Webhook creation returned %s: %s" % (resp.status_code,
resp.text))
else:
self.webhook_id = webhook_id
def remove(self):
try:
resp = requests.delete(shopify_api('/admin/webhooks/%d.json' % self.webhook_id))
resp.raise_for_status()
except requests.exceptions.RequestException:
logger.error("Webhook removal returned %s: %s" % (resp.status_code,
resp.text))
| from __future__ import unicode_literals
import logging
import uuid
from django.contrib.sites.models import Site
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
import requests
from .utils import shopify_api
logger = logging.getLogger(__name__)
@python_2_unicode_compatible
class Webhook(models.Model):
TOPIC_CHOICES = (
('orders/create', 'Order creation'),
('orders/delete', 'Order deletion'),
('orders/updated', 'Order update'),
('orders/paid', 'Order payment'),
('orders/cancelled', 'Order cancellation'),
('orders/fulfilled', 'Order fulfillment'),
('carts/create', 'Cart creation'),
('carts/update', 'Cart update'),
('checkouts/create', 'Checkout creation'),
('checkouts/update', 'Checkout update'),
('checkouts/delete', 'Checkout deletion'),
('refunds/create', 'Refund create'),
('products/create', 'Product creation'),
('products/update', 'Product update'),
('products/delete', 'Product deletion'),
('collections/create', 'Collection creation'),
('collections/update', 'Collection update'),
('collections/delete', 'Collection deletion'),
('customer_groups/create', 'Customer group creation'),
('customer_groups/update', 'Customer group update'),
('customer_groups/delete', 'Customer group deletion'),
('customers/create', 'Customer creation'),
('customers/enable', 'Customer enable'),
('customers/disable', 'Customer disable'),
('customers/update', 'Customer update'),
('customers/delete', 'Customer deletion'),
('fulfillments/create', 'Fulfillment creation'),
('fulfillments/update', 'Fulfillment update'),
('shop/update', 'Shop update'),
)
# Automatically generated GUID for the local webhook. This
# GUID is also used to construct a unique URL.
id = models.CharField(primary_key=True, default=uuid.uuid4,
max_length=36, editable=False)
# An accepted event that will trigger the webhook
topic = models.CharField(max_length=32, choices=TOPIC_CHOICES)
# A unique Shopify ID for the webhook
webhook_id = models.IntegerField(editable=False)
def __str__(self):
return self.path
def save(self, *args, **kwargs):
if not self.webhook_id:
self.create()
super(Webhook, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
if self.webhook_id:
self.remove()
super(Webhook, self).delete(*args, **kwargs)
@property
def path(self):
return "/%s/%s/" % (self.topic, self.id)
def get_absolute_url(self):
base = 'https://%s' % Site.objects.get_current().domain
return base + self.path
def create(self):
payload = {'webhook': {'topic': self.topic,
'address': self.get_absolute_url(),
'format': 'json'}}
try:
resp = requests.post(shopify_api('/admin/webhooks.json'),
json=payload)
resp.raise_for_status()
webhook_id = resp.json()['webhook']['id']
except requests.exceptions.RequestException:
logger.error("Webhook creation returned %s: %s" % (resp.status_code,
resp.text))
else:
self.webhook_id = webhook_id
def remove(self):
try:
resp = requests.delete(shopify_api('/admin/webhooks/%d.json' % self.webhook_id))
resp.raise_for_status()
except requests.exceptions.RequestException:
logger.error("Webhook removal returned %s: %s" % (resp.status_code,
resp.text))
| Python | 0.000001 |
220f4f7d2d5e94760576cddb607478ef7345a901 | add xtheme plugin to render only products which have discount | shuup/discounts/plugins.py | shuup/discounts/plugins.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2019, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django import forms
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from shuup.discounts.models import Discount
from shuup.front.template_helpers.general import get_listed_products
from shuup.xtheme import TemplatedPlugin
from shuup.xtheme.plugins.forms import GenericPluginForm, TranslatableField
class ProductSelectionConfigForm(GenericPluginForm):
"""
A configuration form for the DiscountedProductsPlugin
"""
def populate(self):
"""
A custom populate method to display product choices
"""
for field in self.plugin.fields:
if isinstance(field, tuple):
name, value = field
value.initial = self.plugin.config.get(name, value.initial)
self.fields[name] = value
discounts_qs = Discount.objects.filter(
Q(shops=self.request.shop, active=True),
Q(Q(product__isnull=False) | Q(category__isnull=False, exclude_selected_category=False))
)
self.fields["discounts"] = forms.ModelMultipleChoiceField(
queryset=discounts_qs,
label=_("Discounts"),
help_text=_(
"Select all discounts to render products from. Only active discounts that have "
"product or category linked are available."
),
required=True,
initial=self.plugin.config.get("discounts", None)
)
def clean(self):
"""
A custom clean method to transform selected discounts into a list of ids
"""
cleaned_data = super(ProductSelectionConfigForm, self).clean()
if cleaned_data.get("discounts"):
cleaned_data["discounts"] = [discount.pk for discount in cleaned_data["discounts"]]
return cleaned_data
class DiscountedProductsPlugin(TemplatedPlugin):
identifier = "discount_product"
name = _("Discounted Products")
template_name = "shuup/discounts/product_discount_plugin.jinja"
editor_form_class = ProductSelectionConfigForm
fields = [
("title", TranslatableField(label=_("Title"), required=False, initial="")),
("count", forms.IntegerField(label=_("Count"), min_value=1, initial=4)),
("orderable_only", forms.BooleanField(
label=_("Only show in-stock and orderable items"),
help_text=_(
"Warning: The final number of products can be lower than 'Count' "
"as it will filter out unorderable products from a set of 'Count' products."
),
initial=True, required=False
))
]
def get_context_data(self, context):
count = self.config.get("count", 4)
orderable_only = self.config.get("orderable_only", True)
discounts = self.config.get("discounts")
products = []
if discounts:
# make sure to have only available discounts
discounts = Discount.objects.available(shop=context["request"].shop).filter(pk__in=discounts)
extra_filters = Q(
Q(product_discounts__in=discounts) | Q(shop_products__categories__category_discounts__in=discounts)
)
products = get_listed_products(context, count, orderable_only=orderable_only, extra_filters=extra_filters)
return {
"request": context["request"],
"title": self.get_translated_value("title"),
"products": products
}
| # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2019, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django import forms
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from shuup.discounts.models import Discount
from shuup.front.template_helpers.general import get_listed_products
from shuup.xtheme import TemplatedPlugin
from shuup.xtheme.plugins.forms import GenericPluginForm, TranslatableField
class ProductSelectionConfigForm(GenericPluginForm):
"""
A configuration form for the DiscountedProductsPlugin
"""
def populate(self):
"""
A custom populate method to display product choices
"""
for field in self.plugin.fields:
if isinstance(field, tuple):
name, value = field
value.initial = self.plugin.config.get(name, value.initial)
self.fields[name] = value
discounts_qs = Discount.objects.filter(
Q(shops=self.request.shop, active=True),
Q(Q(product__isnull=False) | Q(category__isnull=False, exclude_selected_category=False))
)
self.fields["discounts"] = forms.ModelMultipleChoiceField(
queryset=discounts_qs,
label=_("Discounts"),
help_text=_(
"Select all discounts to render products from. Only active discounts that have "
"product or category linked are available."
),
required=True,
initial=self.plugin.config.get("discounts", None)
)
def clean(self):
"""
A custom clean method to transform selected discounts into a list of ids
"""
cleaned_data = super(ProductSelectionConfigForm, self).clean()
if cleaned_data.get("discounts"):
cleaned_data["discounts"] = [discount.pk for discount in cleaned_data["discounts"]]
return cleaned_data
class DiscountedProductsPlugin(TemplatedPlugin):
identifier = "discount_product"
name = _("Discounted Products")
template_name = "shuup/discounts/product_discount_plugin.jinja"
editor_form_class = ProductSelectionConfigForm
fields = [
("title", TranslatableField(label=_("Title"), required=False, initial="")),
("count", forms.IntegerField(label=_("Count"), min_value=1, initial=4)),
("orderable_only", forms.BooleanField(
label=_("Only show in-stock and orderable items"),
help_text=_(
"Warning: The final number of products can be lower than 'Count' "
"as it will filter out unorderable products from a set of 'Count' products."
),
initial=True, required=False
))
]
def get_context_data(self, context):
count = self.config.get("count", 4)
orderable_only = self.config.get("orderable_only", True)
discounts = self.config.get("discounts")
if discounts:
# make sure to have only available discounts
discounts = Discount.objects.available(shop=context["request"].shop).filter(pk__in=discounts)
extra_filters = Q(
Q(product_discounts__in=discounts) | Q(shop_products__categories__category_discounts__in=discounts)
)
products = get_listed_products(context, count, orderable_only=orderable_only, extra_filters=extra_filters)
else:
products = []
return {
"request": context["request"],
"title": self.get_translated_value("title"),
"products": products
}
| Python | 0 |
3c9d45ad67b1a1c274cc5ee7a78d174595445733 | Update websocket | websocket_data_collector.py | websocket_data_collector.py | #!venv/bin/python
'''
websocket_data_collector.py
This script uses websockets to transmit data collected by the NeuroPy module to a remote server.
'''
import NeuroPy.NeuroPy as NP
import socketIO_client
import json
import click
from threading import Lock
CLIENT_ID = "CLIENT1"
# declare this globally
socketIO = None
lock = None
def on_connect():
print("connected")
def on_disconnect():
print("disconnected")
def on_callback_response(*args):
print("On callback response: ", args)
# generic callback function for neuropy
# which sends the data collected over socketio
def generic_callback(variable_name, variable_val):
# generate the dictionary to send to the remote server
# as specified in the doc
if variable_name == "rawValue":
return
global filename
print("writing")
filename.write("{} {}\n".format(variable_name, variable_val))
def start_data_collection(serial_port, num_seconds=-1):
headset_obj = NP.NeuroPy(serial_port, 9600, log=False)
headset_obj.setCallBack("attention", generic_callback)
headset_obj.setCallBack("meditation", generic_callback)
headset_obj.setCallBack("rawValue", generic_callback)
headset_obj.setCallBack("delta", generic_callback)
headset_obj.setCallBack("theta", generic_callback)
headset_obj.setCallBack("lowAlpha", generic_callback)
headset_obj.setCallBack("highAlpha", generic_callback)
headset_obj.setCallBack("lowBeta", generic_callback)
headset_obj.setCallBack("highBeta", generic_callback)
headset_obj.setCallBack("lowGamma", generic_callback)
headset_obj.setCallBack("midGamma", generic_callback)
headset_obj.setCallBack("poorSignal", generic_callback)
headset_obj.setCallBack("blinkStrength", generic_callback)
headset_obj.start()
if num_seconds != -1:
time.sleep(num_seconds)
headset_obj.stop()
@click.command()
@click.argument('runfile')
@click.argument('clientid')
@click.option('--serial_port', default="/dev/tty.MindWaveMobile-SerialPo", help="Serial port of bluetooth headset")
@click.option('--time', default=5, help="Number of seconds to collect data")
def main(runfile, clientid, serial_port, time):
global filename
filename = open("{}:{}".format(runfile,clientid), "w")
start_data_collection(serial_port, time)
if __name__ == "__main__":
main()
| #!venv/bin/python
'''
websocket_data_collector.py
This script uses websockets to transmit data collected by the NeuroPy module to a remote server.
'''
import NeuroPy.NeuroPy as NP
import socketIO_client
import json
import click
from threading import Lock
CLIENT_ID = "CLIENT1"
# declare this globally
socketIO = None
lock = None
def on_connect():
print("connected")
def on_disconnect():
print("disconnected")
def on_callback_response(*args):
print("On callback response: ", args)
# generic callback function for neuropy
# which sends the data collected over socketio
def generic_callback(variable_name, variable_val):
# generate the dictionary to send to the remote server
# as specified in the doc
return_dict = {}
return_dict["client_id"] = CLIENT_ID
# for now, do nothing when setting rawData
if variable_name == "rawData":
return
return_dict["data"] = [{"type": variable_name, "value": variable_val}]
lock.acquire()
socketIO.emit("data", return_dict, on_callback_response)
lock.release()
def start_data_collection(serial_port, num_seconds=-1):
headset_obj = NP.NeuroPy(serial_port, 9600, log=False)
headset_obj.setCallBack("attention", generic_callback)
headset_obj.setCallBack("meditation", generic_callback)
headset_obj.setCallBack("rawValue", generic_callback)
headset_obj.setCallBack("delta", generic_callback)
headset_obj.setCallBack("theta", generic_callback)
headset_obj.setCallBack("lowAlpha", generic_callback)
headset_obj.setCallBack("highAlpha", generic_callback)
headset_obj.setCallBack("lowBeta", generic_callback)
headset_obj.setCallBack("highBeta", generic_callback)
headset_obj.setCallBack("lowGamma", generic_callback)
headset_obj.setCallBack("midGamma", generic_callback)
headset_obj.setCallBack("poorSignal", generic_callback)
headset_obj.setCallBack("blinkStrength", generic_callback)
headset_obj.start()
@click.command()
@click.argument('host')
@click.argument('port')
@click.option('--serial_port', default="/dev/tty.MindWaveMobile-SerialPo", help="Serial port of bluetooth headset")
@click.option('--time', default=-1, help="Number of seconds to collect data")
def main(host, port, serial_port, time):
lock = Lock()
socketIO = socketIO_client.SocketIO(host, port)
print("Got here")
#socketIO.on("connect", on_connect)
#socketIO.on("disconnected", on_disconnect)
#start_data_collection(serial_port, time)
for i in range(10):
socketIO.emit("data", {"test": i})
socketIO.wait(seconds=1)
if __name__ == "__main__":
main()
| Python | 0.000001 |
531c81d5654783da9443a2392fe878344ff07b3c | Update feed2db.py | newsman/bin/text_based_feeds/feed2db.py | newsman/bin/text_based_feeds/feed2db.py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
feed2db works to turn text-based feed list into database
"""
# @author chengdujin
# @contact chengdujin@gmail.com
# @created Jul. 30, 2013
import sys
reload(sys)
sys.setdefaultencoding('UTF-8')
sys.path.append('../..')
from config.settings import Collection
from config.settings import db
# CONSTANTS
from config.settings import FEED_REGISTRAR
#FILE_PREFIX = '/home/work/newsman/newsman/bin/text_based_feeds/feed_lists/'
#FILE_PREFIX = '/home/ubuntu/newsman/newsman/bin/text_based_feeds/feed_lists/'
FILE_PREFIX = '/home/jinyuan/Downloads/newsman/newsman/bin/text_based_feeds/feed_lists/'
def _parse_task(line):
"""
read *_feeds_list.txt
"""
line = line.strip()
if line:
task = line.strip().split('*|*')
# task[1] refers to categories
if len(task) == 5:
return task[0].strip(), task[1].strip(), task[2].strip(), task[3].strip(), task[4].strip(), None
elif len(task) == 6:
return task[0].strip(), task[1].strip(), task[2].strip(), task[3].strip(), task[4].strip(), task[5].strip()
else:
return None
else:
return None
def _convert(language='en', country=None):
"""
turn text-based feed infor into database items
Note. 1. categories: [(), ()]
"""
# read in file content
feeds_list = open('%s%s_%s_feeds_list' % (FILE_PREFIX, language, country), 'r')
lines = feeds_list.readlines()
feeds_list.close()
# open datbase
db_feeds = Collection(db, FEED_REGISTRAR)
db_id_list = open('db_id_list', 'w')
for line in lines:
if line.strip():
language, category, transcoder, feed_link, feed_title, labels = _parse_task(line)
if feed_link:
category = '%s::%s' % (country, category)
# break labels
if labels:
labels = ['%s::%s' % (category, label.strip()) for label in labels.split(',')]
print feed_link
existing_item = db_feeds.find_one({'feed_link':feed_link})
if not existing_item:
print '+'
db_feeds.save({'language': language, 'countries':[country], 'feed_link': feed_link, 'categories': [category], 'labels':labels, 'feed_title': feed_title, 'latest_update': None, 'updated_times': 0, 'transcoder': transcoder})
else:
print '*'
new_item = existing_item
new_item['language'] = language
new_item['categories'] = list(set(existing_item['categories'].extend([category])))
new_item['labels'] = list(set(existing_item['labels'].extend(labels)))
new_item['countries'] = list(set(existing_item['countries'].append(country)))
new_item['transcoder'] = transcoder
new_item['feed_title'] = feed_title
db_feeds.update({'_id': existing_item['_id']}, new_item)
db_id_list.write(str(existing_item['_id']) + '\n')
else:
continue
else:
continue
db_id_list.close()
if __name__ == "__main__":
if len(sys.argv) > 1:
_convert(sys.argv[1], sys.argv[2])
else:
print 'Please indicate a language and country'
| #!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
feed2db works to turn text-based feed list into database
"""
# @author chengdujin
# @contact chengdujin@gmail.com
# @created Jul. 30, 2013
import sys
reload(sys)
sys.setdefaultencoding('UTF-8')
sys.path.append('../..')
from config.settings import Collection
from config.settings import db
# CONSTANTS
from config.settings import FEED_REGISTRAR
FILE_PREFIX = '/home/work/newsman/newsman/bin/text_based_feeds/feed_lists/'
#FILE_PREFIX = '/home/ubuntu/newsman/newsman/bin/text_based_feeds/feed_lists/'
#FILE_PREFIX = '/home/jinyuan/Downloads/newsman/newsman/bin/text_based_feeds/feed_lists/'
def _parse_task(line):
"""
read *_feeds_list.txt
"""
line = line.strip()
if line:
task = line.strip().split('*|*')
# task[1] refers to categories
if len(task) == 5:
return task[0].strip(), task[1].strip(), task[2].strip(), task[3].strip(), task[4].strip(), None
elif len(task) == 6:
return task[0].strip(), task[1].strip(), task[2].strip(), task[3].strip(), task[4].strip(), task[5].strip()
else:
return None
else:
return None
def _convert(language='en', country=None):
"""
turn text-based feed infor into database items
Note. 1. categories: [(), ()]
"""
# read in file content
feeds_list = open('%s%s_%s_feeds_list' % (FILE_PREFIX, language, country), 'r')
lines = feeds_list.readlines()
feeds_list.close()
# open datbase
db_feeds = Collection(db, FEED_REGISTRAR)
for line in lines:
if line.strip():
language, category, transcoder, feed_link, feed_title, labels = _parse_task(line)
if feed_link:
category = '%s::%s' % (country, category)
# break labels
if labels:
labels = ['%s::%s' % (category, label.strip()) for label in labels.split(',')]
print feed_title, labels
existing_item = db_feeds.find_one({'link':feed_link})
if not existing_item:
db_feeds.save({'language': language, 'countries':[country], 'feed_link': feed_link, 'categories': [category], 'labels':labels, 'feed_title': feed_title, 'latest_update': None, 'updated_times': 0, 'transcoder': transcoder})
else:
new_item = existing_item
new_item['language'] = language
new_item['categories'] = list(set(new_item['categories'].extend([category])))
new_item['labels'] = list(set(new_item['labels'].extend(labels)))
new_item['countries'] = list(set(new_item['countries'].append(country)))
new_item['transcoder'] = transcoder
new_item['feed_title'] = feed_title
db_feeds.update({'_id': item['_id']}, new_item)
else:
continue
else:
continue
if __name__ == "__main__":
if len(sys.argv) > 1:
_convert(sys.argv[1], sys.argv[2])
else:
print 'Please indicate a language and country'
| Python | 0 |
0cc7fbea3952485e8274c8df1b223fc791181035 | Complete migrate from django to toilets script | ona_migration_script/migrate_toilets.py | ona_migration_script/migrate_toilets.py | import argparse
from ona import OnaApiClient
def generate_location(lat, lon):
return ' '.join([str(lat), str(lon)])
CONVERSIONS = {
'code': 'toilet_code', 'section': 'toilet_section',
'cluster': 'toilet_cluster'}
ADDITIONS = {
'toilet_location': (generate_location, ['lat', 'lon'])
}
DEFAULTS = {
'toilet_state': 'no_issue', 'toilet_issue': '', 'toilet_issue_date': ''}
parser = argparse.ArgumentParser(description='Migrate submissions')
parser.add_argument(
'url', type=str,
help='The full URL to get the JSON toilet information from')
parser.add_argument(
'to_id', type=str,
help="The id (number) of the form to migrate submissions to")
parser.add_argument(
'username', type=str, help='The Ona username used to log in')
parser.add_argument(
'password', type=str, help='The Ona password used to log in')
args = parser.parse_args()
client = OnaApiClient(args.username, args.password)
def get_toilet_info_from_django():
url = args.url
headers = {
"Content-type": "application/json; charset=utf-8"
}
r = client.session.request(
'GET', url, headers=headers)
r.raise_for_status()
return r.json()
def get_fields_from_form(formid):
form = client.get_form_information(formid)
fields = []
for child in form.get('children'):
fields.append(child.get('name'))
return fields
toilet_data = get_toilet_info_from_django()
to_fields = get_fields_from_form(args.to_id)
for toilet in toilet_data:
new_toilet = toilet.copy()
# Add fields
for field, (function, arguments) in ADDITIONS.iteritems():
arguments = [toilet[arg] for arg in arguments]
new_toilet[field] = function(*arguments)
# Migrate fields
for field in toilet:
if field in CONVERSIONS:
new_toilet[CONVERSIONS[field]] = toilet[field]
# Remove deleted fields
if field not in to_fields:
del new_toilet[field]
# Add missing fields
for field in to_fields:
if field not in new_toilet:
new_toilet[field] = DEFAULTS.get(field, None)
# Post submission to new form
form_id_string = client.get_form(args.to_id)['id_string']
try:
client.submission({
"id": form_id_string,
"submission": new_toilet,
})
except:
print "Error sending form %s. Submission: " % form_id_string
print new_toilet
| Python | 0.000001 | |
a7827ecf5e480c228c881180e63633712e3dbc3c | Modify ARDUINO_SEARCH_PATHS to include default ubuntu package location | site_scons/find_avrdude.py | site_scons/find_avrdude.py | import sys
import os
from itertools import chain
from path import path
home_dir = path('~').expand()
ARDUINO_SEARCH_PATHS = [home_dir, ]
if os.name == 'nt':
from win32com.shell import shell, shellcon
mydocs = shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, 0, 0)
AVRDUDE_NAME = 'avrdude.exe'
ARDUINO_SEARCH_PATHS += [path(mydocs),
path('%SYSTEMDRIVE%/').expand(),
path('%PROGRAMFILES%').expand(), ]
else:
AVRDUDE_NAME = 'avrdude'
ARDUINO_SEARCH_PATHS += [path("/usr/share/")]
def get_arduino_paths():
fs = []
for p in ARDUINO_SEARCH_PATHS:
fs += get_avrdude_list(p)
if not fs:
print >> sys.stderr, '''\
ERROR: arduino install directory not found!
Searched:
%s''' % '\n '.join(ARDUINO_SEARCH_PATHS)
sys.exit(1)
fs.sort(key=lambda x: -x.ctime)
avrdude = fs[0]
p = avrdude.parent
while p and p.name != 'hardware':
p = p.parent
if not p:
print >> sys.stderr, '''Arduino install path not found.'''
sys.exit(1)
arduino_path = p.parent
avrdude_conf = list(arduino_path.walkfiles('avrdude.conf'))
if not avrdude_conf:
print >> sys.stderr, '''avrdude configuration (avrdude.conf) path not found.'''
sys.exit(1)
else:
avrdude_conf = avrdude_conf[0]
return arduino_path, avrdude, avrdude_conf
def get_avrdude_list(p):
return list(set(chain(*[d.walkfiles(AVRDUDE_NAME) for d in p.dirs('arduino*')])))
if __name__ == '__main__':
arduino_path, avrdude, avrdude_conf = get_arduino_paths()
print 'found arduino path:', arduino_path
print 'using newest avrdude:', avrdude
print 'using avrdude config:', avrdude_conf
| import sys
import os
from itertools import chain
from path import path
home_dir = path('~').expand()
ARDUINO_SEARCH_PATHS = [home_dir, ]
if os.name == 'nt':
from win32com.shell import shell, shellcon
mydocs = shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, 0, 0)
AVRDUDE_NAME = 'avrdude.exe'
ARDUINO_SEARCH_PATHS += [path(mydocs),
path('%SYSTEMDRIVE%/').expand(),
path('%PROGRAMFILES%').expand(), ]
else:
AVRDUDE_NAME = 'avrdude'
ARDUINO_SEARCH_PATHS += [home_dir / path('local/opt'), ]
def get_arduino_paths():
fs = []
for p in ARDUINO_SEARCH_PATHS:
fs += get_avrdude_list(p)
if not fs:
print >> sys.stderr, '''\
ERROR: arduino install directory not found!
Searched:
%s''' % '\n '.join(ARDUINO_SEARCH_PATHS)
sys.exit(1)
fs.sort(key=lambda x: -x.ctime)
avrdude = fs[0]
p = avrdude.parent
while p and p.name != 'hardware':
p = p.parent
if not p:
print >> sys.stderr, '''Arduino install path not found.'''
sys.exit(1)
arduino_path = p.parent
avrdude_conf = list(arduino_path.walkfiles('avrdude.conf'))
if not avrdude_conf:
print >> sys.stderr, '''avrdude configuration (avrdude.conf) path not found.'''
sys.exit(1)
else:
avrdude_conf = avrdude_conf[0]
return arduino_path, avrdude, avrdude_conf
def get_avrdude_list(p):
return list(set(chain(*[d.walkfiles(AVRDUDE_NAME) for d in p.dirs('arduino*')])))
if __name__ == '__main__':
arduino_path, avrdude, avrdude_conf = get_arduino_paths()
print 'found arduino path:', arduino_path
print 'using newest avrdude:', avrdude
print 'using avrdude config:', avrdude_conf
| Python | 0 |
028abc55a2c0e7bf9d727fa73eafff98e5f917d2 | Add sparkhistogram package | Spark_Notes/Spark_Histograms/python/setup.py | Spark_Notes/Spark_Histograms/python/setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
description = "Sparkhistogram contains helper functions for generating data histograms with the Spark DataFrame API."
long_description = """
Use this package, sparkhistogram, together with PySpark for generating data histograms using the Spark DataFrame API.
Currently, the package contains only two functions covering some of the most common and low-complexity use cases.
Use:
- `from sparkhistogram import computeHistogram` -> computeHistogram is a function to compute the count/frequency histogram of a given DataFrame column
- `from sparkhistogram import computeWeightedHistogram` -> computeWeightedHistogram is a function to compute the weighted histogram of a given DataFrame column
```
def computeHistogram(df: "DataFrame", value_col: str, min: int, max: int, bins: int) -> "DataFrame"
Parameters
----------
df: the dataframe with the data to compute
value_col: column name on which to compute the histogram
min: minimum value in the histogram
max: maximum value in the histogram
bins: number of histogram buckets to compute
Output DataFrame
----------------
bucket: the bucket number, range from 1 to bins (included)
value: midpoint value of the given bucket
count: number of values in the bucket
```
## Run this example in the PySpark shell
Note: requires PySpark version 3.1 or higher.
`bin/pyspark`
```
# import the helper function to generate the histogram using Spark DataFrame operations
from sparkhistogram import computeHistogram
# generate some toy data
num_events = 100
scale = 100
seed = 4242
df = spark.sql(f"select random({seed}) * {scale} as random_value from range({num_events})")
# define the DataFrame transformation to compute the histogram
histogram = computeHistogram(df, "random_value", -20, 90, 11)
# with Spark 3.3.0 and higher you can also use df.transform
# histogram = df.transform(computeHistogram, "random_value", -20, 90, 11)
# fetch and display the (toy) data
histogram.show()
# expected output:
+------+-----+-----+
|bucket|value|count|
+------+-----+-----+
| 1|-15.0| 0|
| 2| -5.0| 0|
| 3| 5.0| 6|
| 4| 15.0| 10|
| 5| 25.0| 15|
| 6| 35.0| 12|
| 7| 45.0| 9|
| 8| 55.0| 7|
| 9| 65.0| 10|
| 10| 75.0| 16|
| 11| 85.0| 7|
+------+-----+-----+
```
More details and notebooks with matplotlib visualization of the histograms at:
https://github.com/LucaCanali/Miscellaneous/blob/master/Spark_Notes/Spark_DataFrame_Histograms.md
"""
setup(name='sparkhistogram',
version='0.1',
description=description,
long_description=long_description,
long_description_content_type="text/markdown",
author='Luca Canali',
author_email='luca.canali@cern.ch',
url='https://github.com/LucaCanali/Miscellaneous/blob/master/Spark_Notes/Spark_DataFrame_Histograms.md',
license='Apache License, Version 2.0',
include_package_data=True,
packages=find_packages(),
zip_safe=False,
python_requires='>=3.6',
install_requires=[],
classifiers=[
'Programming Language :: Python :: 3',
'Operating System :: OS Independent',
'License :: OSI Approved :: Apache Software License',
'Intended Audience :: Developers',
'Development Status :: 4 - Beta',
]
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
description = "sparkhistogram contains helper functions for generating data histograms with the Spark DataFrame API and with Spark SQL."
long_description = "sparkhistogram contains helper functions for generating data histograms with the Spark DataFrame API and with Spark SQL."
setup(name='sparkhistogram',
version='0.1',
description=description,
long_description=long_description,
long_description_content_type="text/markdown",
author='Luca Canali',
author_email='luca.canali@cern.ch',
url='https://github.com/LucaCanali/Miscellaneous/blob/master/Spark_Notes/Spark_DataFrame_Histograms.md',
license='Apache License, Version 2.0',
include_package_data=True,
packages=find_packages(),
zip_safe=False,
python_requires='>=3.6',
install_requires=[],
classifiers=[
'Programming Language :: Python :: 3',
'Operating System :: OS Independent',
'License :: OSI Approved :: Apache Software License',
'Intended Audience :: Developers',
'Development Status :: 4 - Beta',
]
)
| Python | 0 |
03c237551aa08cb70fd397cc348e75531cdabd0e | fix schemas for password views | src/eduid_webapp/security/schemas.py | src/eduid_webapp/security/schemas.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016 NORDUnet A/S
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# 3. Neither the name of the NORDUnet nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
from marshmallow import fields
from eduid_common.api.schemas.base import FluxStandardAction, EduidSchema
class CredentialSchema(EduidSchema):
credential_type = fields.String(required=True)
created_ts = fields.String(required=True)
success_ts = fields.String(required=True)
class CredentialList(EduidSchema):
credentials = fields.Nested(CredentialSchema, many=True)
csrf_token = fields.String(required=True)
class SecurityResponseSchema(FluxStandardAction):
payload = fields.Nested(CredentialList, only=('credentials', 'csrf_token'))
csrf_token = fields.String(attribute='csrf_token')
class CsrfSchema(EduidSchema):
csrf_token = fields.String(required=True)
class SecurityPasswordSchema(EduidSchema):
password = fields.String(required=True)
new_password = fields.String(required=True)
repeat_password = fields.String(required=True)
csrf_token = fields.String(required=True)
| # -*- coding: utf-8 -*-
#
# Copyright (c) 2016 NORDUnet A/S
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# 3. Neither the name of the NORDUnet nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
from marshmallow import fields
from eduid_common.api.schemas.base import EduidSchema
class CredentialSchema(EduidSchema):
credential_type = fields.String(required=True)
created_ts = fields.String(required=True)
success_ts = fields.String(required=True)
class CredentialList(EduidSchema):
credentials = fields.Nested(CredentialSchema, many=True)
csrf_token = fields.String(required=True)
class SecurityResponseSchema(EduidSchema):
payload = fields.Nested(CredentialList, only=('credentials', 'csrf_token'))
class CsrfSchema(EduidSchema):
csrf_token = fields.String(required=True)
class SecurityPasswordSchema(EduidSchema):
password = fields.String(required=True)
new_password = fields.String(required=True)
repeat_password = fields.String(required=True)
csrf_token = fields.String(required=True)
| Python | 0.000002 |
daa92b15852b3572d7ef03392b061184dbbc76c1 | fix to use the right cert in AuthServer provisioning | Code/scripts/provisionAuthServer.py | Code/scripts/provisionAuthServer.py | #!/usr/bin/env python
from __future__ import print_function
from subprocess import check_call
import os
import argparse
parser = argparse.ArgumentParser(description="Generates the keys for authServer.exe")
parser.add_argument("--scriptPath", required="true", help="The path to the directory that contains the scripts used by provisionAuthServer.py")
args = parser.parse_args()
check_call([os.path.join(args.scriptPath, "createPrincipal.py"), "5", "AuthServer"])
check_call(["./cryptUtility.exe", "-EncapsulateMessage", "authServer/cert", "authServer/signingKeyMetaData", "AuthServerPrivateKey.xml", "authServer/signingKey"])
check_call(["cp", "AuthServerPublicKey.xml", "authServer/signingCert"])
| #!/usr/bin/env python
from __future__ import print_function
from subprocess import check_call
import os
import argparse
parser = argparse.ArgumentParser(description="Generates the keys for authServer.exe")
parser.add_argument("--scriptPath", required="true", help="The path to the directory that contains the scripts used by provisionAuthServer.py")
args = parser.parse_args()
check_call([os.path.join(args.scriptPath, "createPrincipal.py"), "5", "AuthServer"])
check_call(["./cryptUtility.exe", "-EncapsulateMessage", "AuthServerPublicKey.xml", "authServer/signingKeyMetaData", "AuthServerPrivateKey.xml", "authServer/signingKey"])
check_call(["cp", "AuthServerPublicKey.xml", "authServer/signingCert"])
| Python | 0 |
93c34ad24f4dc675f1f8d212a6b1a7e53daf381b | change pinout values | RP/static_funcs.py | RP/static_funcs.py | #-------------------------------------------------------------------------------
# Name: Static funcs
# Purpose:
#
# Author: I070890
#
# Created: 18/01/2015
# Copyright: (c) I070890 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
import time, os, subprocess, multiprocessing
import RPi.GPIO as GPIO
# A couple of variables
# ---------------------
debug = False # debug mode for console output
#debug = True # debug mode for console output
first_iter = True
def init_func():
# Wait for 2 seconds to allow the ultrasonics to settle (probably not needed)
# ---------------------------------------------------------------------------
print "Waiting for 2 seconds....."
time.sleep(2)
# Go
# --
print "Running....\nStart Beep process...."
GPIO.setmode(GPIO.BCM)
def distance(GPIO_ECHO,GPIO_TRIG):
debug_print ("GPIO_TRIG = " + str(GPIO_TRIG) + ",GPIO_ECHO = " + str(GPIO_ECHO))
# Set GPIO Channels
# -----------------
GPIO.setup(GPIO_ECHO, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(GPIO_TRIG, GPIO.OUT)
GPIO.output(GPIO_TRIG, False)
# A couple of variables
# ---------------------
EXIT = 0 # Infinite loop
decpulsetrigger = 0.0001 # Trigger duration
inttimeout = 1000 # Number of loop iterations before timeout called
min_dist = 100
# Never ending loop
# -----------------
while EXIT < 10:
# Trigger high for 0.0001s then low
GPIO.output(GPIO_TRIG, True)
time.sleep(decpulsetrigger)
GPIO.output(GPIO_TRIG, False)
# Wait for echo to go high (or timeout)
i_countdown = inttimeout
while (GPIO.input(GPIO_ECHO) == 0 and i_countdown > 0):
i_countdown -= 1
# If echo is high than the i_countdown not zero
if i_countdown > 0:
# Start timer and init timeout countdown
echostart = time.time()
i_countdown = inttimeout
# Wait for echo to go low (or timeout)
while (GPIO.input(GPIO_ECHO) == 1 and i_countdown > 0):
i_countdown -= 1
# Stop timer
echoend = time.time()
# Echo duration
echoduration = echoend - echostart
# Display distance
if i_countdown > 0:
i_distance = (echoduration*1000000)/58
debug_print("Distance = " + str(i_distance) + "cm")
min_dist = min(min_dist,i_distance)
else:
debug_print("Distance - timeout")
# Wait at least .01s before re trig (or in this case .1s)
time.sleep(.1)
EXIT +=1
return min_dist
def debug_print(line,must_print = False):
if debug or must_print:
print line
def beep_func(printOutput = True, GPIO_ECHO_INPUT = None ):
while True:
if GPIO_ECHO_INPUT != None:
GPIO_ECHO_BEEP = [0]
GPIO_TRIG_BEEP = [1]
else:
GPIO_ECHO_BEEP = 26
GPIO_TRIG_BEEP = 27
calc_dist = distance(GPIO_ECHO_BEEP,GPIO_TRIG_BEEP)
print "BEEP dist is: " + str(calc_dist)
if calc_dist < 60:
cmd = "(speaker-test -t sine -f " + str(75*calc_dist) + " -l 1 -p 1024 -P 4 > /dev/null)& pid=$!; sleep 0.25s; kill -9 $pid"
debug_print(cmd)
os.system(cmd)
time.sleep(0.1)
| #-------------------------------------------------------------------------------
# Name: Static funcs
# Purpose:
#
# Author: I070890
#
# Created: 18/01/2015
# Copyright: (c) I070890 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
import time, os, subprocess, multiprocessing
import RPi.GPIO as GPIO
# A couple of variables
# ---------------------
debug = False # debug mode for console output
#debug = True # debug mode for console output
first_iter = True
def init_func():
# Wait for 2 seconds to allow the ultrasonics to settle (probably not needed)
# ---------------------------------------------------------------------------
print "Waiting for 2 seconds....."
time.sleep(2)
# Go
# --
print "Running....\nStart Beep process...."
GPIO.setmode(GPIO.BCM)
def distance(GPIO_ECHO,GPIO_TRIG):
debug_print ("GPIO_TRIG = " + str(GPIO_TRIG) + ",GPIO_ECHO = " + str(GPIO_ECHO))
# Set GPIO Channels
# -----------------
GPIO.setup(GPIO_ECHO, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(GPIO_TRIG, GPIO.OUT)
GPIO.output(GPIO_TRIG, False)
# A couple of variables
# ---------------------
EXIT = 0 # Infinite loop
decpulsetrigger = 0.0001 # Trigger duration
inttimeout = 1000 # Number of loop iterations before timeout called
min_dist = 100
# Never ending loop
# -----------------
while EXIT < 10:
# Trigger high for 0.0001s then low
GPIO.output(GPIO_TRIG, True)
time.sleep(decpulsetrigger)
GPIO.output(GPIO_TRIG, False)
# Wait for echo to go high (or timeout)
i_countdown = inttimeout
while (GPIO.input(GPIO_ECHO) == 0 and i_countdown > 0):
i_countdown -= 1
# If echo is high than the i_countdown not zero
if i_countdown > 0:
# Start timer and init timeout countdown
echostart = time.time()
i_countdown = inttimeout
# Wait for echo to go low (or timeout)
while (GPIO.input(GPIO_ECHO) == 1 and i_countdown > 0):
i_countdown -= 1
# Stop timer
echoend = time.time()
# Echo duration
echoduration = echoend - echostart
# Display distance
if i_countdown > 0:
i_distance = (echoduration*1000000)/58
debug_print("Distance = " + str(i_distance) + "cm")
min_dist = min(min_dist,i_distance)
else:
debug_print("Distance - timeout")
# Wait at least .01s before re trig (or in this case .1s)
time.sleep(.1)
EXIT +=1
return min_dist
def debug_print(line,must_print = False):
if debug or must_print:
print line
def beep_func(printOutput = True, GPIO_ECHO_INPUT = None ):
while True:
if GPIO_ECHO_INPUT != None:
GPIO_ECHO_BEEP = [0]
GPIO_TRIG_BEEP = [1]
else:
GPIO_ECHO_BEEP = 22
GPIO_TRIG_BEEP = 27
calc_dist = distance(GPIO_ECHO_BEEP,GPIO_TRIG_BEEP)
print "BEEP dist is: " + str(calc_dist)
if calc_dist < 60:
cmd = "(speaker-test -t sine -f " + str(75*calc_dist) + " -l 1 -p 1024 -P 4 > /dev/null)& pid=$!; sleep 0.25s; kill -9 $pid"
print cmd
os.system(cmd)
time.sleep(0.1)
| Python | 0.000002 |
fe4c62acd52a4060eebf4284c15c465970ea8932 | remove duplicate enum key (#7173) | sdk/cognitiveservices/azure-cognitiveservices-language-luis/azure/cognitiveservices/language/luis/authoring/models/_luis_authoring_client_enums.py | sdk/cognitiveservices/azure-cognitiveservices-language-luis/azure/cognitiveservices/language/luis/authoring/models/_luis_authoring_client_enums.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from enum import Enum
class TrainingStatus(str, Enum):
needs_training = "NeedsTraining"
in_progress = "InProgress"
trained = "Trained"
class OperationStatusType(str, Enum):
failed = "Failed"
success = "Success"
| # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from enum import Enum
class TrainingStatus(str, Enum):
needs_training = "NeedsTraining"
in_progress = "InProgress"
trained = "Trained"
class OperationStatusType(str, Enum):
failed = "Failed"
failed = "FAILED"
success = "Success"
| Python | 0.000003 |
b56882c5d3a145b571deb10f901f35c071c5c34d | Update release.py to blacklist thumbs.db and .ds_store as opposed to whitelisting known file types. | Release/release.py | Release/release.py | VERSION = '0.2.0'
import shutil
import os
import io
import sys
def copyDirectory(source, target):
source = source.replace('/', os.sep)
target = target.replace('/', os.sep)
os.makedirs(target)
for file in os.listdir(source):
fullpath = os.path.join(source, file)
fulltargetpath = os.path.join(target, file)
if os.path.isdir(fullpath):
copyDirectory(fullpath, fulltargetpath)
elif file.lower() in ('.ds_store', 'thumbs.db'):
pass
else:
shutil.copyfile(fullpath, fulltargetpath)
def readFile(path):
c = open(path.replace('/', os.sep), 'rt')
text = c.read()
c.close()
return text
def writeFile(path, content, lineEnding):
content = content.replace("\r\n", "\n").replace("\r", "\n").replace("\n", lineEnding)
ucontent = unicode(content, 'utf-8')
with io.open(path.replace('/', os.sep), 'w', newline=lineEnding) as f:
f.write(ucontent)
def runCommand(cmd):
c = os.popen(cmd)
output = c.read()
c.close()
return output
def main(args):
librariesForRelease = [
'Audio',
'Core',
'Easing',
'FileIO',
'FileIOCommon',
'Game',
'Gamepad',
'Graphics2D',
'GraphicsText',
'Http',
'ImageEncoder',
'ImageResources',
'ImageWebResources',
'Json',
'Math',
'Random',
'Resources',
'UserData',
'Web',
'Xml',
]
if len(args) != 1:
print("usage: python release.py windows|mono")
return
platform = args[0]
if not platform in ('windows', 'mono'):
print ("Invalid platform: " + platform)
return
copyToDir = 'crayon-' + VERSION + '-' + platform
if os.path.exists(copyToDir):
shutil.rmtree(copyToDir)
os.makedirs(copyToDir)
if platform == 'mono':
print runCommand('xbuild /p:Configuration=Release ../Compiler/CrayonOSX.sln')
else:
print runCommand(' '.join([
r'C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe',
'/p:Configuration=Release',
r'..\Compiler\CrayonWindows.sln'
]))
shutil.copyfile('../Compiler/bin/Release/Crayon.exe', copyToDir + '/crayon.exe')
shutil.copyfile('../Compiler/bin/Release/Interpreter.dll', copyToDir + '/Interpreter.dll')
shutil.copyfile('../Compiler/bin/Release/Resources.dll', copyToDir + '/Resources.dll')
shutil.copyfile('../Compiler/bin/Release/LICENSE.txt', copyToDir + '/LICENSE.txt')
shutil.copyfile('../README.md', copyToDir + '/README.md')
if platform == 'windows':
setupFile = readFile("setup-windows.txt")
writeFile(copyToDir + '/Setup Instructions.txt', setupFile, '\r\n')
if platform == 'mono':
setupFile = readFile("setup-mono.md")
writeFile(copyToDir + '/Setup Instructions.txt', setupFile, '\n')
for lib in librariesForRelease:
sourcePath = '../Libraries/' + lib
targetPath = copyToDir + '/libs/' + lib
copyDirectory(sourcePath, targetPath)
print("Release directory created: " + copyToDir)
main(sys.argv[1:])
| VERSION = '0.2.0'
import shutil
import os
import io
import sys
def copyDirectory(source, target):
source = source.replace('/', os.sep)
target = target.replace('/', os.sep)
os.makedirs(target)
for file in os.listdir(source):
fullpath = os.path.join(source, file)
fulltargetpath = os.path.join(target, file)
if os.path.isdir(fullpath):
copyDirectory(fullpath, fulltargetpath)
elif file.endswith('.txt') or file.endswith('.cry'):
# The intent of this is to avoid os generated files like thumbs.db
# Tweak if new file types are added.
shutil.copyfile(fullpath, fulltargetpath)
def readFile(path):
c = open(path.replace('/', os.sep), 'rt')
text = c.read()
c.close()
return text
def writeFile(path, content, lineEnding):
content = content.replace("\r\n", "\n").replace("\r", "\n").replace("\n", lineEnding)
ucontent = unicode(content, 'utf-8')
with io.open(path.replace('/', os.sep), 'w', newline=lineEnding) as f:
f.write(ucontent)
def runCommand(cmd):
c = os.popen(cmd)
output = c.read()
c.close()
return output
def main(args):
librariesForRelease = [
'Audio',
'Core',
'Easing',
'FileIO',
'FileIOCommon',
'Game',
'Gamepad',
'Graphics2D',
'GraphicsText',
'Http',
'ImageEncoder',
'ImageResources',
'ImageWebResources',
'Json',
'Math',
'Random',
'Resources',
'UserData',
'Web',
'Xml',
]
if len(args) != 1:
print("usage: python release.py windows|mono")
return
platform = args[0]
if not platform in ('windows', 'mono'):
print ("Invalid platform: " + platform)
return
copyToDir = 'crayon-' + VERSION + '-' + platform
if os.path.exists(copyToDir):
shutil.rmtree(copyToDir)
os.makedirs(copyToDir)
if platform == 'mono':
print runCommand('xbuild /p:Configuration=Release ../Compiler/CrayonOSX.sln')
else:
print runCommand(' '.join([
r'C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe',
'/p:Configuration=Release',
r'..\Compiler\CrayonWindows.sln'
]))
shutil.copyfile('../Compiler/bin/Release/Crayon.exe', copyToDir + '/crayon.exe')
shutil.copyfile('../Compiler/bin/Release/Interpreter.dll', copyToDir + '/Interpreter.dll')
shutil.copyfile('../Compiler/bin/Release/Resources.dll', copyToDir + '/Resources.dll')
shutil.copyfile('../Compiler/bin/Release/LICENSE.txt', copyToDir + '/LICENSE.txt')
shutil.copyfile('../README.md', copyToDir + '/README.md')
if platform == 'windows':
setupFile = readFile("setup-windows.txt")
writeFile(copyToDir + '/Setup Instructions.txt', setupFile, '\r\n')
if platform == 'mono':
setupFile = readFile("setup-mono.md")
writeFile(copyToDir + '/Setup Instructions.txt', setupFile, '\n')
for lib in librariesForRelease:
sourcePath = '../Libraries/' + lib
targetPath = copyToDir + '/libs/' + lib
copyDirectory(sourcePath, targetPath)
print("Release directory created: " + copyToDir)
main(sys.argv[1:])
| Python | 0 |
ba7fbebe4285de482028a5b88cc939b910bbcc6c | Remove some duplicated code | pombola/core/management/commands/core_find_stale_elasticsearch_documents.py | pombola/core/management/commands/core_find_stale_elasticsearch_documents.py | import sys
from django.core.management.base import BaseCommand
from haystack import connections as haystack_connections
from haystack.exceptions import NotHandled
from haystack.query import SearchQuerySet
from haystack.utils.app_loading import (
haystack_get_models, haystack_load_apps
)
def get_all_indexed_models():
backends = haystack_connections.connections_info.keys()
available_models = {}
for backend_key in backends:
connection = haystack_connections[backend_key]
backend = connection.get_backend()
unified_index = haystack_connections[backend_key].get_unified_index()
for app in haystack_load_apps():
for model in haystack_get_models(app):
try:
index = unified_index.get_index(model)
except NotHandled:
continue
model_name = model.__module__ + '.' + model.__name__
available_models[model_name] = {
'backend_key': backend_key,
'backend': backend,
'app': app,
'model': model,
'index': index,
}
return available_models
def get_models_to_check(model_names, available_models):
models_to_check = []
if model_names:
missing_models = False
for model_name in model_names:
if model_name in available_models:
models_to_check.append(model_name)
else:
missing_models = True
print "There was no model {0} with a search index".format(model_name)
if missing_models:
print "Some models were not found; they must be one of:"
for model in sorted(available_models.keys()):
print " ", model
sys.exit(1)
else:
models_to_check = sorted(available_models.keys())
return models_to_check
class Command(BaseCommand):
args = 'MODEL ...'
help = 'Get all search results for the given models'
def handle(self, *args, **options):
available_models = get_all_indexed_models()
models_to_check = get_models_to_check(args, available_models)
# Now we know which models to check, do that:
for model_name in models_to_check:
model_details = available_models[model_name]
qs = model_details['index'].build_queryset()
print "Checking {0} ({1} objects in the database)".format(
model_name, qs.count()
)
# Get all the primary keys from the database:
pks_in_database = set(
unicode(pk) for pk in qs.values_list('pk', flat=True)
)
# Then go through every search result for that
# model, and check that the primary key is one
# that's in the database:
for search_result in SearchQuerySet(
using=model_details['backend'].connection_alias
).models(model_details['model']):
if search_result.pk not in pks_in_database:
print " stale search entry for primary key", search_result.pk
| import sys
from django.core.management.base import BaseCommand
from haystack import connections as haystack_connections
from haystack.exceptions import NotHandled
from haystack.query import SearchQuerySet
from haystack.utils.app_loading import (
haystack_get_models, haystack_load_apps
)
def get_all_indexed_models():
backends = haystack_connections.connections_info.keys()
available_models = {}
for backend_key in backends:
unified_index = haystack_connections[backend_key].get_unified_index()
for app in haystack_load_apps():
for model in haystack_get_models(app):
try:
unified_index.get_index(model)
except NotHandled:
continue
model_name = model.__module__ + '.' + model.__name__
available_models[model_name] = {
'backend_key': backend_key,
'app': app,
'model': model,
}
return available_models
def get_models_to_check(model_names, available_models):
models_to_check = []
if model_names:
missing_models = False
for model_name in model_names:
if model_name in available_models:
models_to_check.append(model_name)
else:
missing_models = True
print "There was no model {0} with a search index".format(model_name)
if missing_models:
print "Some models were not found; they must be one of:"
for model in sorted(available_models.keys()):
print " ", model
sys.exit(1)
else:
models_to_check = sorted(available_models.keys())
return models_to_check
class Command(BaseCommand):
args = 'MODEL ...'
help = 'Get all search results for the given models'
def handle(self, *args, **options):
available_models = get_all_indexed_models()
models_to_check = get_models_to_check(args, available_models)
# Now we know which models to check, do that:
for model_name in models_to_check:
model_details = available_models[model_name]
backend_key = model_details['backend_key']
model = model_details['model']
backend = haystack_connections[backend_key].get_backend()
unified_index = haystack_connections[backend_key].get_unified_index()
index = unified_index.get_index(model)
qs = index.build_queryset()
print "Checking {0} ({1} objects in the database)".format(
model_name, qs.count()
)
# Get all the primary keys from the database:
pks_in_database = set(
unicode(pk) for pk in qs.values_list('pk', flat=True)
)
# Then go through every search result for that
# model, and check that the primary key is one
# that's in the database:
for search_result in SearchQuerySet(using=backend.connection_alias).models(model):
if search_result.pk not in pks_in_database:
print " stale search entry for primary key", search_result.pk
| Python | 0.003916 |
0bdc25cab0deeca81cedace37f135bef40f6eb09 | use shutdownMicroprocess() instead; fix hilighted by tests. | Sketches/PT/dns.py | Sketches/PT/dns.py | #!/usr/bin/env python
#
# (C) 2007 British Broadcasting Corporation and Kamaelia Contributors(1)
# All Rights Reserved.
#
# You may only modify and redistribute this under the terms of any of the
# following licenses(2): Mozilla Public License, V1.1, GNU General
# Public License, V2.0, GNU Lesser General Public License, V2.1
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://kamaelia.sourceforge.net/AUTHORS - please extend this file,
# not this notice.
# (2) Reproduced in the COPYING file, and at:
# http://kamaelia.sourceforge.net/COPYING
# Under section 3.5 of the MPL, we are using this text since we deem the MPL
# notice inappropriate for this file. As per MPL/GPL/LGPL removal of this
# notice is prohibited.
#
# Please contact us via: kamaelia-list-owner@lists.sourceforge.net
# to discuss alternative licensing.
# -------------------------------------------------------------------------
"""\
========================
Non-blocking DNS lookups
========================
This component will process DNS requests, using the blocking syscall
gethostbyname(). It will take hostnames recieved on "inbox" and puts a tuple of
(hostname, ip) in "outbox". In the event of a failure, the specific message will
be placed on "signal" in the form (hostname, error code).
Example Usage
-------------
Type hostnames, and they will be resolved and printed out::
Pipeline(
ConsoleReader(">>> ", ""),
GetHostByName(),
ConsoleEchoer(),
).run()
How does it work?
-----------------
The gethostbyname() syscall is a blocking one, and its use unmodified in a
kamaelia system can be a problem. This threadedcomponent processes requests and
can block without problems. Note that although all requests are processed
sequentially, this may not always be the case, and should not be relied on,
hence returning the hostname along with the IP address.
If this component recieves producerFinished or shutdown on the "signal" inbox,
it will emit a producerFinished on the "control" outbox, and shut down.
"""
from Axon.ThreadedComponent import threadedcomponent
from Axon.Ipc import producerFinished, shutdownMicroprocess
import socket
class GetHostByName(threadedcomponent):
def __init__(self, oneShot = False):
self.oneShot = oneShot
super(GetHostByName, self).__init__()
def doLookup(self, data):
try: hostname = socket.gethostbyname(data)
except socket.gaierror, e:
self.send((data, e[1]), "signal")
else: self.send((data, hostname), "outbox")
def main(self):
if self.oneShot:
self.doLookup(self.oneShot)
self.send(producerFinished(self), "signal")
return
while True:
while self.dataReady("inbox"):
returnval = self.doLookup(self.recv("inbox"))
if returnval != None:
self.send(returnval, "outbox")
while self.dataReady("control"):
msg = self.recv("control")
if isinstance(msg, producerFinished) or isinstance(msg, shutdownMicroprocess):
self.send(producerFinished(self), "signal")
return
self.pause()
__kamaelia_components__ = ( GetHostByName, )
if __name__ == "__main__":
from Kamaelia.Chassis.Pipeline import Pipeline
from Kamaelia.Util.Console import ConsoleReader, ConsoleEchoer
Pipeline(ConsoleReader(">>> ", ""),GetHostByName(),ConsoleEchoer()).run() | #!/usr/bin/env python
# (C) 2006 British Broadcasting Corporation and Kamaelia Contributors(1)
# All Rights Reserved.
#
# You may only modify and redistribute this under the terms of any of the
# following licenses(2): Mozilla Public License, V1.1, GNU General
# Public License, V2.0, GNU Lesser General Public License, V2.1
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://kamaelia.sourceforge.net/AUTHORS - please extend this file,
# not this notice.
# (2) Reproduced in the COPYING file, and at:
# http://kamaelia.sourceforge.net/COPYING
# Under section 3.5 of the MPL, we are using this text since we deem the MPL
# notice inappropriate for this file. As per MPL/GPL/LGPL removal of this
# notice is prohibited.
#
# Please contact us via: kamaelia-list-owner@lists.sourceforge.net
# to discuss alternative licensing.
# -------------------------------------------------------------------------
"""\
========================
Non-blocking DNS lookups
========================
This component will process DNS requests, using the blocking syscall
gethostbyname(). It will take hostnames recieved on "inbox" and puts a tuple of
(hostname, ip) in "outbox". In the event of a failure, the specific message will
be placed on "signal" in the form (hostname, error code).
Example Usage
-------------
Type hostnames, and they will be resolved and printed out.
pipeline(
ConsoleReader(">>> ", ""),
GetHostByName(),
ConsoleEchoer(),
).run()
How does it work?
-----------------
The gethostbyname() syscall is a blocking one, and its use unmodified in a
kamaelia system can be a problem. This threadedcomponent processes requests and
can block without problems. Note that although all requests are processed
sequentially, this may not always be the case, and should not be relied on,
hence returning the hostname along with the IP address.
"""
from Axon.ThreadedComponent import threadedcomponent
from Axon.Ipc import producerFinished, shutdown
import socket
class GetHostByName(threadedcomponent):
def __init__(self, oneShot = False):
self.oneShot = oneShot
super(GetHostByName, self).__init__()
def doLookup(self, data):
try: hostname = socket.gethostbyname(data)
except socket.gaierror, e:
self.send((data, e[1]), "signal")
else: self.send((data, hostname), "outbox")
def main(self):
if self.oneShot:
self.doLookup(self, oneShot)
self.send(producerFinished(self), "signal")
return
while True:
while self.dataReady("inbox"):
returnval = self.doLookup(self.recv("inbox"))
if returnval != None:
self.send(returnval, "outbox")
while self.dataReady("control"):
msg = self.recv("control")
if isinstance(msg, producerFinished) or isinstance(msg, shutdown):
self.send(producerFinished(self), "signal")
return
self.pause()
__kamaelia_components__ = ( GetHostByName, )
if __name__ == "__main__":
from Kamaelia.Chassis.Pipeline import Pipeline
from Kamaelia.Util.Console import ConsoleReader, ConsoleEchoer
Pipeline(ConsoleReader(">>> ", ""),GetHostByName(),ConsoleEchoer()).run() | Python | 0 |
5f1f1145d4f01f4b30e8782d284feb44781c21ad | Use sorted on the set to parametrize tests so that pytest-xdist works | tests/cupyx_tests/scipy_tests/special_tests/test_ufunc_dispatch.py | tests/cupyx_tests/scipy_tests/special_tests/test_ufunc_dispatch.py | import numpy
import cupy
import scipy.special
import cupyx.scipy.special
from cupy import testing
import pytest
scipy_ufuncs = {
f
for f in scipy.special.__all__
if isinstance(getattr(scipy.special, f), numpy.ufunc)
}
cupyx_scipy_ufuncs = {
f
for f in dir(cupyx.scipy.special)
if isinstance(getattr(cupyx.scipy.special, f), cupy.ufunc)
}
@testing.gpu
@testing.with_requires("scipy")
@pytest.mark.parametrize("ufunc", sorted(cupyx_scipy_ufuncs & scipy_ufuncs))
class TestUfunc:
@testing.numpy_cupy_allclose(atol=1e-5)
def test_dispatch(self, xp, ufunc):
ufunc = getattr(scipy.special, ufunc)
# some ufunc (like sph_harm) do not work with float inputs
# therefore we retrieve the types from the ufunc itself
types = ufunc.types[0]
args = [
cupy.testing.shaped_random((5,), xp, dtype=types[i])
for i in range(ufunc.nargs - 1)
]
res = ufunc(*args)
assert type(res) == xp.ndarray
return res
| import numpy
import cupy
import scipy.special
import cupyx.scipy.special
from cupy import testing
import pytest
scipy_ufuncs = {
f
for f in scipy.special.__all__
if isinstance(getattr(scipy.special, f), numpy.ufunc)
}
cupyx_scipy_ufuncs = {
f
for f in dir(cupyx.scipy.special)
if isinstance(getattr(cupyx.scipy.special, f), cupy.ufunc)
}
@testing.gpu
@testing.with_requires("scipy")
@pytest.mark.parametrize("ufunc", cupyx_scipy_ufuncs & scipy_ufuncs)
class TestUfunc:
@testing.numpy_cupy_allclose(atol=1e-5)
def test_dispatch(self, xp, ufunc):
ufunc = getattr(scipy.special, ufunc)
# some ufunc (like sph_harm) do not work with float inputs
# therefore we retrieve the types from the ufunc itself
types = ufunc.types[0]
args = [
cupy.testing.shaped_random((5,), xp, dtype=types[i])
for i in range(ufunc.nargs - 1)
]
res = ufunc(*args)
assert type(res) == xp.ndarray
return res
| Python | 0 |
72c0c74936b7a7c1c9df572adb41f33283c74d57 | don't need to autoescape the output of urlize | localtv/templatetags/filters.py | localtv/templatetags/filters.py | # Copyright 2009 - Participatory Culture Foundation
#
# This file is part of Miro Community.
#
# Miro Community 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.
#
# Miro Community is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Miro Community. If not, see <http://www.gnu.org/licenses/>.
import datetime
import re
from BeautifulSoup import BeautifulSoup, Comment, Tag
from django.template import Library
from django.utils.html import urlize
from django.utils.safestring import mark_safe
register = Library()
def simpletimesince(value, arg=None):
"""Formats a date as the time since that date (i.e. "4 days, 6 hours")."""
from django.utils.timesince import timesince
if not value:
return u''
try:
if arg:
return timesince(value, arg)
return timesince(value, datetime.datetime.utcnow()).split(', ')[0]
except (ValueError, TypeError):
return u''
def sanitize(value, extra_filters=None):
"""
Sanitize the given HTML.
Based on code from:
* http://www.djangosnippets.org/snippets/1655/
* http://www.djangosnippets.org/snippets/205/
"""
if value is None:
return u''
if '<' not in value: # no HTML
return urlize(mark_safe(value),
nofollow=True) # convert plain-text links into HTML
js_regex = re.compile(r'[\s]*(&#x.{1,7})?'.join(list('javascript')),
re.IGNORECASE)
allowed_tags = ('p i strong em b u a h1 h2 h3 h4 h5 h6 pre br img ul '
'ol li span').split()
allowed_attributes = 'href src style'.split()
whitelist = False
extra_tags = ()
extra_attributes = ()
if isinstance(extra_filters, basestring):
if '|' in extra_filters:
parts = extra_filters.split('|')
else:
parts = [extra_filters.split()]
if parts[0] == 'whitelist':
whitelist = True
parts = parts[1:]
extra_tags = parts[0].split()
if len(parts) > 1:
extra_attributes = parts[1].split()
elif extra_filters:
extra_tags = extra_filters
if whitelist:
allowed_tags, allowed_attributes = extra_tags, extra_attributes
else:
allowed_tags = set(allowed_tags) | set(extra_tags)
allowed_attributes = set(allowed_attributes) | set(extra_attributes)
soup = BeautifulSoup(value)
for comment in soup.findAll(text=lambda text: isinstance(text, Comment)):
# remove comments
comment.extract()
for tag in soup.findAll(True):
if tag.name not in allowed_tags:
tag.hidden = True
else:
tag.attrs = [(attr, js_regex.sub('', val))
for attr, val in tag.attrs
if attr in allowed_attributes]
return mark_safe(soup.renderContents().decode('utf8'))
def wmode_transparent(value):
soup = BeautifulSoup(value)
param_tag = Tag(soup, 'param', [
('name', 'wmode'),
('value', 'transparent')])
for html_object in soup.findAll('object'):
html_object.insert(0, param_tag)
for flash_embed in soup.findAll('embed',
type="application/x-shockwave-flash"):
flash_embed['wmode'] = 'transparent'
return mark_safe(soup.prettify())
register.filter(simpletimesince)
register.filter(sanitize)
register.filter(wmode_transparent)
| # Copyright 2009 - Participatory Culture Foundation
#
# This file is part of Miro Community.
#
# Miro Community 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.
#
# Miro Community is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Miro Community. If not, see <http://www.gnu.org/licenses/>.
import datetime
import re
from BeautifulSoup import BeautifulSoup, Comment, Tag
from django.template import Library
from django.utils.html import urlize
from django.utils.safestring import mark_safe
register = Library()
def simpletimesince(value, arg=None):
"""Formats a date as the time since that date (i.e. "4 days, 6 hours")."""
from django.utils.timesince import timesince
if not value:
return u''
try:
if arg:
return timesince(value, arg)
return timesince(value, datetime.datetime.utcnow()).split(', ')[0]
except (ValueError, TypeError):
return u''
def sanitize(value, extra_filters=None):
"""
Sanitize the given HTML.
Based on code from:
* http://www.djangosnippets.org/snippets/1655/
* http://www.djangosnippets.org/snippets/205/
"""
if value is None:
return u''
if '<' not in value: # no HTML
return urlize(mark_safe(value),
nofollow=True,
autoescape=True) # convert plain-text links into HTML
js_regex = re.compile(r'[\s]*(&#x.{1,7})?'.join(list('javascript')),
re.IGNORECASE)
allowed_tags = ('p i strong em b u a h1 h2 h3 h4 h5 h6 pre br img ul '
'ol li span').split()
allowed_attributes = 'href src style'.split()
whitelist = False
extra_tags = ()
extra_attributes = ()
if isinstance(extra_filters, basestring):
if '|' in extra_filters:
parts = extra_filters.split('|')
else:
parts = [extra_filters.split()]
if parts[0] == 'whitelist':
whitelist = True
parts = parts[1:]
extra_tags = parts[0].split()
if len(parts) > 1:
extra_attributes = parts[1].split()
elif extra_filters:
extra_tags = extra_filters
if whitelist:
allowed_tags, allowed_attributes = extra_tags, extra_attributes
else:
allowed_tags = set(allowed_tags) | set(extra_tags)
allowed_attributes = set(allowed_attributes) | set(extra_attributes)
soup = BeautifulSoup(value)
for comment in soup.findAll(text=lambda text: isinstance(text, Comment)):
# remove comments
comment.extract()
for tag in soup.findAll(True):
if tag.name not in allowed_tags:
tag.hidden = True
else:
tag.attrs = [(attr, js_regex.sub('', val))
for attr, val in tag.attrs
if attr in allowed_attributes]
return mark_safe(soup.renderContents().decode('utf8'))
def wmode_transparent(value):
soup = BeautifulSoup(value)
param_tag = Tag(soup, 'param', [
('name', 'wmode'),
('value', 'transparent')])
for html_object in soup.findAll('object'):
html_object.insert(0, param_tag)
for flash_embed in soup.findAll('embed',
type="application/x-shockwave-flash"):
flash_embed['wmode'] = 'transparent'
return mark_safe(soup.prettify())
register.filter(simpletimesince)
register.filter(sanitize)
register.filter(wmode_transparent)
| Python | 0.99954 |
fabd8e5a1fbb8dd083b05b053320b090fedad119 | Fix cryptostate to no longer assign multiple states at once (issue #620) | mailpile/plugins/cryptostate.py | mailpile/plugins/cryptostate.py | from gettext import gettext as _
from mailpile.plugins import PluginManager
from mailpile.crypto.state import EncryptionInfo, SignatureInfo
_plugins = PluginManager(builtin=__file__)
##[ Keywords ]################################################################
def text_kw_extractor(index, msg, ctype, text):
kw = set()
if ('-----BEGIN PGP' in text and '\n-----END PGP' in text):
kw.add('pgp:has')
kw.add('crypto:has')
return kw
def meta_kw_extractor(index, msg_mid, msg, msg_size, msg_ts):
kw, enc, sig = set(), set(), set()
def crypto_eval(part):
# This is generic
if part.encryption_info.get('status') != 'none':
enc.add('mp_%s-%s' % ('enc', part.encryption_info['status']))
kw.add('crypto:has')
if part.signature_info.get('status') != 'none':
sig.add('mp_%s-%s' % ('sig', part.signature_info['status']))
kw.add('crypto:has')
# This is OpenPGP-specific
if (part.encryption_info.get('protocol') == 'openpgp'
or part.signature_info.get('protocol') == 'openpgp'):
kw.add('pgp:has')
# FIXME: Other encryption protocols?
def choose_one(fmt, statuses, ordering):
for o in ordering:
status = (fmt % o)
if status in statuses:
return set([status])
return set(list(statuses)[:1])
# Evaluate all the message parts
crypto_eval(msg)
for part in msg.walk():
crypto_eval(part)
# OK, we should have exactly encryption state...
if len(enc) < 1:
enc.add('mp_enc-none')
elif len(enc) > 1:
enc = choose_one('mp_enc-%s', enc, EncryptionInfo.STATUSES)
# ... and exactly one signature state.
if len(sig) < 1:
sig.add('mp_sig-none')
elif len(sig) > 1:
sig = choose_one('mp_sig-%s', sig, SignatureInfo.STATUSES)
# Emit tags for our states
for tname in (enc | sig):
tag = index.config.get_tags(slug=tname)
if tag:
kw.add('%s:in' % tag[0]._key)
return list(kw)
_plugins.register_text_kw_extractor('crypto_tkwe', text_kw_extractor)
_plugins.register_meta_kw_extractor('crypto_mkwe', meta_kw_extractor)
##[ Search helpers ]##########################################################
def search(config, idx, term, hits):
#
# FIXME: Translate things like pgp:signed into a search for all the
# tags that have signatures (good or bad).
#
return []
_plugins.register_search_term('crypto', search)
_plugins.register_search_term('pgp', search)
| from gettext import gettext as _
from mailpile.plugins import PluginManager
_plugins = PluginManager(builtin=__file__)
##[ Keywords ]################################################################
def text_kw_extractor(index, msg, ctype, text):
kw = set()
if ('-----BEGIN PGP' in text and '\n-----END PGP' in text):
kw.add('pgp:has')
kw.add('crypto:has')
return kw
def meta_kw_extractor(index, msg_mid, msg, msg_size, msg_ts):
kw, enc, sig = set(), set(), set()
for part in msg.walk():
enc.add('mp_%s-%s' % ('enc', part.encryption_info['status']))
sig.add('mp_%s-%s' % ('sig', part.signature_info['status']))
# This is generic
if (part.encryption_info.get('status') != 'none'
or part.signature_info.get('status') != 'none'):
kw.add('crypto:has')
# This is OpenPGP-specific
if (part.encryption_info.get('protocol') == 'openpgp'
or part.signature_info.get('protocol') == 'openpgp'):
kw.add('pgp:has')
# FIXME: Other encryption protocols?
for tname in (enc | sig):
tag = index.config.get_tags(slug=tname)
if tag:
kw.add('%s:in' % tag[0]._key)
return list(kw)
_plugins.register_text_kw_extractor('crypto_tkwe', text_kw_extractor)
_plugins.register_meta_kw_extractor('crypto_mkwe', meta_kw_extractor)
##[ Search helpers ]##########################################################
def search(config, idx, term, hits):
#
# FIXME: Translate things like pgp:signed into a search for all the
# tags that have signatures (good or bad).
#
return []
_plugins.register_search_term('crypto', search)
_plugins.register_search_term('pgp', search)
| Python | 0 |
dfda6dad01050d1198779d1a33838f79adfc2198 | Fix KeyError for FilePath | bro-otx.py | bro-otx.py | #!/usr/bin/env python
import requests
import sys
from ConfigParser import ConfigParser
from datetime import datetime, timedelta
# The URL is hard coded. I'm comfortable doing this since it's unlikely that
# the URL will change without resulting in an API change that will require
# changes to this script.
_URL = 'http://otx.alienvault.com/api/v1/pulses/subscribed'
# Bro Intel file header format
_HEADER = "#fields\tindicator\tindicator_type\tmeta.source\tmeta.url\tmeta.do_notice\n"
# Mapping of OTXv2 Indicator types to Bro Intel types, additionally,
# identifies unsupported intel types to prevent errors in Bro.
_MAP = {
"IPv4": "Intel::ADDR",
"IPv6": "Intel::ADDR",
"domain": "Intel::DOMAIN",
"hostname": "Intel::DOMAIN",
"email": "Intel::EMAIL",
"URL": "Intel::URL",
"URI": "Intel::URL",
"FileHash-MD5": "Intel::FILE_HASH",
"FileHash-SHA1": "Intel::FILE_HASH",
"FileHash-SHA256": "Intel::FILE_HASH",
}
def _get(key, mtime, limit=20, next_request=''):
'''
Retrieves a result set from the OTXv2 API using the restrictions of
mtime as a date restriction.
'''
headers = {'X-OTX-API-KEY': key}
params = {'limit': limit, 'modified_since': mtime}
if next_request == '':
r = requests.get(_URL, headers=headers, params=params)
else:
r = requests.get(next_request, headers=headers)
# Depending on the response code, return the valid response.
if r.status_code == 200:
return r.json()
if r.status_code == 403:
print("An invalid API key was specified.")
sys.exit(1)
if r.status_code == 400:
print("An invalid request was made.")
sys.exit(1)
def iter_pulses(key, mtime, limit=20):
'''
Creates an iterator that steps through Pulses since mtime using key.
'''
# Populate an initial result set, after this the API will generate the next
# request in the loop for every iteration.
initial_results = _get(key, mtime, limit)
for result in initial_results['results']:
yield result
next_request = initial_results['next']
while next_request:
json_data = _get(key, mtime, next_request=next_request)
for result in json_data['results']:
yield result
next_request = json_data['next']
def map_indicator_type(indicator_type):
'''
Maps an OTXv2 indicator type to a Bro Intel Framework type.
'''
return _MAP.get(indicator_type)
def main():
'''Retrieve intel from OTXv2 API.'''
config = ConfigParser()
config.read('bro-otx.conf')
key = config.get('otx', 'api_key')
days = int(config.get('otx', 'days_of_history'))
outfile = config.get('otx', 'outfile')
do_notice = config.get('otx', 'do_notice')
mtime = (datetime.now() - timedelta(days=days)).isoformat()
with open(outfile, 'wb') as f:
f.write(_HEADER)
for pulse in iter_pulses(key, mtime):
for indicator in pulse[u'indicators']:
bro_type = map_indicator_type(indicator[u'type'])
if bro_type is None:
continue
try:
url = pulse[u'references'][0]
except IndexError:
url = 'https://otx.alienvault.com'
fields = [indicator[u'indicator'],
bro_type,
pulse[u'author_name'],
url,
do_notice + '\n']
f.write('\t'.join(fields))
if __name__ == '__main__':
main()
| #!/usr/bin/env python
import requests
import sys
from ConfigParser import ConfigParser
from datetime import datetime, timedelta
# The URL is hard coded. I'm comfortable doing this since it's unlikely that
# the URL will change without resulting in an API change that will require
# changes to this script.
_URL = 'http://otx.alienvault.com/api/v1/pulses/subscribed'
# Bro Intel file header format
_HEADER = "#fields\tindicator\tindicator_type\tmeta.source\tmeta.url\tmeta.do_notice\n"
# Mapping of OTXv2 Indicator types to Bro Intel types, additionally,
# identifies unsupported intel types to prevent errors in Bro.
_MAP = {"IPv4":"Intel::ADDR",
"IPv6":"Intel::ADDR",
"domain":"Intel::DOMAIN",
"hostname":"Intel::DOMAIN",
"email":"Intel::EMAIL",
"URL":"Intel::URL",
"URI":"Intel::URL",
"FileHash-MD5":"Intel::FILE_HASH",
"FileHash-SHA1":"Intel::FILE_HASH",
"FileHash-SHA256":"Intel::FILE_HASH",
"CVE":"Unsupported",
"Mutex":"Unsupported",
"CIDR":"Unsupported"}
def _get(key, mtime, limit=20, next_request=''):
'''
Retrieves a result set from the OTXv2 API using the restrictions of
mtime as a date restriction.
'''
headers = {'X-OTX-API-KEY': key}
params = {'limit': limit, 'modified_since': mtime}
if next_request == '':
r = requests.get(_URL, headers=headers, params=params)
else:
r = requests.get(next_request, headers=headers)
# Depending on the response code, return the valid response.
if r.status_code == 200:
return r.json()
if r.status_code == 403:
print("An invalid API key was specified.")
sys.exit(1)
if r.status_code == 400:
print("An invalid request was made.")
sys.exit(1)
def iter_pulses(key, mtime, limit=20):
'''
Creates an iterator that steps through Pulses since mtime using key.
'''
# Populate an initial result set, after this the API will generate the next
# request in the loop for every iteration.
initial_results = _get(key, mtime, limit)
for result in initial_results['results']:
yield result
next_request = initial_results['next']
while next_request:
json_data = _get(key, mtime, next_request=next_request)
for result in json_data['results']:
yield result
next_request = json_data['next']
def map_indicator_type(indicator_type):
'''
Maps an OTXv2 indicator type to a Bro Intel Framework type.
'''
return _MAP[indicator_type]
def main():
'''Retrieve intel from OTXv2 API.'''
config = ConfigParser()
config.read('bro-otx.conf')
key = config.get('otx', 'api_key')
days = int(config.get('otx', 'days_of_history'))
outfile = config.get('otx', 'outfile')
do_notice = config.get('otx', 'do_notice')
mtime = (datetime.now() - timedelta(days=days)).isoformat()
with open(outfile, 'wb') as f:
f.write(_HEADER)
for pulse in iter_pulses(key, mtime):
for indicator in pulse[u'indicators']:
bro_type = map_indicator_type(indicator[u'type'])
if bro_type == 'Unsupported':
continue
try:
url = pulse[u'references'][0]
except IndexError:
url = 'https://otx.alienvault.com'
fields = [indicator[u'indicator'],
bro_type,
pulse[u'author_name'],
url,
do_notice + '\n']
f.write('\t'.join(fields))
if __name__ == '__main__':
main()
| Python | 0.000001 |
d5c30bdae34450b4052f83f773ef993e89fc8bef | Prepare 1.1 release | c4ddev.pyp | c4ddev.pyp | # Copyright (C) 2014-2016 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
__author__ = 'Niklas Rosenstein <rosensteinniklas@gmail.com>'
__version__ = '1.1'
import os
import sys
import c4d
_added_paths = []
def add_path(path, module=sys):
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(__file__), path)
if path not in module.path:
module.path.append(path)
_added_paths.append((module, path))
# The third party modules in this plugin should be available globally.
add_path('lib/py-shroud')
add_path('lib/requests')
import shroud
add_path('lib', module=shroud)
add_path('lib/py-localimport', module=shroud)
def load_extensions():
extensions = []
ext_dir = os.path.join(os.path.dirname(__file__), 'ext')
for file in os.listdir(ext_dir):
if file.endswith('.py'):
extensions.append(shroud.require(os.path.join(ext_dir, file)))
return extensions
extensions = load_extensions()
def PluginMessage(msg_type, data):
if msg_type == c4d.C4DPL_RELOADPYTHONPLUGINS:
for mod, path in _added_paths:
try: mod.path.remove(path)
except ValueError: pass
for extension in extensions:
if hasattr(extension, 'PluginMessage'):
extension.PluginMessage(msg_type, data)
return True
| # Copyright (C) 2014-2016 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
__author__ = 'Niklas Rosenstein <rosensteinniklas@gmail.com>'
__version__ = '1.0'
import os
import sys
import c4d
_added_paths = []
def add_path(path, module=sys):
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(__file__), path)
if path not in module.path:
module.path.append(path)
_added_paths.append((module, path))
# The third party modules in this plugin should be available globally.
add_path('lib/py-shroud')
add_path('lib/requests')
import shroud
add_path('lib', module=shroud)
add_path('lib/py-localimport', module=shroud)
def load_extensions():
extensions = []
ext_dir = os.path.join(os.path.dirname(__file__), 'ext')
for file in os.listdir(ext_dir):
if file.endswith('.py'):
extensions.append(shroud.require(os.path.join(ext_dir, file)))
return extensions
extensions = load_extensions()
def PluginMessage(msg_type, data):
if msg_type == c4d.C4DPL_RELOADPYTHONPLUGINS:
for mod, path in _added_paths:
try: mod.path.remove(path)
except ValueError: pass
for extension in extensions:
if hasattr(extension, 'PluginMessage'):
extension.PluginMessage(msg_type, data)
return True
| Python | 0 |
8c0e1a976e6341d565140725d51562cc9021f90e | add hostname to all messages | cc/reqs.py | cc/reqs.py | import time
from cc.json import Struct, Field
from cc.message import CCMessage
from socket import gethostname
__all__ = ['LogMessage', 'InfofileMessage', 'JobRequestMessage', 'JobConfigReplyMessage', 'TaskRegisterMessage', 'TaskSendMessage']
class BaseMessage(Struct):
req = Field(str)
hostname = Field(str, default = gethostname())
def send_to(self, sock):
cmsg = CCMessage(jmsg = self)
sock.send_multipart(cmsg.zmsg)
class LogMessage(BaseMessage):
"log.*"
level = Field(str)
service_type = Field(str)
job_name = Field(str)
msg = Field(str)
time = Field(float)
pid = Field(int)
line = Field(int)
function = Field(str)
class InfofileMessage(BaseMessage):
"pub.infofile"
mtime = Field(float)
filename = Field(str)
body = Field(str)
class JobConfigRequestMessage(BaseMessage):
"job.config"
job_name = Field(str)
class JobConfigReplyMessage(BaseMessage):
"job.config"
job_name = Field(str)
config = Field(dict)
class TaskRegisterMessage(BaseMessage):
"req.task.register"
host = Field(str)
class TaskSendMessage(BaseMessage):
"req.task.send"
host = Field(str)
def parse_json(js):
return Struct.from_json(js)
| import time
from cc.json import Struct, Field
from cc.message import CCMessage
__all__ = ['LogMessage', 'InfofileMessage', 'JobRequestMessage', 'JobConfigReplyMessage', 'TaskRegisterMessage', 'TaskSendMessage']
class BaseMessage(Struct):
req = Field(str)
def send_to(self, sock):
cmsg = CCMessage(jmsg = self)
sock.send_multipart(cmsg.zmsg)
class LogMessage(BaseMessage):
"log.*"
level = Field(str)
service_type = Field(str)
job_name = Field(str)
msg = Field(str)
time = Field(float)
pid = Field(int)
line = Field(int)
function = Field(str)
class InfofileMessage(BaseMessage):
"pub.infofile"
mtime = Field(float)
filename = Field(str)
body = Field(str)
class JobConfigRequestMessage(BaseMessage):
"job.config"
job_name = Field(str)
class JobConfigReplyMessage(BaseMessage):
"job.config"
job_name = Field(str)
config = Field(dict)
class TaskRegisterMessage(BaseMessage):
"req.task.register"
host = Field(str)
class TaskSendMessage(BaseMessage):
"req.task.send"
host = Field(str)
def parse_json(js):
return Struct.from_json(js)
| Python | 0.000001 |
89d9328696a01e70428fccfa890d847e91f5f5c4 | Fix copy-paste bug | certifi.py | certifi.py | import platform
if platform.system() == "Windows":
import wincertstore
import atexit
import ssl
certfile = wincertstore.CertFile()
certfile.addstore("CA")
certfile.addstore("ROOT")
atexit.register(certfile.close) # cleanup and remove files on shutdown
def where():
return certfile
else:
import ssl
def where():
return ssl.get_default_verify_paths().openssl_cafile
| import platform
if platform.system() == "Windows":
import wincertstore
import atexit
import ssl
certfile = wincertstore.CertFile()
certfile.addstore("CA")
certfile.addstore("ROOT")
atexit.register(certfile.close) # cleanup and remove files on shutdown
def where():
return certfile
else:
import ssl
def where():
return ssl.ssl.get_default_verify_paths().openssl_cafile | Python | 0.000002 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.