commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
|---|---|---|---|---|---|---|---|
1ebfda57b49dd62f2ca931d615cd52d987d74890
|
allow to procure from planned orders
|
mrp_multi_level/wizards/mrp_inventory_procure.py
|
mrp_multi_level/wizards/mrp_inventory_procure.py
|
# Copyright 2018-19 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import _, api, fields, models
from odoo.exceptions import UserError, ValidationError
class MrpInventoryProcure(models.TransientModel):
_name = "mrp.inventory.procure"
_description = "Make Procurements from MRP inventory projections"
item_ids = fields.One2many(
comodel_name="mrp.inventory.procure.item", inverse_name="wiz_id", string="Items"
)
@api.model
def _prepare_item(self, planned_order):
return {
"planned_order_id": planned_order.id,
"qty": planned_order.mrp_qty - planned_order.qty_released,
"uom_id": planned_order.mrp_inventory_id.uom_id.id,
"date_planned": planned_order.due_date,
"mrp_inventory_id": planned_order.mrp_inventory_id.id,
"product_id": planned_order.product_id.id,
"warehouse_id": planned_order.mrp_area_id.warehouse_id.id,
"location_id": planned_order.product_mrp_area_id.location_proc_id.id
or planned_order.mrp_area_id.location_id.id,
"supply_method": planned_order.product_mrp_area_id.supply_method,
}
@api.model
def fields_view_get(
self, view_id=None, view_type="form", toolbar=False, submenu=False
):
if self.user_has_groups("mrp_multi_level.group_change_mrp_procure_qty"):
view_id = self.env.ref(
"mrp_multi_level." "view_mrp_inventory_procure_wizard"
).id
else:
view_id = self.env.ref(
"mrp_multi_level." "view_mrp_inventory_procure_without_security"
).id
return super(MrpInventoryProcure, self).fields_view_get(
view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu
)
@api.model
def default_get(self, fields):
res = super(MrpInventoryProcure, self).default_get(fields)
active_ids = self.env.context["active_ids"] or []
active_model = self.env.context["active_model"]
if not active_ids or "item_ids" not in fields:
return res
if active_model == "mrp.inventory":
items = item_obj = self.env["mrp.inventory.procure.item"]
mrp_inventory_obj = self.env["mrp.inventory"]
for line in mrp_inventory_obj.browse(active_ids).mapped(
"planned_order_ids"
):
if line.qty_released < line.mrp_qty:
items += item_obj.create(self._prepare_item(line))
res["item_ids"] = [(6, 0, items.ids)]
return res
def make_procurement(self):
self.ensure_one()
errors = []
pg = self.env["procurement.group"]
procurements = []
for item in self.item_ids:
if not item.qty:
raise ValidationError(_("Quantity must be positive."))
values = item._prepare_procurement_values()
procurements.append(
pg.Procurement(
item.product_id,
item.qty,
item.uom_id,
item.location_id,
"MRP: " + str(self.env.user.login), # name?
"MRP: " + str(self.env.user.login), # origin?
item.mrp_inventory_id.company_id,
values,
)
)
# Run procurements
try:
pg.run(procurements)
for item in self.item_ids:
item.planned_order_id.qty_released += item.qty
except UserError as error:
errors.append(error.name)
if errors:
raise UserError("\n".join(errors))
return {"type": "ir.actions.act_window_close"}
class MrpInventoryProcureItem(models.TransientModel):
_name = "mrp.inventory.procure.item"
_description = "MRP Inventory procure item"
wiz_id = fields.Many2one(
comodel_name="mrp.inventory.procure",
string="Wizard",
ondelete="cascade",
readonly=True,
)
qty = fields.Float(string="Quantity")
uom_id = fields.Many2one(string="Unit of Measure", comodel_name="uom.uom")
date_planned = fields.Date(string="Planned Date", required=True)
mrp_inventory_id = fields.Many2one(
string="Mrp Inventory", comodel_name="mrp.inventory"
)
planned_order_id = fields.Many2one(comodel_name="mrp.planned.order")
product_id = fields.Many2one(string="Product", comodel_name="product.product")
warehouse_id = fields.Many2one(string="Warehouse", comodel_name="stock.warehouse")
location_id = fields.Many2one(string="Location", comodel_name="stock.location")
supply_method = fields.Selection(
string="Supply Method",
selection=[
("buy", "Buy"),
("none", "Undefined"),
("manufacture", "Produce"),
("pull", "Pull From"),
("push", "Push To"),
("pull_push", "Pull & Push"),
],
readonly=True,
)
def _prepare_procurement_values(self, group=False):
return {
"date_planned": fields.Datetime.to_string(
fields.Date.from_string(self.date_planned)
),
"warehouse_id": self.warehouse_id,
"group_id": group,
"planned_order_id": self.planned_order_id.id,
}
@api.onchange("uom_id")
def onchange_uom_id(self):
for rec in self:
rec.qty = rec.mrp_inventory_id.uom_id._compute_quantity(
rec.mrp_inventory_id.to_procure, rec.uom_id
)
|
Python
| 0
|
@@ -2198,56 +2198,8 @@
i
-f active_model == %22mrp.inventory%22:%0A i
tems
@@ -2250,16 +2250,60 @@
e.item%22%5D
+%0A if active_model == %22mrp.inventory%22:
%0A
@@ -2336,31 +2336,28 @@
elf.env%5B
-%22mrp.inventory%22
+active_model
%5D%0A
@@ -2519,24 +2519,24 @@
ne.mrp_qty:%0A
-
@@ -2594,16 +2594,333 @@
(line))%0A
+ elif active_model == %22mrp.planned.order%22:%0A mrp_planned_order_obj = self.env%5Bactive_model%5D%0A for line in mrp_planned_order_obj.browse(active_ids):%0A if line.qty_released %3C line.mrp_qty:%0A items += item_obj.create(self._prepare_item(line))%0A if items:%0A
|
c4fde7ec13bd86718b7db55fa004a8c24aa0fa63
|
Fix books recommendations view
|
apps/books/views.py
|
apps/books/views.py
|
from django.core.urlresolvers import reverse, reverse_lazy
from django.views.generic import ListView, DetailView, TemplateView, FormView, CreateView, UpdateView, View
from django.db.models import Q
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from django.views.generic.detail import SingleObjectMixin
from apps.books.forms import *
from apps.core.views import BaseView
from apps.books.models import Book, UserProfileBook
from apps.reviews.views import CreateReviewView
from apps.reviews.models import Review
from apps.users.models import FollowShip, UserProfile
class HomePageView(BaseView, ListView):
"""docstring for HomePageView"""
template_name = 'books/index.html'
model = Book
context_object_name = 'list_book'
def get_queryset(self):
return Book.objects.order_by('-id')
def get_context_data(self, **kwargs):
context = super(HomePageView, self).get_context_data(**kwargs)
info = {
'info': {
'title': 'Book Review System'
}
}
context.update(info)
return context
class DetaiBookView(BaseView, DetailView):
"""docstring for DetaiView"""
model = Book
template_name = 'books/detail.html'
def get_context_data(self, **kwargs):
context = super(DetaiBookView, self).get_context_data(**kwargs)
info = {
'info': {
'title': self.object.title
},
'favourite': self.object.favourites.filter(user=self.request.user).exists(),
}
context.update(info)
context['reviews'] = Review.objects.filter(
book=self.object
).order_by('-updated_time')
if self.request.user.is_authenticated():
context['status_review'] = Review.objects.filter(
book=self.object,
user_profile=self.request.user.profile).exists()
try:
context['status_read'] = UserProfileBook.objects.get(
book=self.object,
user_profile=self.request.user.profile)
except UserProfileBook.DoesNotExist:
context['status_read'] = None
return context
def get(self, request, *args, **kwargs):
return super().get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
view = CreateReviewView.as_view()
return view(request, *args, **kwargs)
class RecommendationsBookView(BaseView, ListView):
"""docstring for RecommendationsBookView"""
model = Book
context_object_name = 'list_book'
template_name = 'books/index.html'
def get_queryset(self):
return Book.objects.order_by('-favourites', '-id')
def get_context_data(self, **kwargs):
context = super(RecommendationsBookView, self).get_context_data(**kwargs)
info = {
'info': {
'title': "Recommendations - Book Review"
}
}
context.update(info)
return context
class SearchBookView(BaseView, ListView):
"""docstring for SearchBookView"""
model = Book
template_name = 'books/index.html'
context_object_name = 'list_book'
def get_queryset(self):
string_search = self.request.GET.get('s', None)
return Book.objects.filter(
Q(title__icontains=string_search) |
Q(categories__name__icontains=string_search)).distinct().order_by('-id')
def get_context_data(self, **kwargs):
context = super(SearchBookView, self).get_context_data(**kwargs)
info = {
'info': {
'title': 'Search Books - Book Review'
}
}
context.update(info)
return context
class ListHistoryBookView(BaseView, ListView):
"""docstring for ListHistoryBookView"""
model = User
template_name = 'books/history.html'
context_object_name = 'list_user_profile_book'
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(ListHistoryBookView, self).dispatch(request, *args, **kwargs)
def get_queryset(self):
return UserProfileBook.objects.filter(
user_profile__user__username=self.kwargs['username']).order_by('-id')
def get_context_data(self, **kwargs):
context = super(ListHistoryBookView, self).get_context_data(**kwargs)
info = {
'history_user': User.objects.get(username=self.kwargs['username']),
'is_followed': FollowShip.objects.filter(
follower=self.request.user.profile,
followee__user__username=self.kwargs['username']).exists(),
'info': {
'title': 'History Book Review'
}
}
context.update(info)
return context
class FavoriteBookView(View, SingleObjectMixin):
model = Book
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(FavoriteBookView, self).dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.object = self.get_object()
self.object.favourites.add(request.user.profile)
self.object.save()
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
return reverse_lazy('books:detail', kwargs={'pk': self.object.id, 'slug': self.object.slug})
class RemoveFavoriteBookView(View, SingleObjectMixin):
model = Book
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(RemoveFavoriteBookView, self).dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.object = self.get_object()
self.object.favourites.remove(request.user.profile)
self.object.save()
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
return reverse_lazy('books:detail', kwargs={'pk': self.object.id, 'slug': self.object.slug})
class ReadBookView(CreateView):
"""docstring for ReadBookView"""
model = UserProfileBook
form_class = UserProfileBookForm
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(ReadBookView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
return reverse_lazy('books:detail', kwargs={'pk': self.object.book.id, 'slug': self.object.book.slug})
class UpdateReadBookView(UpdateView):
"""docstring for UpdateReadBookView"""
model = UserProfileBook
form_class = UserProfileBookForm
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(UpdateReadBookView, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
return reverse_lazy('books:detail', kwargs={'pk': self.object.book.id, 'slug': self.object.book.slug})
|
Python
| 0
|
@@ -456,16 +456,51 @@
ectMixin
+%0Afrom django.db.models import Count
%0A%0Afrom a
@@ -2954,38 +2954,42 @@
(self):%0A
-return
+queryset =
Book.objects.or
@@ -2990,38 +2990,126 @@
cts.
-order_by('-favourites', '-id')
+annotate(Count('favourites')%0A ).order_by('-favourites__count')%5B0:5%5D%0A return queryset
%0A%0A
|
6f69a770ef3b55a7d846abfc306e41025131d8a6
|
Fix FeedEntry custom model admin
|
apps/feeds/admin.py
|
apps/feeds/admin.py
|
from django.contrib import admin
from .models import Feed, FeedEntry
class FeedEntryAdmin(admin.ModelAdmin):
list_display = ('title', 'link', 'feed',
'feed__created_by', 'added_to_kippt')
admin.site.register(Feed)
admin.site.register(FeedEntry, FeedEntryAdmin)
|
Python
| 0
|
@@ -65,16 +65,99 @@
Entry%0A%0A%0A
+class FeedAdmin(admin.ModelAdmin):%0A list_display = ('feed_url', 'created_by')%0A%0A%0A
class Fe
@@ -259,17 +259,16 @@
'feed_
-_
created_
@@ -291,16 +291,141 @@
ippt')%0A%0A
+ def feed_created_by(self, obj):%0A return obj.feed.created_by%0A feed_created_by.short_description = 'Created by'%0A%0A
%0Aadmin.s
@@ -441,16 +441,27 @@
ter(Feed
+, FeedAdmin
)%0Aadmin.
|
034070458b18805d7282f2bb7f0880f688bf3e6e
|
Remove all subdir functionality
|
stuff/urls.py
|
stuff/urls.py
|
import settings
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
subdir = ''
urlpatterns = patterns('',
(r'^%sadmin/(.*)' % subdir, admin.site.root),
(r'^%spublication/' % subdir, include('stuff.publications.urls')),
(r'^%sfile/' % subdir, include('stuff.files.urls')),
(r'^%sphoto/' % subdir, include('stuff.picasaweb.urls')),
(r'^%sbookmark/' % subdir, include('stuff.delicious.urls')),
(r'^%sproject/' % subdir, include('stuff.projects.urls')),
(r'^%smultimedia/' % subdir, include('stuff.multimedia.urls')),
# (r'^%sdb/(.*)' % subdir, databrowse.site.root),
(r'^%s$' % subdir, 'stuff.views.index'),
# Media serving
(r'^%smedia/(?P<path>.*)$' % subdir,
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT,
'show_indexes': True}
),
)
|
Python
| 0.000004
|
@@ -109,20 +109,8 @@
()%0A%0A
-subdir = ''%0A
urlp
@@ -140,18 +140,16 @@
(r'%5E
-%25s
admin/(.
@@ -151,25 +151,16 @@
in/(.*)'
- %25 subdir
, admin.
@@ -179,18 +179,16 @@
(r'%5E
-%25s
publicat
@@ -192,25 +192,16 @@
cation/'
- %25 subdir
, includ
@@ -243,25 +243,14 @@
(r'%5E
-%25s
file/'
- %25 subdir
, in
@@ -289,26 +289,15 @@
(r'%5E
-%25s
photo/'
- %25 subdir
, in
@@ -336,18 +336,16 @@
(r'%5E
-%25s
bookmark
@@ -346,25 +346,16 @@
okmark/'
- %25 subdir
, includ
@@ -390,18 +390,16 @@
(r'%5E
-%25s
project/
@@ -399,25 +399,16 @@
roject/'
- %25 subdir
, includ
@@ -442,18 +442,16 @@
(r'%5E
-%25s
multimed
@@ -454,25 +454,16 @@
imedia/'
- %25 subdir
, includ
@@ -487,24 +487,67 @@
ia.urls')),%0A
+ (r'%5Egit/', include('stuff.dit.urls')),%0A
# (r'%5E%25s
@@ -548,18 +548,16 @@
(r'%5E
-%25s
db/(.*)'
%25 s
@@ -552,25 +552,16 @@
db/(.*)'
- %25 subdir
, databr
@@ -589,21 +589,10 @@
(r'%5E
-%25s$' %25 subdir
+$'
, 's
@@ -666,17 +666,8 @@
*)$'
- %25 subdir
,%0A
|
0fdacebfdcde53d92f9b17ccccf8fe815bd438c4
|
Fix bug number.
|
assess_add_cloud.py
|
assess_add_cloud.py
|
#!/usr/bin/env python
from argparse import ArgumentParser
from collections import namedtuple
from copy import deepcopy
import logging
import sys
import yaml
from jujupy import (
AuthNotAccepted,
EnvJujuClient,
get_client_class,
JujuData,
NameNotAccepted,
TypeNotAccepted,
)
from utility import (
add_arg_juju_bin,
JujuAssertionError,
temp_dir,
)
class CloudMismatch(JujuAssertionError):
"""The clouds did not match in some way."""
def __init__(self):
super(CloudMismatch, self).__init__('Cloud mismatch')
class NameMismatch(JujuAssertionError):
"""The cloud names did not match."""
def __init__(self):
super(NameMismatch, self).__init__('Name mismatch')
class NotRaised(Exception):
"""An expected exception was not raised."""
def __init__(self):
msg = 'Expected exception not raised: {}'.format(
cloud_spec.exception)
super(NotRaised, self).__init__(msg)
CloudSpec = namedtuple('CloudSpec', [
'label', 'name', 'config', 'exception', 'xfail_bug'])
def cloud_spec(label, name, config, exception=None, xfail_bug=None):
"""Generate a CloudSpec, with defaults.
:param label: The label to display in test results.
:param name: The name to use for the cloud.
:param config: The cloud-config.
:param exception: The exception that is expected to be raised (if any).
:param xfail_bug: If this CloudSpec represents an expected failure, the
bug number.
"""
return CloudSpec(label, name, config, exception, xfail_bug)
def xfail(spec, bug, xfail_exception):
"""Return a variant of a CloudSpec that is expected to fail.
Wrapping the original spec improves maintainability, because the xfail can
be removed to restore the original value.
"""
return CloudSpec(spec.label, spec.name, spec.config, xfail_exception, bug)
def assess_cloud(client, cloud_name, example_cloud):
"""Assess interactively adding a cloud.
Will raise an exception
- If no clouds are present after interactive add-cloud.
- If the resulting cloud name doesn't match the supplied cloud-name.
- If the cloud data doesn't match the supplied cloud data.
"""
clouds = client.env.read_clouds()
if len(clouds['clouds']) > 0:
raise AssertionError('Clouds already present!')
client.add_cloud_interactive(cloud_name, example_cloud)
clouds = client.env.read_clouds()
if len(clouds['clouds']) == 0:
raise JujuAssertionError('Clouds missing!')
if clouds['clouds'].keys() != [cloud_name]:
raise NameMismatch()
if clouds['clouds'][cloud_name] != example_cloud:
sys.stderr.write('\nExpected:\n')
yaml.dump(example_cloud, sys.stderr)
sys.stderr.write('\nActual:\n')
yaml.dump(clouds['clouds'][cloud_name], sys.stderr)
raise CloudMismatch()
def iter_clouds(clouds):
"""Iterate through CloudSpecs."""
yield cloud_spec('bogus-type', 'bogus-type', {'type': 'bogus'},
exception=TypeNotAccepted)
for cloud_name, cloud in clouds.items():
yield cloud_spec(cloud_name, cloud_name, cloud)
for cloud_name, cloud in clouds.items():
yield xfail(cloud_spec('long-name-{}'.format(cloud_name), 'A' * 4096,
cloud, NameNotAccepted), 1641970, NameMismatch)
yield xfail(
cloud_spec('invalid-name-{}'.format(cloud_name), 'invalid/name',
cloud, NameNotAccepted), 1649181, None)
if cloud['type'] not in ('maas', 'manual', 'vsphere'):
variant = deepcopy(cloud)
variant_name = 'bogus-auth-{}'.format(cloud_name)
variant['auth-types'] = ['asdf']
yield cloud_spec(variant_name, cloud_name, variant,
AuthNotAccepted)
if 'endpoint' in cloud:
variant = deepcopy(cloud)
variant['endpoint'] = 'A' * 4096
if variant['type'] == 'vsphere':
for region in variant['regions'].values():
region['endpoint'] = variant['endpoint']
variant_name = 'long-endpoint-{}'.format(cloud_name)
yield xfail(cloud_spec(variant_name, cloud_name, variant),
1641970, CloudMismatch)
for region_name in cloud.get('regions', {}).keys():
if cloud['type'] == 'vsphere':
continue
variant = deepcopy(cloud)
region = variant['regions'][region_name]
region['endpoint'] = 'A' * 4096
variant_name = 'long-endpoint-{}-{}'.format(cloud_name,
region_name)
yield xfail(cloud_spec(variant_name, cloud_name, variant,
exception=None), 1641970, CloudMismatch)
def assess_all_clouds(client, cloud_specs):
"""Test all the supplied cloud_specs and return the results.
Returns a tuple of succeeded, expected_failed, and failed.
succeeded and failed are sets of cloud labels. expected_failed is a dict
linking a given bug to its associated failures.
"""
succeeded = set()
xfailed = {}
failed = set()
client.env.load_yaml()
for cloud_spec in cloud_specs:
sys.stdout.write('Testing {}.\n'.format(cloud_spec.label))
try:
if cloud_spec.exception is None:
assess_cloud(client, cloud_spec.name, cloud_spec.config)
else:
try:
assess_cloud(client, cloud_spec.name, cloud_spec.config)
except cloud_spec.exception:
pass
else:
raise NotRaised(cloud_spec.exception)
except Exception as e:
logging.exception(e)
failed.add(cloud_spec.label)
else:
if cloud_spec.xfail_bug is not None:
xfailed.setdefault(
cloud_spec.xfail_bug, set()).add(cloud_spec.label)
else:
succeeded.add(cloud_spec.label)
finally:
client.env.clouds = {'clouds': {}}
client.env.dump_yaml(client.env.juju_home, {})
return succeeded, xfailed, failed
def write_status(status, tests):
if len(tests) == 0:
test_str = 'none'
else:
test_str = ', '.join(sorted(tests))
sys.stdout.write('{}: {}\n'.format(status, test_str))
def parse_args():
parser = ArgumentParser()
parser.add_argument('example_clouds',
help='A clouds.yaml file to use for testing.')
add_arg_juju_bin(parser)
return parser.parse_args()
def main():
args = parse_args()
juju_bin = args.juju_bin
version = EnvJujuClient.get_version(juju_bin)
client_class = get_client_class(version)
if client_class.config_class is not JujuData:
logging.warn('This test does not support old jujus.')
with open(args.example_clouds) as f:
clouds = yaml.safe_load(f)['clouds']
cloud_specs = iter_clouds(clouds)
with temp_dir() as juju_home:
env = JujuData('foo', config=None, juju_home=juju_home)
client = client_class(env, version, juju_bin)
succeeded, xfailed, failed = assess_all_clouds(client, cloud_specs)
write_status('Succeeded', succeeded)
for bug, failures in sorted(xfailed.items()):
write_status('Expected fail (bug #{})'.format(bug), failures)
write_status('Failed', failed)
if len(failed) > 0:
return 1
return 0
if __name__ == '__main__':
sys.exit(main())
|
Python
| 0
|
@@ -3521,10 +3521,10 @@
164
-9
1
+9
81,
|
ea94909e180c23d6e4873b2b0cc3d3f3c8fa7fd9
|
Move Student's class variable declarations outside of __init__
|
student.py
|
student.py
|
from major import Major
from concentration import Concentration
from course import Course, getCourse
from standing import Standing
def print_entire_list_as_english(passed_list):
for i, item in enumerate(passed_list):
if len(self.passed_list) is 1:
output += item + " "
elif len(self.passed_list) is 2:
output += item
if i is not (len(self.passed_list) - 1):
output += " and "
else:
output += " "
else:
if i is not (len(self.passed_list) - 1):
output += item + ", "
else:
output += "and " + item + ", "
class Student:
def __init__(self, name="", start_year=0, end_year=0, majors=[], concentrations=[], filename=""):
if not filename:
self.name = name
self.start_year = int(start_year)
self.end_year = int(end_year)
self.majors = []
self.concentrations = []
self.courses = {}
self.addMajors(majors)
self.addConcentrations(concentrations)
# self.standing = GraduationRequirement()
else:
previousHeading = ""
with open(filename) as infile:
for line in infile:
if not previousHeading:
previousHeading = "# NAME"
if line[0] == '#':
line = line.upper()
previousHeading = line
continue
elif line:
if line[0:2] == "//":
# it's a comment
pass
elif previousHeading == "# NAME":
self.name = line
elif previousHeading == "# MAJORS":
self.addMajor(line)
elif previousHeading == "# CONCENTRATIONS":
self.addConcentration(line)
elif previousHeading == "# COURSES":
self.addCourse(line)
elif previousHeading == "# LABS":
self.addCourse(line)
def __eq__(self, other):
return (
self.name == other.name and
self.start_year == other.start_year and
self.end_year == other.end_year and
self.majors == other.majors and
self.concentrations == other.concentrations and
self.courses == other.courses
# and
# self.standing == other.standing
)
def __str__(self):
self.updateStanding()
output = ""
output += self.name + ", "
if self.majors:
output += "you are majoring in "
print_entire_list_as_english(self.majors)
if self.concentrations:
output += "with concentrations in "
print_entire_list_as_english(self.concentrations)
if self.majors:
output += "while taking:" + '\n'
else:
output += "you are taking: " + '\n'
for course in self.courses:
output += c + '\n'
output += '\n'
# TODO: don't cout an extra line at the end of the output.
output += "As such, you must fulfill these requirements to graduate: " + '\n'
for major in self.majors:
for requirement in major.requirements:
output += requirement + '\n'
for requirement_set in major.specialRequirements:
for requirement in requirement_set.valid:
output += req + '\n'
for concentration in self.concentrations:
for requirement in concentration.requirements:
output += requirement + '\n'
for requirement_set in concentration.specialRequirements:
for requirement in requirement_set.valid:
output += req + '\n'
return output
def updateStanding(self):
for major in self.majors:
for course in self.courses:
for requirement in major.requirements:
if requirement.fulfillsRequirement(course.id):
requirement.increment()
for requirement_set in major.specialRequirements:
for requirement in requirement_set.valid:
if requirement.fulfillsRequirement(course.id):
requirement.increment()
for concentration in self.concentrations:
for course in self.courses:
for requirement in major.requirements:
if requirement.fulfillsRequirement(course.id):
requirement.increment()
for requirement_set in major.specialRequirements:
for requirement in requirement_set.valid:
if requirement.fulfillsRequirement(course.id):
requirement.increment()
def hasTakenCourse(self, identifier):
courseID = ID(combined=identifier)
if courseID in self.courses:
return self.courses[courseID]
else:
return None
def addCourse(self, course):
if not isinstance(course, Course):
course = Course(course)
self.courses.append(course)
def addMajor(self, major):
if not isinstance(major, Major):
major = Major(major)
self.majors.append(major)
def addConcentration(self, concentration):
if not isinstance(concentration, Concentration):
concentration = Concentration(concentration)
self.concentrations.append(concentration)
if __name__ == '__main__':
tmp = Student(name="Hawken", data="")
other = tmp = Student(name="Hawken", data="")
print(tmp)
if tmp == other:
print("equality success")
|
Python
| 0
|
@@ -556,16 +556,130 @@
tudent:%0A
+%09name = %22%22%0A%09start_year = 0%0A%09end_year = 0%0A%0A%09majors = %5B%5D%0A%09concentrations = %5B%5D%0A%09courses = %5B%5D%0A%09standing = Standing()%0A%0A
%09def __i
@@ -883,77 +883,8 @@
r)%0A%0A
-%09%09%09self.majors = %5B%5D%0A%09%09%09self.concentrations = %5B%5D%0A%09%09%09self.courses = %7B%7D%0A
%0A%09%09%09
@@ -951,54 +951,8 @@
ons)
-%0A%0A%09%09%09# self.standing = GraduationRequirement()
%0A%09%09e
|
75f3ab5331b9c5937e61af1bc279097cd9865e53
|
Add role project resource
|
mint/django_rest/rbuilder/projects/models.py
|
mint/django_rest/rbuilder/projects/models.py
|
#
# Copyright (c) 2011 rPath, Inc.
#
# All Rights Reserved
#
from django.db import models
from mint.django_rest.rbuilder import modellib
from mint.django_rest.rbuilder import models as rbuildermodels
from xobj import xobj
class Projects(modellib.Collection):
class Meta:
abstract = True
_xobj = xobj.XObjMetadata(
tag = "projects")
view_name = "Projects"
list_fields = ["project"]
project = []
class Project(modellib.XObjIdModel):
view_name = "Project"
url_key = "short_name"
project_id = models.AutoField(primary_key=True, db_column="projectid",
blank=True)
hostname = models.CharField(unique=True, max_length=63)
name = models.CharField(unique=True, max_length=128)
namespace = models.CharField(max_length=16, null=True)
domain_name = models.CharField(max_length=128, db_column="domainname")
short_name = models.CharField(unique=True, max_length=63,
db_column="short_name")
project_url = models.CharField(max_length=128, null=True, blank=True,
db_column= "projecturl")
repository_hostname = models.CharField(max_length=255, db_column="fqdn")
description = models.TextField(null=True, blank=True)
project_type = models.CharField(max_length=128, db_column="prodtype")
commit_email = models.CharField(max_length=128, null=True, blank=True,
db_column="commitemail")
backup_external = models.SmallIntegerField(null=True, blank=True,
db_column="backup_external")
time_created = models.DecimalField(max_digits=14, decimal_places=3,
blank=True, db_column="timecreated")
time_modified = models.DecimalField(max_digits=14, decimal_places=3,
blank=True, db_column="timemodified")
hidden = models.SmallIntegerField()
creator_id = models.ForeignKey(rbuildermodels.Users,
related_name="creator", null=True, db_column="creatorid")
members = models.ManyToManyField(rbuildermodels.Users, through="Members",
related_name="members")
class Meta:
db_table = u"projects"
def __unicode__(self):
return self.hostname
def _attributes(self):
return ({"id": self.hostname})
class Members(modellib.XObjModel):
productId = models.ForeignKey(Project, db_column='projectid',
related_name='product')
userid = models.ForeignKey(rbuildermodels.Users, db_column='userid',
related_name='user')
level = models.SmallIntegerField()
class Meta:
db_table = u'projectusers'
class Version(modellib.XObjIdModel):
class Meta:
db_table = u'productversions'
_xobj = xobj.XObjMetadata(
tag="version")
view_name = 'ProjectVersions'
def __unicode__(self):
return self.name
productVersionId = models.AutoField(primary_key=True,
db_column='productversionid')
productId = modellib.DeferredForeignKey(Project, db_column='projectid',
related_name="versions")
namespace = models.CharField(max_length=16)
name = models.CharField(max_length=16)
description = models.TextField()
timecreated = models.DecimalField(max_digits=14, decimal_places=3)
class Releases(modellib.XObjModel):
pubreleaseid = models.AutoField(primary_key=True)
productId = modellib.DeferredForeignKey(Project, db_column='projectid',
related_name='releasesProduct')
name = models.CharField(max_length=255)
version = models.CharField(max_length=32)
description = models.TextField()
timecreated = models.DecimalField(max_digits=14, decimal_places=3)
createdby = models.ForeignKey(rbuildermodels.Users, db_column='createdby',
related_name='releaseCreator')
timeupdated = models.DecimalField(max_digits=14, decimal_places=3)
updatedby = models.ForeignKey(rbuildermodels.Users, db_column='updatedby',
related_name='releaseUpdater')
timepublished = models.DecimalField(max_digits=14, decimal_places=3)
publishedby = models.ForeignKey(rbuildermodels.Users, db_column='publishedby',
related_name='releasePublisher')
shouldmirror = models.SmallIntegerField()
timemirrored = models.DecimalField(max_digits=14, decimal_places=3)
class Meta:
db_table = u'publishedreleases'
def __unicode__(self):
return self.name
class Image(modellib.XObjIdModel):
class Meta:
db_table = u'builds'
_xobj = xobj.XObjMetadata(
tag="image")
view_name = "ProjectImage"
def __unicode__(self):
return self.name
imageId = models.AutoField(primary_key=True, db_column='buildid')
productId = modellib.DeferredForeignKey(Project, db_column='projectid',
related_name="images")
pubreleaseid = models.ForeignKey(Releases, null=True,
db_column='pubreleaseid')
buildtype = models.IntegerField()
name = models.CharField(max_length=255)
description = models.TextField()
trovename = models.CharField(max_length=128)
troveversion = models.CharField(max_length=255)
troveflavor = models.CharField(max_length=4096)
trovelastchanged = models.DecimalField(max_digits=14,
decimal_places=3)
timecreated = models.DecimalField(max_digits=14, decimal_places=3)
createdby = models.ForeignKey(rbuildermodels.Users, db_column='createdby',
related_name='imageCreator')
timeupdated = models.DecimalField(max_digits=14, decimal_places=3,
null=True)
updatedby = models.ForeignKey(rbuildermodels.Users, db_column='updatedby',
related_name='imageUpdater', null=True)
deleted = models.SmallIntegerField()
buildcount = models.IntegerField()
productversionid = models.ForeignKey(Version,
db_column='productversionid')
stagename = models.CharField(max_length=255)
status = models.IntegerField()
statusmessage = models.TextField()
def get_absolute_url(self, request, parents=None, model=None):
if parents:
if isinstance(parents[0], Project):
self.view_name = "ProjectImages"
return modellib.XObjIdModel.get_absolute_url(self, request,
parents, model)
class Downloads(modellib.XObjModel):
class Meta:
db_table = u'urldownloads'
imageId = models.ForeignKey(Image, db_column='urlid')
timedownloaded = models.CharField(max_length=14)
ip = models.CharField(max_length=64)
|
Python
| 0.000001
|
@@ -81,24 +81,52 @@
ort models%0A%0A
+from mint import userlevels%0A
from mint.dj
@@ -2179,65 +2179,282 @@
def
-_attributes(self):%0A return (%7B%22id%22: self.hostname%7D)
+serialize(self, request):%0A xobjModel = modellib.XObjIdModel.serialize(self, request)%0A member = self.members.filter(userid=request._authUser)%0A if member:%0A role = userlevels%5Brole.level%5D%0A xobjModel.role = role%0A return xobjModel
%0A%0Acl
|
d112f8913bdfccfaf6e6bf9d8c48a4b57e437f7c
|
Rename file exists function
|
openassessment/fileupload/backends/filesystem.py
|
openassessment/fileupload/backends/filesystem.py
|
""" Filesystem backend for file upload. """
from pathlib import Path
from django.conf import settings
import django.core.cache
from django.urls import reverse
from django.utils.encoding import smart_text
from .. import exceptions
from .base import BaseBackend
class Backend(BaseBackend):
"""
Upload openassessment student files to a local filesystem. Note
that in order to use this file storage backend, you need to include the
urls from openassessment.fileupload in your urls.py file:
E.g:
url(r'^openassessment/storage', include(openassessment.fileupload.urls)),
The ORA2_FILEUPLOAD_CACHE_NAME setting will also have to be defined for the
name of the django.core.cache instance which will maintain the list of
active storage URLs.
E.g:
ORA2_FILEUPLOAD_CACHE_NAME = "ora2-storage"
CACHES = {
...
'ora2-storage': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
...
},
...
}
"""
def get_upload_url(self, key, content_type):
make_upload_url_available(self._get_key_name(key), self.UPLOAD_URL_TIMEOUT)
return self._get_url(key)
def get_download_url(self, key):
key_name = self._get_key_name(key)
if self._is_file_existing(key_name):
make_download_url_available(key_name, self.DOWNLOAD_URL_TIMEOUT)
return self._get_url(key)
return None
def remove_file(self, key):
from openassessment.fileupload.views_filesystem import safe_remove, get_file_path
return safe_remove(get_file_path(self._get_key_name(key)))
def _get_url(self, key):
key_name = self._get_key_name(key)
url = reverse("openassessment-filesystem-storage", kwargs={'key': key_name})
return url
def _is_file_existing(self, key_name):
from openassessment.fileupload.views_filesystem import get_file_path
file_path = get_file_path(key_name)
file_path = Path(file_path)
return file_path.exists()
def get_cache():
"""
Returns a django.core.cache instance in charge of maintaining the
authorized upload and download URL.
Raises:
FileUploadInternalError if the cache name setting is not defined.
InvalidCacheBackendError if the corresponding cache backend has not
been configured.
"""
cache_name = getattr(settings, "ORA2_FILEUPLOAD_CACHE_NAME", None)
if cache_name is None:
raise exceptions.FileUploadInternalError("Undefined cache backend for file upload")
return django.core.cache.caches[cache_name]
def make_upload_url_available(url_key_name, timeout):
"""
Authorize an upload URL.
Arguments:
url_key_name (str): key that uniquely identifies the upload url
timeout (int): time in seconds before the url expires
"""
get_cache().set(
smart_text(get_upload_cache_key(url_key_name)),
1, timeout
)
def make_download_url_available(url_key_name, timeout):
"""
Authorize a download URL.
Arguments:
url_key_name (str): key that uniquely identifies the url
timeout (int): time in seconds before the url expires
"""
get_cache().set(
smart_text(get_download_cache_key(url_key_name)),
1, timeout
)
def is_upload_url_available(url_key_name):
"""
Return True if the corresponding upload URL is available.
"""
return get_cache().get(smart_text(get_upload_cache_key(url_key_name))) is not None
def is_download_url_available(url_key_name):
"""
Return True if the corresponding download URL is available.
"""
return get_cache().get(smart_text(get_download_cache_key(url_key_name))) is not None
def get_upload_cache_key(url_key_name):
if isinstance(url_key_name, bytes):
url_key_name = url_key_name.decode('utf-8')
return "upload/" + url_key_name
def get_download_cache_key(url_key_name):
if isinstance(url_key_name, bytes):
url_key_name = url_key_name.decode('utf-8')
return "download/" + url_key_name
|
Python
| 0
|
@@ -1319,19 +1319,16 @@
f self._
-is_
file_exi
@@ -1329,19 +1329,17 @@
le_exist
-ing
+s
(key_nam
@@ -1857,11 +1857,8 @@
def
-_is
_fil
@@ -1864,19 +1864,17 @@
le_exist
-ing
+s
(self, k
|
f2395dd7c37798086cf7c67c0a8cfa7e48f4ec64
|
Remove unnecessary loop
|
atlas/mongo_read.py
|
atlas/mongo_read.py
|
try:
import simplejson as json
except ImportError:
import json
from pymongo import MongoClient
from pymongo.errors import PyMongoError
from atlas.constants import MONGO
__author__ = 'rblourenco@uchicago.edu'
# 2015-09-04 - Initial commit
class MongoRead(object):
def __init__(self, a_x, a_y, b_x, b_y, c_x, c_y, d_x, d_y, dpmm,
collection=None):
"""Class for geospatial information retrieval on MongoDB
:param a_x: Top left decimal longitude
:type a_x: float
:param a_y: Top left decimal latitude
:type a_y: float
:param b_x: Top right decimal longitude
:type b_x: float
:param b_y: Top right decimal latitude
:type b_y: float
:param c_x: Bottom right decimal longitude
:type c_x: float
:param c_y: Bottom right decimal latitude
:type c_y: float
:param d_x: Bottom left decimal longitude
:type d_x: float
:param d_y: Bottom left decimal latitude
:type d_y: float
:param dpmm: Dots per millimeter
:type dpmm: float
"""
self.a_x = a_x
self.a_y = a_y
self.b_x = b_x
self.b_y = b_y
self.c_x = c_x
self.c_y = c_y
self.d_x = d_x
self.d_y = d_y
self.dpmm = dpmm
if collection is None:
uri = "mongodb://{}:{}@{}/{}?authMechanism=SCRAM-SHA-1".format(
MONGO['user'], MONGO['password'], MONGO['domain'], MONGO['database']
)
client = MongoClient(uri) if not MONGO['local'] \
else MongoClient('localhost', MONGO['port'])
db = client['atlas']
collection = db['simulation_poly']
self.collection = collection
@property
def quadrilateral(self):
"""Returns the GeoJSON documents within a quadrilateral
:return: List of GeoJSON files
:rtype: list
"""
geojsonfiles = []
cursor = self.collection.find(
{'geometry': {'$geoIntersects': {
'$geometry': {'type': 'Polygon', 'coordinates': [
[[self.a_x, self.a_y], [self.b_x, self.b_y],
[self.c_x, self.c_y], [self.d_x, self.d_y],
[self.a_x, self.a_y]]]}}}},
projection={'_id': False, 'type': True, 'geometry': True,
'properties.value': True, })
for document in cursor:
geojsonfiles.append(document)
return geojsonfiles
@property
def multiscale(self):
geojsonfiles = []
return geojsonfiles
if __name__ == '__main__':
import pprint
pp = pprint.PrettyPrinter(indent=2)
try:
mr = MongoRead(46., 10., 48., 10., 48., 8., 46., 8., 1)
pp.pprint(mr.quadrilateral)
except PyMongoError, error:
print 'Error while reading on MongoDB.'
raise error
|
Python
| 0.000048
|
@@ -1946,34 +1946,8 @@
%22%22%22%0A
- geojsonfiles = %5B%5D%0A
@@ -2395,24 +2395,25 @@
rue, %7D)%0A
+%0A
for docu
@@ -2408,102 +2408,27 @@
-for document in cursor:%0A geojsonfiles.append(document)%0A%0A return geojsonfiles
+return list(cursor)
%0A%0A
|
be800d70ef3085035bc8330037f0881203e978cc
|
fix SSL vdsClient connections
|
ovirt_hosted_engine_ha/broker/submonitor_util.py
|
ovirt_hosted_engine_ha/broker/submonitor_util.py
|
#
# ovirt-hosted-engine-ha -- ovirt hosted engine high availability
# Copyright (C) 2013 Red Hat, Inc.
#
# 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 logging
import socket
import time
from otopi import util
from vdsm import vdscli
from . import constants
def run_vds_client_cmd(address, use_ssl, command):
"""
Run the passed in command name from the vdsClient library and either
throw an exception with the error message or return the results.
"""
# FIXME pass context to allow for shared or persistent vdsm connection
log = logging.getLogger('SubmonitorUtil')
log.debug("Connecting to vdsClient at %s with ssl=%r", address, use_ssl)
vdsClient = util.loadModule(
path=constants.VDS_CLIENT_DIR,
name='vdsClient'
)
if vdsClient._glusterEnabled:
serv = vdsClient.ge.GlusterService()
else:
serv = vdsClient.service()
serv.use_ssl = use_ssl
if hasattr(vdscli, 'cannonizeAddrPort'):
server, server_port = vdscli.cannonizeAddrPort(
address
).split(':', 1)
serv.do_connect(server, server_port)
else:
host_port = vdscli.cannonizeHostPort(address)
serv.do_connect(host_port)
log.debug("Connected")
method = getattr(serv.s, command)
retry = 0
while retry < constants.VDS_CLIENT_MAX_RETRY:
try:
response = method()
break
except socket.error:
log.debug("Error", exc_info=True)
retry += 1
time.sleep(1)
if retry >= constants.VDS_CLIENT_MAX_RETRY:
raise Exception("VDSM initialization timeout")
if response['status']['code'] != 0:
raise Exception("Error {0} from {1}: {2}",
response['status']['code'], command,
response['status']['message'])
return response
|
Python
| 0
|
@@ -1589,20 +1589,19 @@
serv.use
-_ssl
+SSL
= use_s
|
3f325f9ac4106eb8b27ec8efc309eeb6ce87bb76
|
Remove experimental dead code
|
base_geoengine/fields.py
|
base_geoengine/fields.py
|
# -*- coding: utf-8 -*-
##############################################################################
#
# 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/>.
#
##############################################################################
import logging
try:
from shapely.geometry import Point
from shapely.wkb import loads as wkbloads
import geojson
except ImportError:
logger = logging.getLogger(__name__)
logger.warning('Shapely or geojson are not available in the sys path')
from openerp.fields import Field
from .geo_helper import geo_convertion_helper as convert
from operator import attrgetter
class GeoField(Field):
""" The field descriptor contains the field definition common to all
specialized fields for geolocalization. Subclasses must define a type
and a geo_type. The type is the name of the corresponding column type,
the geo_type is the name of the corresponding type in the GIS system.
"""
geo_type = None
dim = 2
srid = 900913
gist_index = True
def convert_to_read(self, value, use_name_get=True):
res = convert.value_to_shape(value)
if res.is_empty:
return False
return geojson.dumps(res)
# properties used by to_column() to create a column instance
_column_dim = property(attrgetter('dim'))
_column_srid = property(attrgetter('srid'))
_column_gist_index = property(attrgetter('gist_index'))
@classmethod
def load_geo(cls, wkb):
"""Load geometry into browse record after read was done"""
return wkbloads(wkb.decode('hex')) if wkb else False
# type = 'many2one'
# _slots = {
# 'ondelete': 'set null', # what to do when value is deleted
# 'auto_join': False, # whether joins are generated upon search
# 'delegate': False, # whether self implements delegation
# }
# def convert_to_write(self, value, target=None, fnames=None):
# import pdb;pdb.set_trace()
# return value.id
#
# def convert_to_onchange(self, value):
# return value.id
#
# def convert_to_export(self, value, env):
# return bool(value) and value.name_get()[0][1]
#
# def convert_to_display_name(self, value, record=None):
# return ustr(value.display_name)
class GeoLine(GeoField):
"""Field for POSTGIS geometry Line type"""
type = 'geo_line'
geo_type = 'LINESTRING'
class GeoMultiLine(GeoField):
"""Field for POSTGIS geometry MultiLine type"""
type = 'geo_multi_line'
geo_type = 'MULTILINESTRING'
class GeoMultiPoint(GeoField):
"""Field for POSTGIS geometry MultiPoint type"""
type = 'geo_multi_point'
geo_type = 'MULTIPOINT'
class GeoMultiPolygon(GeoField):
"""Field for POSTGIS geometry MultiPolygon type"""
type = 'geo_multi_polygon'
geo_type = 'MULTIPOLYGON'
class GeoPoint(GeoField):
"""Field for POSTGIS geometry Point type"""
type = 'geo_point'
geo_type = 'POINT'
@classmethod
def from_latlon(cls, cr, latitude, longitude):
""" Convert a (latitude, longitude) into an UTM coordinate Point:
"""
pt = Point(longitude, latitude)
cr.execute("""
SELECT
ST_Transform(
ST_GeomFromText(%(wkt)s, 4326),
%(srid)s)
""", {'wkt': pt.wkt,
'srid': cls.srid})
res = cr.fetchone()
return cls.load_geo(res[0])
class GeoPolygon(GeoField):
"""Field for POSTGIS geometry Polygon type"""
type = 'geo_polygon'
geo_type = 'POLYGON'
|
Python
| 0.000027
|
@@ -2236,723 +2236,8 @@
se%0A%0A
- # type = 'many2one'%0A # _slots = %7B%0A # 'ondelete': 'set null', # what to do when value is deleted%0A # 'auto_join': False, # whether joins are generated upon search%0A # 'delegate': False, # whether self implements delegation%0A # %7D%0A%0A # def convert_to_write(self, value, target=None, fnames=None):%0A # import pdb;pdb.set_trace()%0A # return value.id%0A #%0A # def convert_to_onchange(self, value):%0A # return value.id%0A #%0A # def convert_to_export(self, value, env):%0A # return bool(value) and value.name_get()%5B0%5D%5B1%5D%0A #%0A # def convert_to_display_name(self, value, record=None):%0A # return ustr(value.display_name)%0A%0A
%0Acla
|
70ad96b2e6f46fbc0fa184ad767dada0212a40a5
|
Use reflect mode, not constant
|
basics/bubble_segment.py
|
basics/bubble_segment.py
|
import numpy as np
import warnings
import scipy.ndimage as nd
from astropy.nddata.utils import extract_array, add_array
from astropy.utils.console import ProgressBar
import astropy.units as u
import skimage.morphology as mo
from skimage.filters import threshold_adaptive
from radio_beam import Beam
from spectral_cube.lower_dimensional_structures import LowerDimensionalObject
from basics.utils import arctan_transform
class BubbleSegment(object):
"""
Image segmentation for bubbles in a 2D image.
"""
def __init__(self, array, scales=[], atan_transform=True, threshold=None,
mask=None, cut_to_box=False, pad_size=0, structure="beam",
beam=None, wcs=None):
if isinstance(array, LowerDimensionalObject):
self.array = array.value
self.wcs = array.wcs
if 'beam' in array.meta:
self.beam = array.meta['beam']
elif beam is not None:
self.beam = beam
else:
raise KeyError("No 'beam' in metadata. Must manually specify "
"the beam with the beam keyword.")
elif isinstance(array, np.ndarray):
self.array = array
if beam is not None:
self.beam = beam
else:
raise KeyError("Must specify the beam with the beam keyword.")
if wcs is not None:
self.wcs = wcs
else:
raise KeyError("Must specify the wcs with the wcs keyword.")
self._threshold = threshold
self.mask = mask
self.pad_size = pad_size
self.scales = scales
self._atan_flag = False
@property
def mask(self):
return self._mask
@mask.setter
def mask(self, mask_array):
if mask_array is None:
self._mask = np.ones_like(mask_array).astype(bool)
else:
if mask_array.shape != self.array.shape:
raise TypeError("mask must match the shape of the given "
"array.")
self._mask = mask_array
@property
def array(self):
return self._array
@array.setter
def array(self, input_array):
if input_array.ndim != 2:
raise TypeError("Given array must be 2D.")
self._array = input_array
@property
def pad_size(self):
return self._pad_size
@pad_size.setter
def pad_size(self, value):
if value < 0:
raise ValueError("Pad size must be >=0")
self._pad_size = value
def apply_atan_transform(self, threshold=None):
if self._atan_flag:
warnings.warn("arctan transform already applied to the data.")
return
if threshold is not None:
self._threshold = threshold
self._array = arctan_transform(self.array, self._threshold)
self._atan_flag = True
def cut_to_bounding_box(self, pad_size=0):
'''
Reduce the array down to the minimum size based on the mask.
Optionally add padding to the reduced size.
'''
if pad_size != self.pad_size:
self.pad_size = pad_size
mask_pixels = np.where(self.mask)
yedges = [mask_pixels[0].min(), mask_pixels[0].max()]
xedges = [mask_pixels[1].min(), mask_pixels[1].max()]
self._corner_coords = (yedges[0], xedges[0])
cut_shape = (yedges[1]+1-yedges[0], xedges[1]+1-xedges[0])
cut_arr = extract_array(self.array, cut_shape, self.corner_coords)
cut_mask = extract_array(self.mask, cut_shape, self.corner_coords)
if self.pad_size > 0:
# Pads edges with zeros
self.array = np.pad(cut_arr, self.pad_size, mode='constant')
self.mask = np.pad(cut_mask, self.pad_size, mode='constant')
else:
self.array = cut_arr
self.mask = cut_mask
@property
def corner_coords(self):
return self._corner_coords
def insert_in_shape(self, shape):
'''
Insert the cut down mask into the given shape.
'''
if self.bubble_mask.shape == shape:
return self.bubble_mask
else:
full_size = np.zeros(shape)
return add_array(full_size, self.bubble_mask, self.corner_coords)
def multiscale_bubblefind(self, scales=None):
'''
Run find_bubbles on the specified scales.
'''
if scales is not None:
self.scales = scales
self._bubble_mask = np.zeros_like(self.array)
for scale in ProgressBar(self.scales):
self._bubble_mask += find_bubbles(self.array, scale,
self.beam, self.wcs)
def find_bubbles(array, scale, beam, wcs):
# In deg/pixel
# pixscale = get_pixel_scales(wcs) * u.deg
pixscale = np.abs(wcs.pixel_scale_matrix[0, 0])
struct, scale_beam = beam_struct(beam, scale, pixscale,
return_beam=True)
struct_orig = beam_struct(beam, 1, pixscale)
# Black tophat
bth = nd.black_tophat(array, structure=struct, mode='constant')
# Adaptive threshold
adapt = \
threshold_adaptive(bth,
int(np.floor((scale_beam.major/pixscale).value)),
param=np.floor(scale_beam.major.value/pixscale)/2)
# Open/close to clean things up
opened = nd.binary_opening(adapt, structure=struct_orig)
closed = nd.binary_closing(opened, structure=struct_orig)
# Remove elements smaller than the original beam.
beam_pixels = np.floor(beam.sr.to(u.deg**2)/pixscale**2).astype(int).value
cleaned = mo.remove_small_objects(closed, min_size=beam_pixels,
connectivity=2)
return cleaned
def beam_struct(beam, scale, pixscale, return_beam=False):
'''
Return a beam structure.
'''
if scale == 1:
scale_beam = beam
else:
scale_beam = Beam(major=scale*beam.major,
minor=scale*beam.minor,
pa=beam.pa)
struct = scale_beam.as_tophat_kernel(pixscale).array
struct = (struct > 0).astype(int)
if return_beam:
return struct, scale_beam
return struct
|
Python
| 0.000002
|
@@ -5181,33 +5181,16 @@
e=struct
-, mode='constant'
)%0A%0A #
|
bf460618bc0b2e535de46a0dc0ddb08b8680ab6c
|
Stop to use the __future__ module.
|
octavia/db/migration/alembic_migrations/env.py
|
octavia/db/migration/alembic_migrations/env.py
|
# Copyright 2014 Rackspace
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import with_statement
import sys
from alembic import context
from sqlalchemy import create_engine
from sqlalchemy import pool
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
try:
octavia_config = config.octavia_config
except AttributeError:
print("Error: Please use the octavia-db-manage command for octavia"
" alembic actions.")
sys.exit(1)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = None
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
context.configure(url=octavia_config.database.connection,
target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
engine = create_engine(
octavia_config.database.connection,
poolclass=pool.NullPool)
connection = engine.connect()
context.configure(
connection=connection,
target_metadata=target_metadata)
try:
with context.begin_transaction():
context.run_migrations()
finally:
connection.close()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
|
Python
| 0.999929
|
@@ -602,47 +602,8 @@
e.%0A%0A
-from __future__ import with_statement%0A%0A
impo
|
f562fd203c441c10269c0a28861c1238c8a0947e
|
Simplify the closeness checking
|
euclid.py
|
euclid.py
|
"""
Simple 2D Euclidean geometric primitives.
"""
from collections import namedtuple
import math
EPSILON = 1e-8
def _near_zero(v):
return math.isclose(v, 0, abs_tol=EPSILON)
class BadGeometry(Exception):
"""Any exception raised by euclid."""
pass
class Point(namedtuple("Point", ["x", "y"])):
"""A point in 2D."""
def __repr__(self):
return f"<{self.x:.1f}, {self.y:.1f}>"
def __eq__(self, other):
assert isinstance(other, Point)
x1, y1 = self
x2, y2 = other
return _near_zero(x1 - x2) and _near_zero(y1 - y2)
def __hash__(self):
return tuple.__hash__(self)
def distance(self, other):
"""Compute the distance from this Point to another Point."""
assert isinstance(other, Point)
x1, y1 = self
x2, y2 = other
return math.hypot(x2 - x1, y2 - y1)
def in_box(self, ll, ur):
"""Is this point in the box defined by the lower-left and upper-right points?"""
x, y = self
llx, lly = ll
urx, ury = ur
return (llx <= x <= urx) and (lly <= y <= ury)
def collinear(p1, p2, p3):
"""Do three points lie on a line?"""
# https://stackoverflow.com/questions/3813681/checking-to-see-if-3-points-are-on-the-same-line
(x1, y1), (x2, y2), (x3, y3) = p1, p2, p3
return _near_zero((y1 - y2) * (x1 - x3) - (y1 - y3) * (x1 - x2))
class Line(namedtuple("Line", ["p1", "p2"])):
"""A line in 2D, defined by two Points."""
def intersect(self, other):
"""
Find the point where this Line and another intersect.
Raises BadGeometry if the lines are parallel or coincident.
"""
# https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
assert isinstance(other, Line)
(x1, y1), (x2, y2) = self
(x3, y3), (x4, y4) = other
denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if _near_zero(denom):
raise BadGeometry("Lines don't intersect usefully: denom = {}".format(denom))
a = x1 * y2 - y1 * x2
b = x3 * y4 - y3 * x4
xi = (a * (x3 - x4) - b * (x1 - x2)) / denom
yi = (a * (y3 - y4) - b * (y1 - y2)) / denom
return Point(xi, yi)
def offset(self, distance):
"""Create another Line `distance` from this one."""
(x1, y1), (x2, y2) = self
dx = x2 - x1
dy = y2 - y1
hyp = math.hypot(dx, dy)
offx = dy / hyp * distance
offy = -dx / hyp * distance
return Line(Point(x1 + offx, y1 + offy), Point(x2 + offx, y2 + offy))
|
Python
| 0.000025
|
@@ -97,40 +97,24 @@
h%0A%0A%0A
-EPSILON = 1e-8%0A%0Adef _near_zero(v
+def isclose(a, b
):%0A
@@ -140,12 +140,12 @@
ose(
-v, 0
+a, b
, ab
@@ -154,15 +154,12 @@
tol=
-EPSILON
+1e-8
)%0A%0A%0A
@@ -518,23 +518,19 @@
urn
-_near_zero(x1 -
+isclose(x1,
x2)
@@ -538,23 +538,19 @@
and
-_near_zero(y1 -
+isclose(y1,
y2)
@@ -1306,26 +1306,23 @@
return
-_near_zero
+isclose
((y1 - y
@@ -1335,18 +1335,17 @@
x1 - x3)
- -
+,
(y1 - y
@@ -1900,24 +1900,24 @@
if
-_near_zero
+isclose
(denom
+, 0
):%0A
|
38968cd1c0659ad258ac976c6950e1e8ebb98541
|
Replace dashes with underscores when resolving commands
|
valohai_cli/plugin_cli.py
|
valohai_cli/plugin_cli.py
|
import pkgutil
from collections import defaultdict
from importlib import import_module
import click
from valohai_cli.utils import cached_property, match_prefix
class PluginCLI(click.MultiCommand):
aliases = {
'new': 'create',
'start': 'run',
}
def __init__(self, **kwargs):
self._commands_module = kwargs.pop('commands_module')
self.aliases = dict(self.aliases, **kwargs.get('aliases', {})) # instance level copy
super(PluginCLI, self).__init__(**kwargs)
@cached_property
def commands_module(self):
if isinstance(self._commands_module, str):
return import_module(self._commands_module)
return self._commands_module
@cached_property
def command_modules(self):
return sorted(c[1] for c in pkgutil.iter_modules(self.commands_module.__path__))
@cached_property
def command_to_canonical_map(self):
command_map = dict((command, command) for command in self.command_modules)
for alias_from, alias_to in self.aliases.items():
if alias_to in command_map:
command_map[alias_from] = command_map.get(alias_to, alias_to) # resolve aliases
return command_map
def list_commands(self, ctx):
return self.command_modules
def get_command(self, ctx, name):
command_map = self.command_to_canonical_map
if name in command_map:
return self._get_command(command_map[name])
matches = match_prefix(command_map.keys(), name, return_unique=False)
if len(matches) == 1:
match = command_map[matches[0]]
return self._get_command(match)
if ' ' not in name:
# Try word suffix matching if possible.
# That is, if the user attempts `vh link` but we know about `vh proj link`, do that.
command_map = {' '.join(trail): cmd for (trail, cmd) in self._get_all_commands(ctx)}
s_matches = [key for key in command_map.keys() if ' ' in key and key.endswith(' ' + name)]
if len(s_matches) == 1:
match = s_matches[0]
click.echo('(Resolved {name} to {match}.)'.format(
name=click.style(name, bold=True),
match=click.style(match, bold=True),
), err=True)
return command_map[match]
if len(matches) > 1:
ctx.fail('"{name}" matches {matches}; be more specific?'.format(
name=name,
matches=', '.join(click.style(match, bold=True) for match in sorted(matches))
))
return None
def resolve_command(self, ctx, args):
cmd_name, cmd, rest_args = super(PluginCLI, self).resolve_command(ctx, args)
return (cmd.name, cmd, rest_args) # Always use the canonical name of the command
def _get_command(self, name):
module = import_module('%s.%s' % (self.commands_module.__name__, name))
return getattr(module, name)
def _get_all_commands(self, ctx):
def walk_commands(multicommand, name_trail=()):
for subcommand in multicommand.list_commands(ctx):
cmd = multicommand.get_command(ctx, subcommand)
assert cmd is not None
new_name_trail = name_trail + (cmd.name,)
yield (new_name_trail, cmd)
if isinstance(cmd, click.MultiCommand):
for o in walk_commands(cmd, new_name_trail):
yield o
for o in walk_commands(self):
yield o
class RecursiveHelpPluginCLI(PluginCLI):
def format_commands(self, ctx, formatter):
rows_by_prefix = defaultdict(list)
for trail, command in self._get_all_commands(ctx):
prefix = (' '.join(trail[:1]) if len(trail) > 1 else '')
help = (command.short_help or command.help or '').partition('\n')[0]
rows_by_prefix[prefix.strip()].append((' '.join(trail).strip(), help))
for prefix, rows in sorted(rows_by_prefix.items()):
title = (
'Commands (%s ...)' % prefix
if prefix
else 'Commands'
)
with formatter.section(title):
formatter.write_dl(rows)
|
Python
| 0.000121
|
@@ -1314,32 +1314,157 @@
lf, ctx, name):%0A
+ # Dashes aren't valid in Python identifiers, so let's just replace them here.%0A name = name.replace('-', '_')%0A%0A
command_
|
0592bd3759fad25a8aa50cd2e2e5a853d0863202
|
Handle implicit encode/decode errors in Py3 (#4).
|
requests_negotiate/__init__.py
|
requests_negotiate/__init__.py
|
import base64
import re
import logging
import gssapi
from requests.auth import AuthBase
from requests.compat import urlparse
import www_authenticate
logger = logging.getLogger(__name__)
class HTTPNegotiateAuth(AuthBase):
def __init__(self, service='HTTP', service_name=None,
negotiate_client_name=None, preempt=False):
self.service = service
self.service_name = service_name
self.contexts = {}
self.preempt = preempt
self.negotiate_client_name = negotiate_client_name
def __call__(self, request):
host = urlparse(request.url).hostname
if self.preempt or host in self.contexts:
logger.debug("__call__(): pre-emptively sending authorization"
"header")
self.contexts[host] = ctx = self.get_context(host)
token = ctx.step(None)
token_b64 = base64.b64encode(token).decode('utf-8')
request.headers['Authorization'] = 'Negotiate ' + token_b64
request.register_hook('response', self.handle_401)
return request
@property
def username(self):
logging.debug("Obtaining username from GSSAPI")
credential = gssapi.Credential(usage=gssapi.C_INITIATE)
logging.debug("Username={0}".format(credential.name))
return str(credential.name)
def get_context(self, host):
service_name = gssapi.Name(self.service_name or '{0}@{1}'.format(self.service, host),
gssapi.NameType.hostbased_service)
logging.debug("get_context(): service name={0}".format(service_name))
if self.negotiate_client_name:
creds = gssapi.Credentials(name=gssapi.Name(self.negotiate_client_name),
usage='initiate')
else:
creds = None
return gssapi.SecurityContext(name=service_name,
creds=creds)
def get_challenges(self, response):
challenges = {}
for k, v in response.headers.items():
if k.lower() == 'www-authenticate':
challenges.update(www_authenticate.parse(v))
return challenges
def handle_401(self, response, **kwargs):
logger.debug("Starting to handle 401 error")
logger.debug(response.headers)
challenges = self.get_challenges(response)
logger.debug("auth_methods={0}".format(challenges))
if 'negotiate' not in challenges:
logger.debug("Giving up on negotiate auth")
return response
host = urlparse(response.url).hostname
logger.debug("host={0}".format(host))
if host in self.contexts:
ctx = self.contexts[host]
else:
ctx = self.contexts[host] = self.get_context(host)
logger.debug("ctx={0}".format(ctx))
in_token = base64.b64decode(challenges['negotiate']) \
if challenges['negotiate'] else None
out_token = base64.b64encode(ctx.step(in_token))
while response.status_code == 401 and not ctx.complete:
response.content
response.raw.release_conn()
new_request = response.request.copy()
new_request.headers['Authorization'] = 'Negotiate ' + out_token
new_response = response.connection.send(new_request, **kwargs)
new_response.history.append(response)
new_response.request = new_request
response = new_response
challenges = self.get_challenges(response)
in_token = base64.b64decode(challenges['negotiate'])
out_token = ctx.step(in_token)
if out_token:
out_token = base64.b64encode(out_token)
return response
|
Python
| 0
|
@@ -2919,12 +2919,28 @@
te'%5D
+.encode('ascii')
) %5C%0A
-
@@ -3005,33 +3005,16 @@
token =
-base64.b64encode(
ctx.step
@@ -3023,17 +3023,16 @@
n_token)
-)
%0A
@@ -3262,32 +3262,84 @@
%5D =
-'Negotiate ' + out_token
+%5C%0A 'Negotiate ' + base64.b64encode(out_token).decode('ascii')
%0A
@@ -3661,16 +3661,25 @@
otiate'%5D
+.encode()
)%0A
@@ -3718,90 +3718,8 @@
ken)
-%0A if out_token:%0A out_token = base64.b64encode(out_token)
%0A%0A
|
25866e86338ac2cf0f042dded6a343a00b5f7241
|
Bump version to 0.5.0-alpha.4.
|
rnachipintegrator/__init__.py
|
rnachipintegrator/__init__.py
|
# Current version of the library
__version__ = '0.5.0-alpha.3'
def get_version():
"""Returns a string with the current version of the library (e.g., "0.2.0")
"""
return __version__
|
Python
| 0
|
@@ -57,9 +57,9 @@
pha.
-3
+4
'%0A%0Ad
|
e7421c5e8f3f26a617e71ee04fd16a7ebba97d53
|
Remove unneeded import
|
bibpy/lexers/__init__.py
|
bibpy/lexers/__init__.py
|
"""Various lexer functions used by the funcparserlib parser."""
import funcparserlib.lexer as lexer
import bibpy
from bibpy.compat import u
from bibpy.lexers.biblexer import BibLexer
from bibpy.lexers.name_lexer import NameLexer
from bibpy.lexers.namelist_lexer import NamelistLexer
from funcparserlib.lexer import Token
def remove_whitespace_tokens(tokens):
"""Remove any whitespace tokens from the given list of tokens."""
return [token for token in tokens if token.type != 'space']
def lex_bib(string):
"""Return a generator of bib(la)tex tokens."""
return remove_whitespace_tokens(BibLexer().lex(string))
def lex_date(date_string):
"""Return the biblatex date tokens in a string."""
tokenizer = lexer.make_tokenizer([
('number', [u('[0-9]+')]),
('dash', [u('-')]),
('slash', [u('/')])
])
return list(tokenizer(date_string))
def lex_string_expr(string):
"""Return the tokens in a string expression."""
tokenizer = lexer.make_tokenizer([
('concat', [u('#')]),
('string', [u('"[^"]+"')]),
('name', [u('[A-Za-z_][A-Za-z_0-9\-:?\'\.\s]*')]),
('space', [u('[ \t\r\n]+')]),
])
try:
return remove_whitespace_tokens(tokenizer(string))
except lexer.LexerError:
# If we fail to lex the string, it is not a valid string expression so
# just return it as a token
return [Token('string', string)]
def lex_braced_expr(string):
"""Return the tokens in a braced expression."""
tokenizer = lexer.make_tokenizer([
('lbrace', [u('{')]),
('rbrace', [u('}')]),
('content', [u('[^{}]+')]),
])
return remove_whitespace_tokens(tokenizer(string))
def lex_namelist(string):
"""Lex a namelist delimited by 'and'."""
return [token for token in NamelistLexer().lex(string) if token]
def lex_name(string):
"""Return a generator of bib(la)tex name tokens."""
name_lexer = NameLexer()
return [token.value for token in name_lexer.lex(string)], name_lexer.commas
def lex_generic_query(query):
"""Return the tokens in a query."""
tokenizer = lexer.make_tokenizer([
('not', [u('\^')]),
('equals', [u('=')]),
('approx', [u('~')]),
('le', [u('<=')]),
('lt', [u('<')]),
('ge', [u('>=')]),
('gt', [u('>')]),
('comma', [u(',')]),
('dash', [u('-')]),
('number', [u('-?(0|([1-9][0-9]*))')]),
('name', [u('\w+')]),
('space', [u('[ \t\r\n]+')]),
('any', [u('[^<><=>=\s=\^~]+')])
])
return remove_whitespace_tokens(tokenizer(query))
|
Python
| 0.000002
|
@@ -98,21 +98,8 @@
xer%0A
-import bibpy%0A
from
|
f97272eebc60eff9ca20550d4c8a3ba0f68817d9
|
Remove a bit of debug code
|
linehaul/server.py
|
linehaul/server.py
|
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import itertools
import uuid
from functools import partial
from typing import Optional
import arrow
import cattr
import tenacity
import trio
from linehaul.events import parser as _event_parser
from linehaul.protocol import LineReceiver
from linehaul.syslog import parser as _syslog_parser
retry = partial(tenacity.retry, sleep=trio.sleep)
_cattr = cattr.Converter()
_cattr.register_unstructure_hook(arrow.Arrow, lambda o: o.float_timestamp)
#
# Non I/O Functions
#
def parse_line(line: bytes, token=None) -> Optional[_event_parser.Download]:
line = line.decode("utf8")
# Check our token, and remove it from the start of the line if it matches.
if token is not None:
# TODO: Use a Constant Time Compare?
if not line.startswith(token):
return
line = line[len(token) :]
# Parse the incoming Syslog Message, and get the download event out of it.
try:
msg = _syslog_parser.parse(line)
event = _event_parser.parse(msg.message)
except ValueError:
# TODO: Better Error Logging.
return
return event
def extract_item_date(item):
return item.timestamp.format("YYYYMDDD")
def compute_batches(all_items):
for date, items in itertools.groupby(
sorted(all_items, key=extract_item_date), extract_item_date
):
items = list(items)
yield extract_item_date(items[0]), [
{"insertId": str(uuid.uuid4()), "json": row}
for row in _cattr.unstructure(items[:1])
],
#
# I/O Functions
#
async def handle_connection(stream, q, token=None):
lr = LineReceiver(partial(parse_line, token=token))
while True:
try:
data: bytes = await stream.receive_some(1024)
except trio.BrokenStreamError:
data = b""
if not data:
lr.close()
break
for msg in lr.recieve_data(data):
await q.put(msg)
@retry(
retry=tenacity.retry_if_exception_type(trio.TooSlowError),
wait=tenacity.wait_random_exponential(multiplier=1, max=60),
stop=tenacity.stop_after_attempt(15),
reraise=True,
)
async def actually_send_batch(bq, table, template_suffix, batch):
with trio.fail_after(15): # TODO: Is 15 seconds a good value?
await bq.insert_all(table, batch, template_suffix)
async def send_batch(*args, **kwargs):
# We split up send_batch and actually_send_batch so that we can use tenacity to
# handle retries for us, while still getting to use the Nurser.start_soon interface.
# This also makes it easier to deal with the error handling aspects of sending a
# batch, from the work of actually sending. The general rule here is that errors
# shoudl not escape from this function.
try:
await actually_send_batch(*args, **kwargs)
except Exception:
# We've tried to send this batch to BigQuery, however for one reason or another
# we were unable to do so. We should log this error, but otherwise we're going
# to just drop this on the floor because there's not much else we can do here
# except buffer it forever (which is not a great idea).
# TODO: Add Logging
pass
async def sender(bq, table, q, *, batch_size=None, batch_timeout=None):
if batch_size is None:
batch_size = 3 # TODO: Change to 500
if batch_timeout is None:
batch_timeout = 30
async with trio.open_nursery() as nursery:
while True:
batch = []
with trio.move_on_after(batch_timeout):
while len(batch) < batch_size:
batch.append(await q.get())
for template_suffix, batch in compute_batches(batch):
nursery.start_soon(send_batch, bq, table, template_suffix, batch)
#
# Main Entry point
#
async def server(
bq,
table,
bind="0.0.0.0",
port=512,
token=None,
qsize=1000, # TODO: Determine the best default size for this queue.
batch_size=None,
batch_timeout=None,
task_status=trio.TASK_STATUS_IGNORED,
):
# Total number of buffered events is:
# qsize + (COUNT(send_batch) * batch_size)
# However, the length of time a single send_batch call sticks around for is time
# boxed, so this won't grow forever. It will not however, apply any backpressure
# to the sender (we can't meaningfully apply backpressure, since these are download
# events being streamed to us).
q = trio.Queue(qsize)
async with trio.open_nursery() as nursery:
nursery.start_soon(
partial(
sender, bq, table, q, batch_size=batch_size, batch_timeout=batch_timeout
)
)
await nursery.start(
trio.serve_tcp, partial(handle_connection, q=q, token=token), port
)
task_status.started()
|
Python
| 0.00066
|
@@ -2043,12 +2043,8 @@
tems
-%5B:1%5D
)%0A
|
fc3fa9871f0edc4c76a201547ec8c7f457aa2b35
|
fix msg string and rename 'iter' variable
|
modules/bibcatalog/lib/bibcatalog_templates.py
|
modules/bibcatalog/lib/bibcatalog_templates.py
|
## This file is part of Invenio.
## Copyright (C) 2009, 2010, 2011 CERN.
##
## Invenio 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 2 of the
## License, or (at your option) any later version.
##
## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Invenio BibCatalog HTML generator."""
from invenio.bibcatalog import bibcatalog_system
from invenio.messages import wash_language, gettext_set_language
from invenio.config import CFG_SITE_LANG
from invenio.webstyle_templates import Template as DefaultTemplate
class Template(DefaultTemplate):
""" HTML generators for BibCatalog """
SHOW_MAX_TICKETS = 25
def tmpl_your_tickets(self, uid, ln=CFG_SITE_LANG, start=1):
""" make a pretty html body of tickets that belong to the user given as param """
ln = wash_language(ln)
_ = gettext_set_language(ln)
#errors? tell what happened and get out
bibcat_probs = bibcatalog_system.check_system(uid)
if bibcat_probs:
return _("Error")+" "+bibcat_probs
tickets = bibcatalog_system.ticket_search(uid, owner=uid) #get ticket id's
lines = "" #put result here
iter = 1
lines += _("You have ")+str(len(tickets))+" "+_("tickets")+".<br/>"
#make a prev link if needed
if (start > 1):
newstart = start - self.SHOW_MAX_TICKETS
if (newstart < 1):
newstart = 1
lines += '<a href="/yourtickets/display?start='+str(newstart)+'">'+_("Previous")+'</a>'
lines += """<table border="1">"""
lastshown = len(tickets) #what was the number of the last shown ticket?
for ticket in tickets:
#get info and show only for those that within the show range
if (iter >= start) and (iter < start+self.SHOW_MAX_TICKETS):
ticket_info = bibcatalog_system.ticket_get_info(uid, ticket)
subject = ticket_info['subject']
status = ticket_info['status']
text = ""
if ticket_info.has_key('text'):
text = ticket_info['text']
display = '<a href="'+ticket_info['url_display']+'">'+_("show")+'</a>'
close = '<a href="'+ticket_info['url_close']+'">'+_("close")+'</a>'
lines += "<tr><td>"+str(ticket)+"</td><td>"+subject+" "+text+"</td><td>"+status+"</td><td>"+display+"</td><td>"+close+"</td></tr>\n"
lastshown = iter
iter = iter+1
lines += "</table>"
#make next link if needed
if (len(tickets) > lastshown):
newstart = lastshown+1
lines += '<a href="/yourtickets/display?start='+str(newstart)+'">'+_("Next")+'</a>'
return lines
|
Python
| 0.000002
|
@@ -1668,19 +1668,16 @@
i
-ter
= 1%0A%0A
@@ -1691,16 +1691,17 @@
ines +=
+(
_(%22You h
@@ -1708,48 +1708,41 @@
ave
-%22)+str(len(tickets))+%22 %22+_(%22
+%25i tickets.%22) %25 len(
tickets
-%22)+%22.
+)) + %22
%3Cbr/
@@ -2261,19 +2261,16 @@
if (i
-ter
%3E= star
@@ -2278,19 +2278,16 @@
) and (i
-ter
%3C start
@@ -2954,19 +2954,16 @@
hown = i
-ter
%0A
@@ -2972,18 +2972,12 @@
i
-ter
= i
-ter
+1%0A
|
1193980f77d715e1ca2b22bcb8a4b74eaed1122c
|
Add missing import
|
lino_book/projects/polls/test.py
|
lino_book/projects/polls/test.py
|
from lino.utils.djangotest import WebIndexTestCase
|
Python
| 0.000466
|
@@ -1,8 +1,44 @@
+from lino.utils.test import DocTest%0A
from lin
|
26e14ff342e9063a6378f6b38be96b037df746c3
|
Fix ordering validation and parsing
|
avocado/query/parsers/dataview.py
|
avocado/query/parsers/dataview.py
|
from modeltree.tree import trees
from modeltree.query import ModelTreeQuerySet
from django.core.exceptions import ValidationError
def has_keys(obj, keys):
"Check the required keys are present in `obj`"
for key in keys:
if key not in obj:
return False
return True
class Node(object):
def __init__(self, concepts=None, ordering=None, **context):
self.concept_ids = concepts or []
self.ordering = ordering or []
self.tree = context.pop('tree', None)
self.context = context
def apply(self, queryset=None, include_pk=True):
tree = trees[self.tree]
if queryset is None:
queryset = tree.get_queryset()
queryset = ModelTreeQuerySet(tree, query=queryset.query)
if self.concept_ids:
queryset = queryset.select(*[f.field for f in self.fields], include_pk=include_pk)
if self.ordering:
queryset = queryset.order_by(*self.order_by)
return queryset
@property
def concepts(self):
from avocado.models import DataConcept
concepts = list(DataConcept.objects.filter(pk__in=self.concept_ids))
concepts.sort(key=lambda o: self.concept_ids.index(o.pk))
return concepts
@property
def fields(self):
fields = []
for concept in self.concepts:
fields.extend(list(concept.fields.select_related('concept_fields')\
.order_by('concept_fields__order')))
return fields
@property
def order_by(self):
order_by = []
if self.ordering:
from avocado.models import DataConcept
tree = trees[self.tree]
ids, directions = zip(*self.ordering)
concepts = list(DataConcept.objects.filter(pk__in=ids))
concepts.sort(key=lambda o: ids.index(o.pk))
fields = []
for concept in self.concepts:
fields.append(concept.fields.select_related('concept_fields')\
.order_by('concept_fields__order'))
for i, direction in enumerate(directions):
for f in fields[i]:
qstr = tree.query_string_for_field(f.field)
if direction == 'desc':
qstr = '-' + qstr
order_by.append(qstr)
return order_by
def validate(attrs, **context):
if not attrs:
return
concepts = attrs.get('concepts', [])
ordering = attrs.get('ordering', [])
node = Node(concepts, ordering, **context)
if concepts and len(node.concepts) != len(concepts):
raise ValidationError('One or more concepts do not exist')
if ordering and len(node.order_by) != len(ordering):
raise ValidationError('One or more concepts do not exist')
def parse(attrs, **context):
if not attrs:
return Node(**context)
concepts = attrs.get('concepts', None)
ordering = attrs.get('ordering', None)
return Node(concepts, ordering, **context)
|
Python
| 0.000001
|
@@ -1886,37 +1886,32 @@
for concept in
-self.
concepts:%0A
@@ -1934,16 +1934,21 @@
.append(
+list(
concept.
@@ -2043,16 +2043,17 @@
order'))
+)
%0A%0A
@@ -2694,50 +2694,153 @@
ring
- and len(node.order_by) != len(ordering):%0A
+:%0A for pk, direction in ordering:%0A if direction not in ('asc', 'desc') or (type(pk) is not int and str(pk).isdigit()):%0A
|
06a2e65423a6e26e3226cda724112219c0867fdd
|
Fix missing else
|
readthedocs/core/management/commands/update_repos.py
|
readthedocs/core/management/commands/update_repos.py
|
"""
Custom management command to rebuild documentation for all projects.
Invoked via ``./manage.py update_repos``.
"""
import logging
from django.core.management.base import BaseCommand
from readthedocs.builds.constants import EXTERNAL, INTERNAL
from readthedocs.builds.models import Version
from readthedocs.core.utils import trigger_build
from readthedocs.projects.models import Project
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""Management command for rebuilding documentation on projects."""
help = __doc__
def add_arguments(self, parser):
parser.add_argument('slugs', nargs='+', type=str)
parser.add_argument(
'-f',
action='store_true',
dest='force',
default=False,
help='Force a build in sphinx',
)
parser.add_argument(
'-V',
dest='version',
default='all',
help='Build a version, or all versions',
)
def handle(self, *args, **options):
force = options['force']
version = options['version']
if options.get('slugs', []):
for slug in options['slugs']:
if version and version != 'all':
log.info('Updating version %s for %s', version, slug)
for version in Version.objects.filter(
project__slug=slug,
slug=version,
):
trigger_build(project=version.project, version=version)
elif version == 'all':
log.info('Updating all versions for %s', slug)
for version in Version.objects.filter(
project__slug=slug,
active=True,
uploaded=False,
):
trigger_build(project=version.project, version=version)
elif version == INTERNAL:
log.info('Updating all internal versions for %s', slug)
for version in Version.internal.filter(
project__slug=slug,
active=True,
uploaded=False,
):
trigger_build(project=version.project, version=version)
elif version == EXTERNAL:
log.info('Updating all external versions for %s', slug)
for version in Version.external.filter(
project__slug=slug,
active=True,
uploaded=False,
):
trigger_build(project=version.project, version=version)
else:
p = Project.all_objects.get(slug=slug)
log.info('Building %s', p)
trigger_build(project=p, force=force)
else:
if version == 'all':
log.info('Updating all versions')
for version in Version.objects.filter(
active=True,
uploaded=False,
):
trigger_build(project=version.project, version=version)
log.info('Updating all docs')
for project in Project.objects.all():
# pylint: disable=no-value-for-parameter
default_version = project.get_default_version()
version = project.versions.get(slug=default_version)
trigger_build(project=version.project, version=version)
|
Python
| 0.998982
|
@@ -3299,16 +3299,34 @@
rsion)%0A%0A
+ else:%0A
|
fcb7435cd6ae2710406fedfe340d66f3564a31c3
|
Disable PositionLog and Noise filters (no need in production)
|
roboime/interface/__init__.py
|
roboime/interface/__init__.py
|
#from sys import platform
#if platform == 'win32':
# from multiprocessing.dummy import Process, Queue, Event, Lock
#else:
# from multiprocessing import Process, Queue, Event, Lock
from multiprocessing import Process, Event
from . import updater
from . import commander
from . import filter
from .. import options
def _update_loop(queue, updater):
while True:
queue.put(updater.receive())
def _command_loop(queue, commander):
latest_actions = None
while True:
while not queue.empty():
latest_actions = queue.get()
if latest_actions is not None:
commander.send(latest_actions)
class Interface(Process):
""" This class is used to manage a single interface channel
More specifically, this class will instantiate a set of updaters,
commanders and filters, and orchestrate them to interact with an
instace of a World.
"""
def __init__(self, world, updaters=[], commanders=[], filters=[], callback=lambda: None):
"""
The callback function will be called whenever an update arrives,
after the world is updated.
"""
super(Interface, self).__init__()
#self.updates = []
#self.commands = []
self.world = world
self.updaters = updaters
self.commanders = commanders
self.filters = filters
self.callback = callback
self._exit = Event()
def start(self):
#super(Interface, self).start()
for p in self.processes():
p.start()
def stop(self):
for p in self.processes():
p.stop()
#def run(self):
# while not self._exit.is_set():
# for up in self.updaters:
# if not up.queue.empty():
# uu = up.queue.get()
# for fi in reversed(self.filters):
# _uu = fi.filter_updates(uu)
# if _uu is not None:
# uu = _uu
# self.updates = uu
# for co in self.commanders:
# if self.actions is not None:
# co.send(self.actions)
# #co.send(actions)
def step(self):
#print "I'm stepping the interface."
# updates injection phase
for up in self.updaters:
if not up.queue.empty():
#uu = up.queue.get_nowait()
for _ in xrange(15):
uu = up.queue.get()
if up.queue.empty():
break
for fi in reversed(self.filters):
_uu = fi.filter_updates(uu)
if _uu is not None:
uu = _uu
for u in uu:
u.apply(self.world)
##with up.queue_lock:
## print 'Queue size: ', up.queue.qsize()
#while not up.queue.empty() and count < 7:
# uu = up.queue.get()
# for fi in reversed(self.filters):
# _uu = fi.filter_updates(uu)
# if _uu is not None:
# uu = _uu
# for u in uu:
# u.apply(self.world)
# count += 1
#if count > 0:
# self.callback()
# actions extraction phase
# TODO filtering
for co in self.commanders:
actions = []
for r in co.team:
if r.action is not None:
actions.append(r.action)
for fi in self.filters:
_actions = fi.filter_commands(actions)
if _actions is not None:
actions = _actions
#co.queue.put(actions)
co.send(actions)
def processes(self):
for up in self.updaters:
yield up
#for co in self.commanders:
# yield co
class TxInterface(Interface):
def __init__(self, world, filters=[], transmission_ipaddr='127.0.0.1', transmission_port=9050, **kwargs):
super(TxInterface, self).__init__(
world,
updaters=[updater.RealVisionUpdater(), updater.RefereeUpdater()],
commanders=[
commander.Tx2012Commander(world.blue_team, ipaddr=transmission_ipaddr, port=transmission_port, verbose=True),
commander.Tx2012Commander(world.yellow_team, ipaddr=transmission_ipaddr, port=transmission_port, verbose=True)
],
filters=filters + [filter.LowPass(), filter.Speed(), filter.Scale()],
**kwargs
)
class SimulationInterface(Interface):
def __init__(self, world, filters=[], **kwargs):
super(SimulationInterface, self).__init__(
world,
updaters=[updater.SimVisionUpdater(), updater.RefereeUpdater()],
commanders=[commander.SimCommander(world.blue_team), commander.SimCommander(world.yellow_team)],
filters=filters + [
filter.PositionLog(options.position_log_filename), #should be last, to have all data available
filter.Acceleration(),
filter.Speed(),
filter.CommandUpdateLog(options.cmdupd_filename),
filter.Kalman(),
filter.Noise(options.noise_var_x,options.noise_var_y,options.noise_var_angle),
filter.Scale(),
],
**kwargs
)
#def start()
|
Python
| 0
|
@@ -5023,24 +5023,25 @@
+#
filter.Posit
@@ -5380,24 +5380,25 @@
+#
filter.Noise
|
02a36c08caaec2c16a965c55a35b8378f2a7609b
|
add 1D cosmic-ray rejection after sky subtraction
|
py/desispec/scripts/procexp.py
|
py/desispec/scripts/procexp.py
|
"""
This script processes an exposure by applying fiberflat, sky subtraction,
spectro-photometric calibration depending on input.
"""
from desispec.io import read_frame, write_frame
from desispec.io import read_fiberflat
from desispec.io import read_sky
from desispec.io.fluxcalibration import read_flux_calibration
from desispec.fiberflat import apply_fiberflat
from desispec.sky import subtract_sky
from desispec.fluxcalibration import apply_flux_calibration
from desiutil.log import get_logger
from desispec.cosmics import reject_cosmic_rays_1d
import argparse
import sys
def parse(options=None):
parser = argparse.ArgumentParser(description="Apply fiberflat, sky subtraction and calibration.")
parser.add_argument('--infile', type = str, default = None, required=True,
help = 'path of DESI exposure frame fits file')
parser.add_argument('--fiberflat', type = str, default = None,
help = 'path of DESI fiberflat fits file')
parser.add_argument('--sky', type = str, default = None,
help = 'path of DESI sky fits file')
parser.add_argument('--calib', type = str, default = None,
help = 'path of DESI calibration fits file')
parser.add_argument('--outfile', type = str, default = None, required=True,
help = 'path of DESI sky fits file')
args = None
if options is None:
args = parser.parse_args()
else:
args = parser.parse_args(options)
return args
def main(args):
log = get_logger()
if (args.fiberflat is None) and (args.sky is None) and (args.calib is None):
log.critical('no --fiberflat, --sky, or --calib; nothing to do ?!?')
sys.exit(12)
frame = read_frame(args.infile)
# Reject cosmics
reject_cosmic_rays_1d(frame)
if args.fiberflat!=None :
log.info("apply fiberflat")
# read fiberflat
fiberflat = read_fiberflat(args.fiberflat)
# apply fiberflat to sky fibers
apply_fiberflat(frame, fiberflat)
if args.sky!=None :
log.info("subtract sky")
# read sky
skymodel=read_sky(args.sky)
# subtract sky
subtract_sky(frame, skymodel)
if args.calib!=None :
log.info("calibrate")
# read calibration
fluxcalib=read_flux_calibration(args.calib)
# apply calibration
apply_flux_calibration(frame, fluxcalib)
# save output
write_frame(args.outfile, frame, units='1e-17 erg/(s cm2 A)')
log.info("successfully wrote %s"%args.outfile)
|
Python
| 0.000017
|
@@ -2452,16 +2452,147 @@
calib)%0A%0A
+ # Reject cosmics one more time after sky subtraction to catch cosmics close to sky lines%0A reject_cosmic_rays_1d(frame)%0A %0A
%0A # s
|
84159dae072424b0cc8d457b9e64e7b2490f08df
|
Remove some redundant URL configs.
|
base/components/people/urls.py
|
base/components/people/urls.py
|
from django.conf.urls import patterns, url
from django.http import Http404
from django.views.generic.base import RedirectView
from multiurl import ContinueResolving, multiurl
from .views import (GroupBrowseView, GroupDetailView, GroupDiscographyView, GroupMembershipView,
IdolBrowseView, IdolDetailView, IdolDiscographyView, StaffBrowseView, StaffDetailView)
urlpatterns = patterns('',
# MultiURL allows us to unite all of the music under a simpler URL.
multiurl(
url(r'^(?P<slug>[-\w]+)/$', name='group-detail', view=GroupDetailView.as_view()),
url(r'^(?P<slug>[-\w]+)/$', name='idol-detail', view=IdolDetailView.as_view()),
# url('^music/(?P<slug>[-\w]+)/$', name='album-detail', view=AlbumDetailView.as_view()),
# url('^music/(?P<slug>[-\w]+)/$', name='single-detail', view=SingleDetailView.as_view()),
catch=(Http404, ContinueResolving)
),
url(r'^groups/browse/$', name='group-browse', view=GroupBrowseView.as_view()),
url(r'^groups/(?P<slug>[-\w]+)/discography/$', name='group-discography', view=GroupDiscographyView.as_view()),
url(r'^groups/(?P<slug>[-\w]+)/members/$', name='group-membership', view=GroupMembershipView.as_view()),
url(r'^groups/(?P<slug>[-\w]+)/$', name='group-detail', view=GroupDetailView.as_view()),
url(r'^groups/$', name='group-list', view=RedirectView.as_view(url='/groups/browse/')),
url(r'^idols/browse/$', name='idol-browse', view=IdolBrowseView.as_view()),
url(r'^idols/(?P<slug>[-\w]+)/discography/$', name='idol-discography', view=IdolDiscographyView.as_view()),
url(r'^idols/(?P<slug>[-\w]+)/$', name='idol-detail', view=IdolDetailView.as_view()),
url(r'^idols/$', name='idol-list', view=RedirectView.as_view(url='/idols/browse/')),
url(r'^staff/browse/$', name='staff-browse', view=StaffBrowseView.as_view()),
url(r'^staff/(?P<slug>[-\w]+)/$', name='staff-detail', view=StaffDetailView.as_view()),
url(r'^staff/$', name='staff-list', view=RedirectView.as_view(url='/staff/browse/'))
)
|
Python
| 0
|
@@ -655,1014 +655,298 @@
)),%0A
-%0A # url('%5Emusic/(?P%3Cslug%3E%5B-%5Cw%5D+)/$', name='album-detail', view=AlbumDetailView.as_view()),%0A # url('%5Emusic/(?P%3Cslug%3E%5B-%5Cw%5D+)/$', name='single-detail', view=SingleDetailView.as_view()),%0A catch=(Http404, ContinueResolving)%0A ),%0A%0A url(r'%5Egroups/browse/$', name='group-browse', view=GroupBrowseView.as_view()),%0A url(r'%5Egroups/(?P%3Cslug%3E%5B-%5Cw%5D+)/discography/$', name='group-discography', view=GroupDiscographyView.as_view()),%0A url(r'%5Egroups/(?P%3Cslug%3E%5B-%5Cw%5D+)/members/$', name='group-membership', view=GroupMembershipView.as_view()),%0A url(r'%5Egroups/(?P%3Cslug%3E%5B-%5Cw%5D+)/$', name='group-detail', view=GroupDetailView.as_view()),%0A url(r'%5Egroups/$', name='group-list', view=RedirectView.as_view(url='/groups/browse/')),%0A%0A url(r'%5Eidols/browse/$', name='idol-browse', view=IdolBrowseView.as_view()),%0A url(r'%5Eidols/(?P%3Cslug%3E%5B-%5Cw%5D+)/discography/$', name='idol-discography', view=IdolDiscographyView.as_view()),%0A url(r'%5Eidols/(?P%3Cslug%3E%5B-%5Cw%5D+)/$', name='idol-detail', view=IdolDetail
+ catch=(Http404, ContinueResolving)%0A ),%0A%0A url(r'%5Egroups/browse/$', name='group-browse', view=GroupBrowseView.as_view()),%0A url(r'%5Egroups/$', name='group-list', view=RedirectView.as_view(url='/groups/browse/')),%0A%0A url(r'%5Eidols/browse/$', name='idol-browse', view=IdolBrowse
View
|
f1c1e471cb6c3de23991301379425dceacebe27d
|
change to PST
|
events.py
|
events.py
|
#!/usr/bin/env python
import requests
import time
import math
import os
import tempfile
from yattag import Doc
outputdir = "./"
allshards = {
'us': {
1701: 'Seastone',
1702: 'Greybriar',
1704: 'Deepwood',
1706: 'Wolfsbane',
1707: 'Faeblight',
1708: 'Laethys',
1721: 'Hailol'
},
'eu': {
2702: 'Bloodiron',
2711: 'Brutwacht',
2714: 'Brisesol',
2721: 'Gelidra',
2722: 'Zaviel',
2741: 'Typhiria'
}
}
url = "https://web-api-us.riftgame.com/chatservice/zoneevent/list?shardId="
os.environ['TZ'] = 'GMT'
for dc in allshards:
# Construct a page at a time
doc, tag, text = Doc().tagtext()
with tag('html'):
with tag('head'):
doc.stag('meta', ('http-equiv', "Refresh"), ('content', 60))
doc.stag('meta', ('http-equiv', "Content-Type"), ('content', "text/html; charset=UTF-8"))
doc.stag('link', ('rel', "stylesheet"), ('type', "text/css"), ('href', "style.css"))
with tag('title'):
text('Rift Events')
with tag('body'):
with tag('h2'):
text('Rift Events - ', dc.upper())
# Links to other DCs
with tag('p'):
for otherdc in allshards:
if (otherdc != dc):
with tag('a', href = otherdc + ".html"):
text(otherdc.upper())
# Event table
with tag('table'):
with tag('thead'):
with tag('tr'):
for title in ['Shard', 'Zone', 'Event Name', 'Elapsed Time']:
with tag('th'):
text(title)
with tag('tbody'):
# Get each shard's events
for shardid in allshards[dc]:
r = requests.get("https://web-api-" + dc + ".riftgame.com/chatservice/zoneevent/list?shardId=" + str(shardid))
r.raise_for_status() # fail
data = r.json()["data"]
displayshard = allshards[dc][shardid]
for zone in data:
# An event is running in a zone, so add a table row
if "name" in zone:
with tag('tr'):
for display in [displayshard, zone['zone'], zone['name'], int( math.floor((time.time() - zone['started']) / 60) )]:
with tag('td'):
text(display)
# already printed the shard name, so clear it
displayshard = ""
with tag('p', klass = 'small'):
text(time.strftime("%x %X %Z"))
# Write page then move it over the old one
with tempfile.NamedTemporaryFile(delete=False) as outfile:
outfile.write(doc.getvalue().encode('utf8'))
os.chmod(outfile.name, 0644)
os.rename(outfile.name, outputdir + dc + ".html")
|
Python
| 0.000581
|
@@ -552,11 +552,27 @@
= '
-GMT
+America/Los_Angeles
'%0A%0Af
|
fc5b13f413713cacd147bbd29daac5df7f5bd2de
|
update notification sending tests
|
awx/main/tests/unit/test_tasks.py
|
awx/main/tests/unit/test_tasks.py
|
import pytest
from contextlib import contextmanager
from awx.main.models import (
UnifiedJob,
Notification,
)
from awx.main.tasks import (
send_notifications,
run_administrative_checks,
)
from awx.main.task_engine import TaskEnhancer
@contextmanager
def apply_patches(_patches):
[p.start() for p in _patches]
yield
[p.stop() for p in _patches]
def test_send_notifications_not_list():
with pytest.raises(TypeError):
send_notifications(None)
def test_send_notifications_job_id(mocker):
with mocker.patch('awx.main.models.UnifiedJob.objects.get'):
send_notifications([], job_id=1)
assert UnifiedJob.objects.get.called
assert UnifiedJob.objects.get.called_with(id=1)
def test_send_notifications_list(mocker):
patches = list()
mock_job = mocker.MagicMock(spec=UnifiedJob)
patches.append(mocker.patch('awx.main.models.UnifiedJob.objects.get', return_value=mock_job))
mock_notification = mocker.MagicMock(spec=Notification, subject="test", body={'hello': 'world'})
patches.append(mocker.patch('awx.main.models.Notification.objects.get', return_value=mock_notification))
with apply_patches(patches):
send_notifications([1,2], job_id=1)
assert Notification.objects.get.call_count == 2
assert mock_notification.status == "successful"
assert mock_notification.save.called
assert mock_job.notifications.add.called
assert mock_job.notifications.add.called_with(mock_notification)
@pytest.mark.parametrize("current_instances,call_count", [(91, 2), (89,1)])
def test_run_admin_checks_usage(mocker, current_instances, call_count):
patches = list()
patches.append(mocker.patch('awx.main.tasks.User'))
mock_te = mocker.Mock(spec=TaskEnhancer)
mock_te.validate_enhancements.return_value = {'instance_count': 100, 'current_instances': current_instances, 'date_warning': True}
patches.append(mocker.patch('awx.main.tasks.TaskEnhancer', return_value=mock_te))
mock_sm = mocker.Mock()
patches.append(mocker.patch('awx.main.tasks.send_mail', wraps=mock_sm))
with apply_patches(patches):
run_administrative_checks()
assert mock_sm.called
if call_count == 2:
assert '90%' in mock_sm.call_args_list[0][0][0]
else:
assert 'expire' in mock_sm.call_args_list[0][0][0]
|
Python
| 0
|
@@ -967,19 +967,21 @@
fication
+s
=
+%5B
mocker.M
@@ -1048,16 +1048,17 @@
world'%7D)
+%5D
%0A pat
@@ -1112,35 +1112,38 @@
ication.objects.
-get
+filter
', return_value=
@@ -1159,16 +1159,17 @@
fication
+s
))%0A%0A
@@ -1273,27 +1273,30 @@
ion.objects.
-get
+filter
.call_count
@@ -1298,17 +1298,17 @@
ount ==
-2
+1
%0A
@@ -1332,16 +1332,20 @@
fication
+s%5B0%5D
.status
@@ -1392,16 +1392,20 @@
fication
+s%5B0%5D
.save.ca
@@ -1513,16 +1513,17 @@
ed_with(
+*
mock_not
@@ -1531,16 +1531,17 @@
fication
+s
)%0A%0A%0A@pyt
|
25ff7901a495a140e4c8d0890fdc0746f54104b7
|
rename bundled assets files
|
eventviz/assets.py
|
eventviz/assets.py
|
# -*- coding: utf-8 -*-
from flask.ext.assets import Bundle, Environment
JS_ASSETS = [
'js/jquery-1.9.1.js',
'js/jquery.tablesorter.js',
'js/bootstrap.js'
]
JS_TIMELINE_ASSETS = [
'js/timeline.js',
'js/eventviz-timeline.js'
]
CSS_ASSETS = [
'css/bootstrap.css',
'css/eventviz.css'
]
CSS_TIMELINE_ASSETS = [
'css/timeline.css'
]
JS_MINIFIER = 'yui_js'
CSS_MINIFIER = 'yui_css'
def setup_assets(app):
assets = Environment(app)
js_all = Bundle(*JS_ASSETS, filters=JS_MINIFIER, output='js/eventviz.min.js')
assets.register('js_all', js_all)
js_timeline = Bundle(*JS_TIMELINE_ASSETS, filters=JS_MINIFIER, output='js/timeline.min.js')
assets.register('js_timeline', js_timeline)
css_all = Bundle(*CSS_ASSETS, filters=CSS_MINIFIER, output='css/eventviz.min.css')
assets.register('css_all', css_all)
css_timeline = Bundle(*CSS_TIMELINE_ASSETS, filters=CSS_MINIFIER, output='css/timeline.min.css')
assets.register('css_timeline', css_timeline)
|
Python
| 0.000001
|
@@ -527,24 +527,31 @@
'js/eventviz
+-bundle
.min.js')%0A
@@ -669,24 +669,31 @@
'js/timeline
+-bundle
.min.js')%0A
@@ -815,16 +815,23 @@
eventviz
+-bundle
.min.css
@@ -964,16 +964,23 @@
timeline
+-bundle
.min.css
|
61e4693988c5b89b4a82457181813e7a6e73403b
|
Fix slugify for use without validator
|
utils/text.py
|
utils/text.py
|
import codecs
from django.core import exceptions
from django.utils import text
import translitcodec
def slugify(model, field, value, validator):
orig_slug = slug = text.slugify(codecs.encode(value, 'translit/long'))[:45]
i = 0
while True:
try:
try:
validator(slug)
except exceptions.ValidationError:
pass
else:
model.objects.get(**{field: slug})
i += 1
slug = orig_slug + '-' + str(i)
except model.DoesNotExist:
return slug
|
Python
| 0.000002
|
@@ -94,16 +94,49 @@
tcodec%0A%0A
+def no_validator(arg):%0A pass%0A%0A
def slug
@@ -160,16 +160,29 @@
value,
+validator=no_
validato
|
75fbe0578ca831b0a6802f0f01c0d76b076153b3
|
Update item tool docs
|
gaphas/tool/itemtool.py
|
gaphas/tool/itemtool.py
|
import logging
from typing import Optional, Tuple, Union
from gi.repository import Gdk, Gtk
from typing_extensions import Protocol
from gaphas.aspect import HandleMove, Move
from gaphas.canvas import ancestors
from gaphas.connector import Handle
from gaphas.geometry import distance_point_point_fast
from gaphas.item import Item
from gaphas.types import Pos
from gaphas.view import GtkView
log = logging.getLogger(__name__)
class MoveType(Protocol):
def __init__(self, item: Item, view: GtkView):
...
def start_move(self, pos: Pos):
...
def move(self, pos: Pos):
...
def stop_move(self, pos: Pos):
...
def item_tool(view: GtkView):
"""Handle item movement and movement of handles."""
gesture = Gtk.GestureDrag.new(view)
drag_state = DragState()
gesture.connect("drag-begin", on_drag_begin, drag_state)
gesture.connect("drag-update", on_drag_update, drag_state)
gesture.connect("drag-end", on_drag_end, drag_state)
return gesture
class DragState:
def __init__(self):
self.moving = set()
def on_drag_begin(gesture, start_x, start_y, drag_state):
view = gesture.get_widget()
selection = view.selection
event = gesture.get_last_event(None)
modifiers = event.get_state()[1]
item, handle = find_item_and_handle_at_point(view, (start_x, start_y))
# Deselect all items unless CTRL or SHIFT is pressed
# or the item is already selected.
if not (
modifiers & (Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)
or item in selection.selected_items
):
selection.unselect_all()
if not item:
gesture.set_state(Gtk.EventSequenceState.DENIED)
return
if (
not handle
and item in selection.selected_items
and modifiers & Gdk.ModifierType.CONTROL_MASK
):
selection.unselect_item(item)
gesture.set_state(Gtk.EventSequenceState.DENIED)
return
selection.set_focused_item(item)
gesture.set_state(Gtk.EventSequenceState.CLAIMED)
if handle:
drag_state.moving = {HandleMove(item, handle, view)}
else:
drag_state.moving = set(moving_items(view))
for moving in drag_state.moving:
moving.start_move((start_x, start_y))
def find_item_and_handle_at_point(view: GtkView, pos: Pos):
item, handle = handle_at_point(view, pos)
return item or item_at_point(view, pos), handle
def moving_items(view):
"""Filter the items that should eventually be moved.
Returns Move aspects for the items.
"""
selected_items = set(view.selection.selected_items)
for item in selected_items:
# Do not move subitems of selected items
if not set(ancestors(view.model, item)).intersection(selected_items):
yield Move(item, view)
def on_drag_update(gesture, offset_x, offset_y, drag_state):
_, x, y = gesture.get_start_point()
for moving in drag_state.moving:
moving.move((x + offset_x, y + offset_y))
def on_drag_end(gesture, offset_x, offset_y, drag_state):
_, x, y = gesture.get_start_point()
for moving in drag_state.moving:
moving.stop_move((x + offset_x, y + offset_y))
drag_state.moving = set()
def item_at_point(view: GtkView, pos: Pos, selected=True) -> Optional[Item]:
"""Return the topmost item located at ``pos`` (x, y).
Parameters:
- view: a view
- pos: Position, in view coordinates
- selected: if False returns first non-selected item
"""
item: Item
for item in reversed(list(view.get_items_in_rectangle((pos[0], pos[1], 1, 1)))):
if not selected and item in view.selection.selected_items:
continue # skip selected items
v2i = view.get_matrix_v2i(item)
ix, iy = v2i.transform_point(*pos)
item_distance = item.point(ix, iy)
if item_distance is None:
log.warning("Item distance is None for %s", item)
continue
if item_distance < 0.5:
return item
return None
def handle_at_point(
view: GtkView, pos: Pos, distance=6
) -> Union[Tuple[Item, Handle], Tuple[None, None]]:
"""Look for a handle at ``pos`` and return the tuple (item, handle)."""
def find(item):
"""Find item's handle at pos."""
v2i = view.get_matrix_v2i(item)
d = distance_point_point_fast(v2i.transform_distance(0, distance))
x, y = v2i.transform_point(*pos)
for h in item.handles():
if not h.movable:
continue
hx, hy = h.pos
if -d < (hx - x) < d and -d < (hy - y) < d:
return h
selection = view.selection
# The focused item is the preferred item for handle grabbing
if selection.focused_item:
h = find(selection.focused_item)
if h:
return selection.focused_item, h
# then try hovered item
if selection.hovered_item:
h = find(selection.hovered_item)
if h:
return selection.hovered_item, h
# Last try all items, checking the bounding box first
x, y = pos
items = reversed(
list(
view.get_items_in_rectangle(
(x - distance, y - distance, distance * 2, distance * 2)
)
)
)
for item in items:
h = find(item)
if h:
return item, h
return None, None
|
Python
| 0
|
@@ -3436,16 +3436,35 @@
osition,
+ a tuple %60%60(x, y)%60%60
in view
|
728c1e57b37e51306eeae59d11792444f7798da5
|
Change Events.default to use @propery access
|
events.py
|
events.py
|
EVENT_LEVELS = BLOCK, CONSUME, NOTIFY = range(3)
# events: dict of (event_name:handler_levels)
# handler_levels: 3-tuple of sets of functions
class Events(object):
def __init__(self, default = NOTIFY):
self.setdefault(default)
self.events = {}
def setdefault(self, value = NOTIFY):
if not hasattr(self, 'default'):
self.default = [value]
else:
self.default[0] = value
def getdefault(self):
return self.default[0]
def _subscribe(self, func, name, level):
self.events[name][level].add(func)
# def subscribe(self, func, name = None, level = None):
def subscribe(self, *args):
args = list(args)
func = args.pop(0) if len(args) and hasattr(args[0], "__call__") else None
cname = args.pop(0) if len(args) else None
level = args.pop(0) if len(args) and args[0] in EVENT_LEVELS else self.getdefault()
def sub(func):
name = cname or func.__name__
if not self.events.has_key(name):
self.events.setdefault(name, (set(), set(), set()))
self._subscribe(func, name, level)
return func
return sub(func) if func else sub
def _unsubscribe(self, func, name, level):
self.events[name][level].discard(func)
if not any(self.events[name]):
self.events.pop(name)
def unsubscribe(self, func, name = None, level = None):
if level not in EVENT_LEVELS:
level = self.getdefault()
if self.events.has_key(name):
self._unsubscribe(func, name, level)
def invoke(self, name, *args, **kwargs):
max_level = kwargs.get('max_level', NOTIFY)
if not self.events.has_key(name):
return None
event = self.events[name]
for level in EVENT_LEVELS:
if level > max_level:
break
for func in event[level]:
# todo: wrap in try block
result = func(*args)
if level < NOTIFY and result:
return result
return None
def recorder(self):
class Recorder(Events):
def __init__(self, existing):
# all properties are objects, so when they are copied
# only references are made; so changes to one apply to all
self.events = existing.events
self.default = existing.default
self.recorded = set()
def _subscribe(self, func, name, level):
self.recorded.add((func, name, level))
Events._subscribe(self, func, name, level)
def _unsubscribe(self, func, name, level):
self.recorded.discard((func, name, level))
Events._unsubscribe(self, func, name, level)
def unsubscribe_all(self):
for args in self.recorded.copy():
self._unsubscribe(*args)
return Recorder(self)
|
Python
| 0
|
@@ -228,27 +228,25 @@
elf.
-set
default
-(
+ =
default
-)
%0A
@@ -272,24 +272,38 @@
%7B%7D%0A %0A
+ @property%0A
def
setdefau
@@ -294,19 +294,16 @@
def
-set
default(
@@ -310,41 +310,45 @@
self
-, value = NOTIFY):%0A if not
+):%0A return self._default%5B0%5D if
has
@@ -362,54 +362,86 @@
lf,
-'
+%22_
default
-'):
+%22) else NOTIFY
%0A
+%0A
- self.default = %5B
+@default.setter%0A def default(self,
value
-%5D
+):
%0A
@@ -445,20 +445,48 @@
-else
+if not hasattr(self, %22_default%22)
:%0A
@@ -500,56 +500,60 @@
elf.
+_
default
-%5B0%5D = value
+ = %5BNOTIFY%5D
%0A
-%0A
-def getdefault(self)
+if value in EVENT_LEVELS
:%0A
@@ -558,28 +558,26 @@
-return
+
self.
+_
default%5B
@@ -578,16 +578,24 @@
fault%5B0%5D
+ = value
%0A %0A
@@ -1012,36 +1012,31 @@
S else self.
-get
default
-()
%0A def
@@ -1620,20 +1620,15 @@
elf.
-get
default
-()
%0A
@@ -2671,63 +2671,8 @@
l):%0A
- self.recorded.add((func, name, level))%0A
@@ -2718,32 +2718,87 @@
c, name, level)%0A
+ self.recorded.add((func, name, level))%0A
%0A
@@ -2869,31 +2869,34 @@
-self.recorded.discard((
+Events._unsubscribe(self,
func
@@ -2901,33 +2901,32 @@
nc, name, level)
-)
%0A
@@ -2930,34 +2930,31 @@
-Events._unsubscribe(self,
+self.recorded.discard((
func
@@ -2959,32 +2959,33 @@
nc, name, level)
+)
%0A %0A
|
f2ffb339714ba848ea48008f20fa7adc71609b7f
|
add --update command to pr management util
|
people_admin/management/commands/create_pulls.py
|
people_admin/management/commands/create_pulls.py
|
from django.core.management.base import BaseCommand
from people_admin.models import DeltaSet, PullStatus
from people_admin.git import delta_set_to_pr
class Command(BaseCommand):
help = "create pull requests from deltas"
def add_arguments(self, parser):
parser.add_argument("--list", default=False, action="store_true")
parser.add_argument("--delta")
def handle(self, *args, **options):
nothing = True
if options["list"]:
nothing = False
to_create = DeltaSet.objects.filter(
pr_status=PullStatus.NOT_CREATED
).order_by("id")
for ds in to_create:
print(f"{ds.id} | {ds.name} | {ds.created_by}")
if options["delta"]:
nothing = False
ds = DeltaSet.objects.get(
pk=options["delta"], pr_status=PullStatus.NOT_CREATED
)
print(f"creating {ds.id} | {ds.name} | {ds.created_by}")
ds.pr_url = delta_set_to_pr(ds)
ds.pr_status = PullStatus.CREATED
ds.save()
if nothing:
print("must either pass --list or --delta parameters")
|
Python
| 0
|
@@ -142,17 +142,32 @@
et_to_pr
+, get_pr_status
%0A
-
%0A%0Aclass
@@ -384,16 +384,92 @@
-delta%22)
+%0A parser.add_argument(%22--update%22, default=False, action=%22store_true%22)
%0A%0A de
@@ -1166,16 +1166,520 @@
.save()%0A
+ if options%5B%22update%22%5D:%0A nothing = False%0A for ds in DeltaSet.objects.filter(pr_status=PullStatus.CREATED):%0A pr_id = int(ds.pr_url.split(%22/%22)%5B-1%5D)%0A new_status = get_pr_status(pr_id)%0A if new_status != ds.pr_status:%0A print(%0A f%22Updating %7Bds.id%7D %7C %7Bds.name%7D %7C %7Bds.get_pr_status%7D =%3E %7Bnew_status%7D%22%0A )%0A ds.pr_status = new_status%0A ds.save()%0A
|
88b01b80ce917fcc8fc38979b96893b9ba46c5cc
|
Migrate everlights light to color_mode (#69182)
|
homeassistant/components/everlights/light.py
|
homeassistant/components/everlights/light.py
|
"""Support for EverLights lights."""
from __future__ import annotations
from datetime import timedelta
import logging
import pyeverlights
import voluptuous as vol
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_EFFECT,
ATTR_HS_COLOR,
PLATFORM_SCHEMA,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
SUPPORT_EFFECT,
LightEntity,
)
from homeassistant.const import CONF_HOSTS
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import PlatformNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
import homeassistant.util.color as color_util
_LOGGER = logging.getLogger(__name__)
SUPPORT_EVERLIGHTS = SUPPORT_EFFECT | SUPPORT_BRIGHTNESS | SUPPORT_COLOR
SCAN_INTERVAL = timedelta(minutes=1)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_HOSTS): vol.All(cv.ensure_list, [cv.string])}
)
def color_rgb_to_int(red: int, green: int, blue: int) -> int:
"""Return a RGB color as an integer."""
return red * 256 * 256 + green * 256 + blue
def color_int_to_rgb(value: int) -> tuple[int, int, int]:
"""Return an RGB tuple from an integer."""
return (value >> 16, (value >> 8) & 0xFF, value & 0xFF)
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the EverLights lights from configuration.yaml."""
lights = []
for ipaddr in config[CONF_HOSTS]:
api = pyeverlights.EverLights(ipaddr, async_get_clientsession(hass))
try:
status = await api.get_status()
effects = await api.get_all_patterns()
except pyeverlights.ConnectionError as err:
raise PlatformNotReady from err
else:
lights.append(EverLightsLight(api, pyeverlights.ZONE_1, status, effects))
lights.append(EverLightsLight(api, pyeverlights.ZONE_2, status, effects))
async_add_entities(lights)
class EverLightsLight(LightEntity):
"""Representation of a Flux light."""
def __init__(self, api, channel, status, effects):
"""Initialize the light."""
self._api = api
self._channel = channel
self._status = status
self._effects = effects
self._mac = status["mac"]
self._error_reported = False
self._hs_color = [255, 255]
self._brightness = 255
self._effect = None
self._available = True
@property
def unique_id(self) -> str:
"""Return a unique ID."""
return f"{self._mac}-{self._channel}"
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._available
@property
def name(self):
"""Return the name of the device."""
return f"EverLights {self._mac} Zone {self._channel}"
@property
def is_on(self):
"""Return true if device is on."""
return self._status[f"ch{self._channel}Active"] == 1
@property
def brightness(self):
"""Return the brightness of this light between 0..255."""
return self._brightness
@property
def hs_color(self):
"""Return the color property."""
return self._hs_color
@property
def effect(self):
"""Return the effect property."""
return self._effect
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_EVERLIGHTS
@property
def effect_list(self):
"""Return the list of supported effects."""
return self._effects
async def async_turn_on(self, **kwargs):
"""Turn the light on."""
hs_color = kwargs.get(ATTR_HS_COLOR, self._hs_color)
brightness = kwargs.get(ATTR_BRIGHTNESS, self._brightness)
effect = kwargs.get(ATTR_EFFECT)
if effect is not None:
colors = await self._api.set_pattern_by_id(self._channel, effect)
rgb = color_int_to_rgb(colors[0])
hsv = color_util.color_RGB_to_hsv(*rgb)
hs_color = hsv[:2]
brightness = hsv[2] / 100 * 255
else:
rgb = color_util.color_hsv_to_RGB(*hs_color, brightness / 255 * 100)
colors = [color_rgb_to_int(*rgb)]
await self._api.set_pattern(self._channel, colors)
self._hs_color = hs_color
self._brightness = brightness
self._effect = effect
async def async_turn_off(self, **kwargs):
"""Turn the light off."""
await self._api.clear_pattern(self._channel)
async def async_update(self):
"""Synchronize state with control box."""
try:
self._status = await self._api.get_status()
except pyeverlights.ConnectionError:
if self._available:
_LOGGER.warning("EverLights control box connection lost")
self._available = False
else:
if not self._available:
_LOGGER.warning("EverLights control box connection restored")
self._available = True
|
Python
| 0
|
@@ -269,66 +269,42 @@
-PLATFORM_SCHEMA,%0A SUPPORT_BRIGHTNESS,%0A SUPPORT_COLOR
+COLOR_MODE_HS,%0A PLATFORM_SCHEMA
,%0A
@@ -839,82 +839,8 @@
_)%0A%0A
-SUPPORT_EVERLIGHTS = SUPPORT_EFFECT %7C SUPPORT_BRIGHTNESS %7C SUPPORT_COLOR%0A%0A
SCAN
@@ -2204,16 +2204,150 @@
ht.%22%22%22%0A%0A
+ _attr_color_mode = COLOR_MODE_HS%0A _attr_supported_color_modes = %7BCOLOR_MODE_HS%7D%0A _attr_supported_features = SUPPORT_EFFECT%0A%0A
def
@@ -3602,32 +3602,32 @@
ct property.%22%22%22%0A
+
return s
@@ -3643,130 +3643,8 @@
ct%0A%0A
- @property%0A def supported_features(self):%0A %22%22%22Flag supported features.%22%22%22%0A return SUPPORT_EVERLIGHTS%0A%0A
|
efef8389f2536179ebea189fed33c3ca446e68ac
|
Refactor indicators
|
pyFxTrader/utils/indicators.py
|
pyFxTrader/utils/indicators.py
|
# -*- coding: utf-8 -*-
import numpy as np
def moving_average(x, n, type='simple'):
"""
compute an n period moving average.
type is 'simple' | 'exponential'
"""
x = np.asarray(x)
if type == 'simple':
weights = np.ones(n)
else:
weights = np.exp(np.linspace(-1., 0., n))
weights /= weights.sum()
a = np.convolve(x, weights, mode='full')[:len(x)]
a[:n] = a[n]
return a
def relative_strength(prices, n=14):
"""
compute the n period relative strength indicator
http://stockcharts.com/school/doku.php?id=chart_school:glossary_r#relativestrengthindex
http://www.investopedia.com/terms/r/rsi.asp
"""
deltas = np.diff(prices)
seed = deltas[:n + 1]
up = seed[seed >= 0].sum() / n
down = -seed[seed < 0].sum() / n
rs = up / down
rsi = np.zeros_like(prices)
rsi[:n] = 100. - 100. / (1. + rs)
for i in range(n, len(prices)):
delta = deltas[i - 1] # cause the diff is 1 shorter
if delta > 0:
upval = delta
downval = 0.
else:
upval = 0.
downval = -delta
up = (up * (n - 1) + upval) / n
down = (down * (n - 1) + downval) / n
rs = up / down
rsi[i] = 100. - 100. / (1. + rs)
return rsi
def moving_average_convergence(x, nslow=26, nfast=12):
"""
compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg'
return value is emaslow, emafast, macd which are len(x) arrays
"""
emaslow = moving_average(x, nslow, type='exponential')
emafast = moving_average(x, nfast, type='exponential')
return emaslow, emafast, emafast - emaslow
|
Python
| 0.000001
|
@@ -128,17 +128,16 @@
verage.%0A
-%0A
type
@@ -165,17 +165,16 @@
ential'%0A
-%0A
%22%22%22%0A
@@ -1349,16 +1349,39 @@
nfast=12
+, nsign=9, simple=False
):%0A %22
@@ -1460,16 +1460,20 @@
fast and
+%0A
slow ex
@@ -1502,90 +1502,53 @@
-return value is emaslow, emafast, macd which are len(x) arrays%0A %22%22%22
+%22%22%22%0A%0A macd_dict = %7B%7D
%0A
-e
ma
-slow
+cd_dict%5B'fast'%5D
= m
@@ -1565,20 +1565,20 @@
age(x, n
-slow
+fast
, type='
@@ -1595,23 +1595,33 @@
l')%0A
-e
ma
-fast
+cd_dict%5B'slow'%5D
= movin
@@ -1626,36 +1626,36 @@
ing_average(x, n
-fast
+slow
, type='exponent
@@ -1668,47 +1668,276 @@
-return emaslow, emafast, emafast - emaslow
+macd_dict%5B'macd'%5D = map(lambda f, s: round(f - s, 5), macd_dict%5B'fast'%5D,%0A macd_dict%5B'slow'%5D)%0A macd_dict%5B'sign'%5D = moving_average(macd_dict%5B'macd'%5D, nsign)%0A if not simple:%0A return macd_dict%0A else:%0A return macd_dict%5B'macd'%5D
%0A
|
2eef6612a046b2982327a36ffe03beb4a0aa54f3
|
Remove dependancies on lmi-sdp and sympy for is_passive.
|
control/passivity.py
|
control/passivity.py
|
'''
Author: Mark Yeatman
Date: May 15, 2022
'''
from . import statesp as ss
from sympy import symbols, Matrix, symarray
from lmi_sdp import LMI_NSD, to_cvxopt
from cvxopt import solvers
import numpy as np
def is_passive(sys):
'''
Indicates if a linear time invarient system is passive
Constructs a linear matrix inequality and a feasibility optimization
such that is a solution exists, the system is passive.
The source for the algorithm is:
McCourt, Michael J., and Panos J. Antsaklis. "Demonstrating passivity and dissipativity using computational methods." ISIS 8 (2013).
'''
A = sys.A
B = sys.B
C = sys.C
D = sys.D
P = Matrix(symarray('p', A.shape))
# enforce symmetry in P
size = A.shape[0]
for i in range(0, size):
for j in range(0, size):
P[i, j] = P[j, i]
# construct matrix for storage function x'*V*x
V = Matrix.vstack(
Matrix.hstack(A.T * P + P*A, P*B - C.T),
Matrix.hstack(B.T*P - C, Matrix(-D - D.T))
)
# construct LMI, convert to form for feasibility solver
LMI_passivty = LMI_NSD(V, 0*V)
min_obj = 0 * symbols("x")
variables = V.free_symbols
solvers.options['show_progress'] = False
c, Gs, hs = to_cvxopt(min_obj, LMI_passivty, variables)
# crunch feasibility solution
sol = solvers.sdp(c, Gs=Gs, hs=hs)
return (sol["x"] is not None)
|
Python
| 0
|
@@ -76,137 +76,47 @@
ss%0A
-from sympy import symbols, Matrix, symarray%0Afrom lmi_sdp import LMI_NSD, to_cvxopt%0Afrom cvxopt import solvers%0A%0Aimport numpy as np
+import numpy as np%0Aimport cvxopt as cvx
%0A%0A%0Ad
@@ -585,76 +585,241 @@
-P = Matrix(symarray('p', A.shape))%0A%0A # enforce symmetry in P%0A
+def make_LMI_matrix(P):%0A V = np.vstack((%0A np.hstack((A.T @ P + P@A, P@B)),%0A np.hstack((B.T@P, np.zeros_like(D))))%0A )%0A return V%0A%0A P = np.zeros_like(A)%0A matrix_list = %5B%5D%0A state_space_
size
@@ -846,32 +846,44 @@
r i in range(0,
+state_space_
size):%0A f
@@ -899,16 +899,28 @@
ange(0,
+state_space_
size):%0A
@@ -934,100 +934,242 @@
-P%5Bi, j%5D = P%5Bj, i%5D%0A%0A # construct matrix for storage function x'*V*x%0A V = Matrix
+if j %3C= i:%0A P = P*0.0%0A P%5Bi, j%5D = 1.0%0A P%5Bj, i%5D = 1.0%0A matrix_list.append(make_LMI_matrix(P).flatten())%0A%0A coefficents = np.vstack(matrix_list).T%0A%0A constants = -np
.vstack(
%0A
@@ -1164,16 +1164,17 @@
.vstack(
+(
%0A
@@ -1174,30 +1174,26 @@
-Matrix
+np
.hstack(
A.T * P
@@ -1188,33 +1188,35 @@
ack(
-A.T * P + P*A, P*B
+(np.zeros_like(A),
- C.T)
+)
,%0A
@@ -1225,22 +1225,18 @@
-Matrix
+np
.hstack(
B.T*
@@ -1235,26 +1235,14 @@
ack(
-B.T*P - C, Matrix(
+(- C,
-D -
@@ -1247,16 +1247,17 @@
- D.T))
+)
%0A )%0A%0A
@@ -1264,264 +1264,150 @@
-# construct LMI, convert to form for feasibility solver%0A LMI_passivty = LMI_NSD(V, 0*V)%0A min_obj = 0 * symbols(%22x%22)%0A variables = V.free_symbols%0A solvers.options%5B'show_progress'%5D = False%0A c, Gs, hs = to_cvxopt(min_obj, LMI_passivty, variables
+number_of_opt_vars = int(%0A (state_space_size**2-state_space_size)/2 + state_space_size)%0A c = cvx.matrix(0.0, (number_of_opt_vars, 1)
)%0A%0A
@@ -1449,16 +1449,20 @@
sol =
+cvx.
solvers.
@@ -1471,21 +1471,117 @@
p(c,
- Gs=Gs, hs=hs
+%0A Gs=%5Bcvx.matrix(coefficents)%5D,%0A hs=%5Bcvx.matrix(constants)%5D
)%0A%0A
|
6fde5b74509e11021d976860502a9a15f63201b8
|
fix bug of view.file_name() is None when execute anonymous
|
events.py
|
events.py
|
import sublime
import sublime_plugin
import os
import time
from . import context
from .salesforce import util
class SFDCEventListener(sublime_plugin.EventListener):
def on_new_async(self, view):
"""
1. Eveytime when you open a new view, default syntax is Apex
2. Set Status with current default project
"""
view.set_syntax_file("Packages/SublimeApex/syntaxes/Apex.tmLanguage")
self.display_active_project(view)
def on_load_async(self, view):
"""
1. Set Status with current default project
"""
self.display_active_project(view)
def display_active_project(self, view):
toolingapi_settings = context.get_toolingapi_settings()
display_message = "Default Project ▄︻┻═┳一 " + toolingapi_settings["default_project_name"]
view.set_status('default_project', display_message)
def on_modified_async(self, view):
"""
Every time when you modified the context, just hide the console,
you can close it in sublime settings
"""
toolingapi_settings = context.get_toolingapi_settings()
# If it is not SFDC Component, just return
component_type = util.get_component_type(view.file_name())
if component_type not in toolingapi_settings["component_types"]: return
# If functionality is close, just return
if not toolingapi_settings["hidden_console_on_modify"]: return
# Hidden Console
sublime.active_window().run_command("hide_panel",
{"panel": "console", "toggle": False})
def on_post_save_async(self, view):
"""
Every time when you save your ApexPage, ApexTrigger, ApexClass, ApexComponent,
this class will make a copy with the time_stamp in the history path of current project
"""
settings = context.get_toolingapi_settings()
# Check whether need to keep history
if not settings["keep_local_change_history"]: return
# Get current file name and Read file content
file_name = view.file_name()
try:
body = open(file_name, encoding="utf-8").read()
except:
body = open(file_name, "rb").read()
# Get component_name amd component_type
component_name = util.get_component_name(file_name)
component_type = util.get_component_type(file_name)
# If this file is not ApexTrigger, ApexComponent,
# ApexPage or ApexClass, just return
if component_type not in settings["component_types"]:
return
# Get toolingapi settings
toolingapi_settings = context.get_toolingapi_settings()
# Get component extension
component_extension = toolingapi_settings[component_type]["extension"]
# Get Workspace, if not exist, make it
workspace = toolingapi_settings["workspace"] + "/history/" + component_type
if not os.path.exists(workspace):
os.makedirs(workspace)
# Backup current file
time_stamp = time.strftime("%Y-%m-%d-%H-%M", time.localtime())
fp = open(workspace + "/" + component_name + "-" +\
time_stamp + component_extension, "w")
fp.write(body)
fp.close()
|
Python
| 0.99976
|
@@ -1171,32 +1171,76 @@
nt, just return%0A
+ if view.file_name() == None: return%0A
componen
|
7252c12fa39ac1a4007aaf46cab4105540fc0bb4
|
Fix bug in pack/unpack mismatch accounting for padding. Unit test now work
|
vectortile/TypedMatrix.py
|
vectortile/TypedMatrix.py
|
"""
TypedMatrix.py - read/write TypedMatrix format
"""
magic = 'tmtx' # Must be four bytes long!
version = 2
import StringIO
import struct
import json
import calendar
from datetime import datetime
# Header Structure
# {
# length: count of rows of data
# version: format version
# cols: array of column definitions
# [{}
# ]
# }
typemap = {
int: 'Float32',
float: 'Float32',
datetime: 'Float32',
}
typeformatmap = {
'Float32': 'f',
}
typedefaultmap = {
'Float32': 0.0,
}
def get_columns(data):
"""
Gets the column definitions implicit in a dict or list of dicts.
If any field which has a datatype that is not in typemap, thows TypeException
"""
# make data iterable
if type(data) is dict:
data = [data]
cols = {}
for i, d in enumerate(data):
for key, value in d.iteritems():
t = type(value)
if t not in typemap:
raise TypeError ('TypedMatrix: "%s" is not a supported type in field "%s"' % (type(value), key))
if key not in cols:
cols[key] = {'name': key, 'type': typemap[t]}
cols = cols.values()
cols.sort(lambda a, b: cmp(a['name'], b['name']))
return cols
def _datetime2timestamp(dt):
return calendar.timegm(dt.utctimetuple()) * 1000.0
def conv(data, t, default):
if 'Float32' == t:
if type(data) is datetime:
fn = _datetime2timestamp
else:
fn = float
else:
assert False, 'Unknown conversion type %s' % t
# noinspection PyBroadException
try:
return fn(data)
except:
return default
def row_fmt(columns):
return '<' + ''.join(typeformatmap[col['type']] for col in columns)
def pack(data, extra_header_fields=None, columns=None, orientation='rowwise'):
"""
Pack a dict or list of dicts into a TypedMatrix binary packed string
If a list of columns is not given, the columns are derived from the data using get_columns()
extra_header_fields can supply an optional dict with additional fields to be included in the packed header
orientation can be 'rowwise' or 'columnwise'. For row-wise orientation, the typedmatrix will stored as a list of rows.
for column-wise oreintation it is stored as a list of columns.
"""
# make data iterable
if type(data) is dict:
data = [data]
if extra_header_fields:
header = dict(extra_header_fields)
else:
header = dict()
header['length'] = len(data)
if not columns:
columns = get_columns(data)
header['cols'] = columns
if 'colsByName' in header:
colsByName = header.pop("colsByName")
for col in header['cols']:
if col['name'] in colsByName:
col.update(colsByName[col['name']])
header['version'] = version
if orientation is None:
raise ValueError ('TypedMatrix: unknown orientation %s' % orientation)
header['orientation'] = orientation
f = StringIO.StringIO()
headerstr = json.dumps(header)
headerlen = len(headerstr)
paddinglen = (4 - headerlen % 4) % 4
# write "magic" file format token at the start
f.write(struct.pack('<%sc' % len(magic), *magic))
f.write(struct.pack("<i", headerlen))
f.write(headerstr)
f.write(" " * paddinglen)
colspecs = [{'name': col['name'], 'type': col['type'], 'default': typedefaultmap[col['type']]} for col in columns]
if orientation == 'rowwise':
for d in data:
f.write(struct.pack(
row_fmt(columns),
*[conv(d[colspec['name']], colspec['type'], colspec['default'])
for colspec in colspecs]))
else:
for colspec in colspecs:
f.write(struct.pack(
'<%s%s' % (len(data),typeformatmap[colspec['type']]),
*[conv(d[colspec['name']], colspec['type'], colspec['default'])
for d in data]))
return f.getvalue()
def _struct_read (f, t, n=1):
fmt = '<%s%s' % (n, t)
result = struct.unpack(fmt, f.read(struct.calcsize(fmt)))
if n == 1:
return result[0]
return result
def unpack(packed_str):
"""
Unpack a binary packed string containing a TypedMatrix. Returns a tuple of header and data
header is a dict and data is a list of dicts
"""
f = StringIO.StringIO(packed_str)
# read "magic" file format token
token = ''.join(_struct_read(f, 'c', len(magic)))
assert(token == magic)
header_len = _struct_read(f,'i')
header = json.loads(f.read(header_len))
assert (header['version'] == version) # only supports one version right now
if header['orientation'] == 'rowwise':
fmt = row_fmt(header['cols'])
data = []
col_names = [col['name'] for col in header['cols']]
for i in range(0, header['length']):
data.append(dict(zip(col_names, struct.unpack(fmt, f.read(struct.calcsize(fmt))))))
elif header['orientation'] == 'columnwise':
col_data = []
col_names = [col['name'] for col in header['cols']]
length = header['length']
for col in header['cols']:
col_data.append(_struct_read(f, typeformatmap[col['type']], length))
col_indexes = range(0, len(col_names))
if length > 1:
data = [dict(zip(col_names, [col_data[c][i] for c in col_indexes])) for i in xrange(0, length)]
elif length == 1:
data = [dict(zip(col_names, [col_data[c] for c in col_indexes]))]
else:
data = []
else:
raise Exception("Unsupported orientation")
return header, data
def get_packed_float_value(f):
"""
Get a float value that has been packed using Float32. This is useful to get the actual precision used
in the packed array for a float column, since Float32 precision is limited to about 9 digits and
there is no native Float32 in python.
"""
return struct.unpack('<f', struct.pack("<f", float(f)))[0]
def get_utc_timestamp(dt=datetime.now()):
"""
Create a timestamp in milliseconds as a Float32 from a datetime
"""
return get_packed_float_value(_datetime2timestamp(dt))
|
Python
| 0
|
@@ -3066,75 +3066,83 @@
-headerlen = len(headerstr)%0A paddinglen = (4 - headerlen %25 4) %25 4
+paddinglen = (4 - len(header) %25 4) %25 4%0A headerstr += (%22 %22 * paddinglen)%0A
%0A%0A
@@ -3278,17 +3278,22 @@
i%22,
+len(
header
-len
+str)
))%0A
@@ -3317,38 +3317,8 @@
str)
-%0A f.write(%22 %22 * paddinglen)
%0A%0A
|
6a4b14980d4afc5290c9b2bdf8301d045a1525e2
|
add old command
|
paulla.ircbot/src/paulla/ircbot/plugins/Urls.py
|
paulla.ircbot/src/paulla/ircbot/plugins/Urls.py
|
import sqlite3
from os.path import exists, dirname, expanduser
import re
from urllib.parse import urlparse
from os import makedirs
import irc3
import requests
from bs4 import BeautifulSoup
@irc3.plugin
class Urls:
"""
A plugin for print Url title
"""
def __init__(self, bot):
self.bot = bot
self.log = self.bot.log
if 'paulla.ircbot.plugins.Urls' in self.bot.config\
and 'db' in self.bot.config['paulla.ircbot.plugins.Urls']\
and self.bot.config['paulla.ircbot.plugins.Urls']['db']:
db = self.bot.config['paulla.ircbot.plugins.Urls']['db']
else:
db = '~/.irc3/Urls.db'
if '~' in db:
db = expanduser(db)
if not exists(db):
if not exists(dirname(db)):
makedirs(dirname(db))
open(db, 'a').close()
self.conn = sqlite3.connect(db)
cur = self.conn.cursor()
cur.execute('''create table if not exists url
(id_url integer primary key,
value text,
title text,
dt_inserted datetime,
nick text
)''')
cur.execute('''create table if not exists tag
(id_tag integer primary key,
id_url interger,
value text
dt_inserted datetime,
nick text
)''')
cur.execute('''create table if not exists old
(id_old integer primary key,
value text
dt_inserted datetime,
nick text
)''')
self.conn.commit()
cur.close()
@irc3.event(irc3.rfc.PRIVMSG)
def url(self, mask, event, target, data):
"""
parse and reply url title
"""
print("plop")
print(mask, event, target, data)
urls = re.findall('(?P<url>http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)', data)
nick = mask.split('!')[0]
for url in urls:
req = requests.get(url)
soup = BeautifulSoup(req.content)
title = soup.title.string.encode('ascii', 'ignore').decode('ascii', 'ignore')
domain = urlparse(url).netloc.split(':')[0]
self.bot.privmsg(target, "Title: %s - (at %s)" % (title, domain))
cur = self.conn.cursor()
cur.execute("SELECT dt_inserted, nick from url where value='%s'" % url)
data = cur.fetchall()
if data:
self.old(target, nick, data[0][0])
else:
cur.execute("INSERT INTO url(value, title, nick, dt_inserted) VALUES('%s', '%s', '%s', datetime('now')) ;" % (url, title, nick))
self.conn.commit()
cur.close()
def old(self, target, nick, dt_inserted):
self.bot.privmsg(target, '%s pfff' % nick)
# end of file
|
Python
| 0.99801
|
@@ -137,16 +137,57 @@
rt irc3%0A
+from irc3.plugins.command import command%0A
import r
@@ -1581,32 +1581,33 @@
value text
+,
%0A
@@ -1867,72 +1867,8 @@
%22%22%22
-%0A%0A print(%22plop%22)%0A print(mask, event, target, data)
%0A
@@ -2554,17 +2554,24 @@
self.
-o
+displayO
ld(targe
@@ -2822,17 +2822,24 @@
def
-o
+displayO
ld(self,
@@ -2918,16 +2918,699 @@
%25 nick)%0A
+ cur = self.conn.cursor()%0A cur.execute(%22SELECT value FROM old ORDER BY RANDOM() LIMIT 1%22)%0A data = cur.fetchall()%0A if data:%0A self.bot.privmsg(target, '%25s %25s %25s' %25 (nick, data%5B0%5D%5B0%5D, dt_inserted))%0A cur.close()%0A%0A @command%0A def old(self, mask, target, args):%0A %22%22%22old command%0A%0A %25%25old %3Cadd/remove%3E %3Cmessage%3E...%0A %22%22%22%0A nick = mask.split('!')%5B0%5D%0A%0A if args%5B'%3Cadd/remove%3E'%5D.lower() == 'add':%0A cur = self.conn.cursor()%0A cur.execute(%22INSERT INTO old(value, nick, dt_inserted) VALUES('%25s', '%25s', datetime('now'));%22 %25(' '.join(args%5B'%3Cmessage%3E'%5D), nick))%0A self.conn.commit()%0A%0A
# end of
|
70d95cb6aabe4a135827ed9027fd46197d708240
|
Add link to docs
|
homeassistant/components/mqtt_eventstream.py
|
homeassistant/components/mqtt_eventstream.py
|
"""
homeassistant.components.mqtt_eventstream
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Connect two Home Assistant instances via mqtt.
Configuration:
To use the mqtt_eventstream component you will need to add the following to
your configuration.yaml file.
If you do not specify a publish_topic you will not forward events to the queue.
If you do not specify a subscribe_topic then you will not receive events from
the remote server.
mqtt_eventstream:
publish_topic: MyServerName
subscribe_topic: OtherHaServerName
"""
import json
from homeassistant.core import EventOrigin, State
from homeassistant.components.mqtt import DOMAIN as MQTT_DOMAIN
from homeassistant.components.mqtt import SERVICE_PUBLISH as MQTT_SVC_PUBLISH
from homeassistant.const import (
MATCH_ALL,
EVENT_TIME_CHANGED,
EVENT_CALL_SERVICE,
EVENT_SERVICE_EXECUTED,
EVENT_STATE_CHANGED,
)
import homeassistant.loader as loader
from homeassistant.remote import JSONEncoder
# The domain of your component. Should be equal to the name of your component
DOMAIN = "mqtt_eventstream"
# List of component names (string) your component depends upon
DEPENDENCIES = ['mqtt']
def setup(hass, config):
""" Setup our mqtt_eventstream component. """
mqtt = loader.get_component('mqtt')
pub_topic = config[DOMAIN].get('publish_topic', None)
sub_topic = config[DOMAIN].get('subscribe_topic', None)
def _event_publisher(event):
""" Handle events by publishing them on the mqtt queue. """
if event.origin != EventOrigin.local:
return
if event.event_type == EVENT_TIME_CHANGED:
return
# Filter out the events that were triggered by publishing
# to the MQTT topic, or you will end up in an infinite loop.
if event.event_type == EVENT_CALL_SERVICE:
if (
event.data.get('domain') == MQTT_DOMAIN and
event.data.get('service') == MQTT_SVC_PUBLISH and
event.data.get('topic') == pub_topic
):
return
# Filter out all the "event service executed" events because they
# are only used internally by core as callbacks for blocking
# during the interval while a service is being executed.
# They will serve no purpose to the external system,
# and thus are unnecessary traffic.
# And at any rate it would cause an infinite loop to publish them
# because publishing to an MQTT topic itself triggers one.
if event.event_type == EVENT_SERVICE_EXECUTED:
return
event_info = {'event_type': event.event_type, 'event_data': event.data}
msg = json.dumps(event_info, cls=JSONEncoder)
mqtt.publish(hass, pub_topic, msg)
# Only listen for local events if you are going to publish them
if pub_topic:
hass.bus.listen(MATCH_ALL, _event_publisher)
# Process events from a remote server that are received on a queue
def _event_receiver(topic, payload, qos):
"""
Receive events published by the other HA instance and fire
them on this hass instance.
"""
event = json.loads(payload)
event_type = event.get('event_type')
event_data = event.get('event_data')
# Special case handling for event STATE_CHANGED
# We will try to convert state dicts back to State objects
# Copied over from the _handle_api_post_events_event method
# of the api component.
if event_type == EVENT_STATE_CHANGED and event_data:
for key in ('old_state', 'new_state'):
state = State.from_dict(event_data.get(key))
if state:
event_data[key] = state
hass.bus.fire(
event_type,
event_data=event_data,
origin=EventOrigin.remote
)
# Only subscribe if you specified a topic
if sub_topic:
mqtt.subscribe(hass, sub_topic, _event_receiver)
hass.states.set('{domain}.initialized'.format(domain=DOMAIN), True)
# return boolean to indicate that initialization was successful
return True
|
Python
| 0
|
@@ -126,400 +126,150 @@
via
-mqtt.%0A%0AConfiguration:%0A%0ATo use the mqtt_eventstream component you will need to add the following to%0Ayour configuration.yaml file.%0A%0AIf you do not specify a publish_topic you will not forward events to the queue.%0AIf you do not specify a subscribe_topic then you will not receive events from%0Athe remote server.%0A%0Amqtt_eventstream:%0A publish_topic: MyServerName%0A subscribe_topic: OtherHaServerName
+MQTT..%0A%0AFor more details about this component, please refer to the documentation at%0Ahttps://home-assistant.io/components/mqtt_eventstream.html
%0A%22%22%22
@@ -948,17 +948,16 @@
tup
-our mqtt_
+th MQTT
even
@@ -1223,20 +1223,20 @@
on the
-mqtt
+MQTT
queue.
|
5cff305e60a6c8a13843789dbdff16d12f782e81
|
Fix typo on openstack_nova_path help doc
|
perfkitbenchmarker/providers/openstack/flags.py
|
perfkitbenchmarker/providers/openstack/flags.py
|
# Copyright 2015 PerfKitBenchmarker Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from perfkitbenchmarker import flags
flags.DEFINE_string('openstack_cli_path',
default='openstack',
help='The path to the OpenStack CLI binary.')
flags.DEFINE_string('openstack_nova_path',
default='nova',
help='the path to the Nova CLI binary.')
flags.DEFINE_string('openstack_neutron_path',
default='neutron',
help='The path to the Neutron CLI binary.')
flags.DEFINE_string('openstack_additional_flags',
default=[],
help='Additional flags to pass to every OpenStack CLI '
'command. See "openstack --help" for more.')
flags.DEFINE_string('openstack_public_network', None,
'(DEPRECATED: Use openstack_floating_ip_pool) '
'Name of OpenStack public network.')
flags.DEFINE_string('openstack_private_network', 'private',
'(DEPRECATED: Use openstack_network) '
'Name of OpenStack private network.')
flags.DEFINE_string('openstack_network', 'private',
'Name of OpenStack network. This network provides '
'automatically allocated fixed-IP addresses to attached '
'instances. Typically, this network is used for internal '
'communication between instances. '
'If openstack_floating_ip_pool is not '
'set then this network will be used to communicate with '
'the instance.')
flags.DEFINE_string('openstack_floating_ip_pool', None,
'Name of OpenStack floating IP-address pool. If set, '
'a floating-ip address from this pool will be associated'
'to each instance and will be used for communicating '
'with it. To use this flag, an internally routable network '
'must also be specified via the openstack_network flag.')
flags.DEFINE_boolean('openstack_config_drive', False,
'Add possibilities to get metadata from external drive')
flags.DEFINE_boolean('openstack_boot_from_volume', False,
'Boot from volume instead of an image')
flags.DEFINE_integer('openstack_volume_size', None,
'Size of the volume (GB)')
flags.DEFINE_string('openstack_image_username', 'ubuntu',
'Ssh username for cloud image')
NONE = 'None'
flags.DEFINE_enum('openstack_scheduler_policy', NONE,
[NONE, 'affinity', 'anti-affinity'],
'Add possibility to use affinity or anti-affinity '
'policy in scheduling process')
|
Python
| 0.000016
|
@@ -897,17 +897,17 @@
help='
-t
+T
he path
|
5a53726cafc776f50079dfbe7c574428b7424569
|
fix permissions
|
nlp_engine.py
|
nlp_engine.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2015, 2016, 2017 Guenter Bartsch
#
# This program 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 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
# core nlp engine
#
# natural language -> [ tokenizer ] -> tokens -> [ seq2seq model ] -> prolog -> [ prolog engine ] -> say/action preds
#
import os
import sys
import logging
import traceback
from optparse import OptionParser
from StringIO import StringIO
from sqlalchemy.orm import sessionmaker
import numpy as np
import model
from logic import *
from logicdb import *
from prolog_parser import PrologParser, SYM_EOF, PrologError
from prolog_ai_engine import PrologAIEngine
from speech_tokenizer import tokenize
from nlp_model import NLPModel, BUCKETS, CKPT_FN
import tensorflow as tf
class NLPEngine(object):
def __init__(self, tf_session):
self.tf_session = tf_session
# session, connect to db
Session = sessionmaker(bind=model.engine)
session = Session()
#
# prolog environment setup
#
db = LogicDB(session)
self.prolog_engine = PrologAIEngine(db)
self.parser = PrologParser()
for m in model.config.get("semantics", "modules").split(','):
m = m.strip()
logging.debug("enabling module %s" % repr(m))
db.enable_module(m)
#
# load nlp model
#
self.nlp_model = NLPModel(session)
self.nlp_model.load_dicts()
# we need the inverse dict to reconstruct the output from tensor
self.inv_output_dict = {v: k for k, v in self.nlp_model.output_dict.iteritems()}
self.tf_model = self.nlp_model.create_tf_model(self.tf_session, forward_only = True)
self.tf_model.batch_size = 1
self.nlp_model.load_model(self.tf_session)
def process_line(self, line):
x = self.nlp_model.compute_x(line)
logging.debug("x: %s -> %s" % (line, x))
# which bucket does it belong to?
bucket_id = min([b for b in xrange(len(BUCKETS)) if BUCKETS[b][0] > len(x)])
# get a 1-element batch to feed the sentence to the model
encoder_inputs, decoder_inputs, target_weights = self.tf_model.get_batch( {bucket_id: [(x, [])]}, bucket_id )
# print "encoder_inputs, decoder_inputs, target_weights", encoder_inputs, decoder_inputs, target_weights
# get output logits for the sentence
_, _, output_logits = self.tf_model.step(self.tf_session, encoder_inputs, decoder_inputs, target_weights, bucket_id, True)
logging.debug("output_logits: %s" % repr(output_logits))
# this is a greedy decoder - outputs are just argmaxes of output_logits.
outputs = [int(np.argmax(logit, axis=1)) for logit in output_logits]
# print "outputs", outputs
preds = map (lambda o: self.inv_output_dict[o], outputs)
logging.debug("preds: %s" % repr(preds))
prolog_s = ''
for p in preds:
if p[0] == '_':
continue # skip _EOS
if len(prolog_s)>0:
prolog_s += ', '
prolog_s += p
logging.debug('?- %s' % prolog_s)
try:
c = self.parser.parse_line_clause_body(prolog_s)
logging.debug( "Parse result: %s" % c)
self.prolog_engine.reset_utterances()
self.prolog_engine.reset_actions()
self.prolog_engine.search(c)
utts = self.prolog_engine.get_utterances()
actions = self.prolog_engine.get_actions()
return utts, actions
except PrologError as e:
logging.error("*** ERROR: %s" % e)
return [], []
|
Python
| 0
| |
7f17ad3874b95c34228f95cb5cb6b4dd98cf43fa
|
Update the doc string on _save_artifacts
|
bok_choy/web_app_test.py
|
bok_choy/web_app_test.py
|
"""
Base class for testing a web application.
"""
from abc import ABCMeta
import sys
from unittest import SkipTest
from uuid import uuid4
from needle.cases import NeedleTestCase, import_from_string
from .browser import browser, save_screenshot, save_driver_logs, save_source
class WebAppTest(NeedleTestCase):
"""
Base class for testing a web application.
"""
__metaclass__ = ABCMeta
# Execute tests in parallel!
_multiprocess_can_split_ = True
def __init__(self, *args, **kwargs):
super(WebAppTest, self).__init__(*args, **kwargs)
# This allows using the @attr() decorator from nose to set these on a
# test by test basis
self.proxy = getattr(self, 'proxy', None)
@classmethod
def setUpClass(cls):
"""
Override NeedleTestCase's setUpClass method so that it does not
start up the browser once for each testcase class.
Instead we start up the browser once per TestCase instance,
in the setUp method.
"""
# Instantiate the diff engine.
# This will allow Needle's flexibility for choosing which you want to use.
# These lines are copied over from Needle's setUpClass method.
klass = import_from_string(cls.engine_class)
cls.engine = klass()
# Needle's setUpClass method set up the driver (thus starting up the browser),
# and set the initial window position and viewport size.
# Those lines are not copied here into WebAppTest's setUpClass method,
# but instead into our setUp method. This follows our paradigm of starting
# up a new browser session for each TestCase.
# Now call the super of the NeedleTestCase class, so that we get everything
# from the setUpClass method of its parent (unittest.TestCase).
super(NeedleTestCase, cls).setUpClass() # pylint: disable=bad-super-call
@classmethod
def tearDownClass(cls):
"""
Override NeedleTestCase's tearDownClass method because it
would quit the browser. This is not needed as we have already quit the browser
after each TestCase, by virtue of a cleanup that we add in the setUp method.
"""
# We still want to call the super of the NeedleTestCase class, so that we get
# everything from the tearDownClass method of its parent (unittest.TestCase).
super(NeedleTestCase, cls).tearDownClass() # pylint: disable=bad-super-call
def get_web_driver(self):
"""
Override NeedleTestCases's get_web_driver class method to return the WebDriver instance
that is already being used, instead of starting up a new one.
"""
return self.browser
def set_viewport_size(self, width, height):
"""
Override NeedleTestCases's set_viewport_size class method because we need it to operate
on the instance not the class.
See the Needle documentation at http://needle.readthedocs.org/ for information on this
feature. It is particularly useful to predict the size of the resulting screenshots
when taking fullscreen captures, or to test responsive sites.
"""
self.driver.set_window_size(width, height)
# Measure the difference between the actual document width and the
# desired viewport width so we can account for scrollbars:
script = "return {width: document.body.clientWidth, height: document.body.clientHeight};"
measured = self.driver.execute_script(script)
delta = width - measured['width']
self.driver.set_window_size(width + delta, height)
def setUp(self):
"""
Start the browser for use by the test.
You *must* call this in the `setUp` method of any subclasses before using the browser!
Returns:
None
"""
super(WebAppTest, self).setUp()
# Set up the browser
# This will start the browser
# If using SauceLabs, tag the job with test info
tags = [self.id()]
self.browser = browser(tags, self.proxy)
# Needle uses these attributes for taking the screenshots
self.driver = self.get_web_driver()
self.driver.set_window_position(0, 0)
self.set_viewport_size(self.viewport_width, self.viewport_height)
# Cleanups are executed in LIFO order.
# This ensures that the screenshot is taken and the driver logs are saved
# BEFORE the browser quits.
self.addCleanup(self.browser.quit)
self.addCleanup(self._save_artifacts)
@property
def unique_id(self):
"""
Helper method to return a uuid.
Returns:
39-char UUID string
"""
return str(uuid4().int) # pylint: disable=no-member
def _save_artifacts(self):
"""
On failure or error save a screenshot, the
selenium driver logs, and the captured har file.
"""
# Determine whether the test case succeeded or failed
result = sys.exc_info()
exception_type = result[0]
# Do not save artifacts for skipped tests.
if exception_type is SkipTest:
return
# If it failed, take a screenshot and save the driver logs.
# The exception info will either be an assertion error (on failure)
# or an actual exception (on error)
if result != (None, None, None):
try:
save_screenshot(self.browser, self.id())
except: # pylint: disable=bare-except
pass
try:
save_source(self.browser, self.id())
except: # pylint: disable=bare-except
pass
try:
save_driver_logs(self.browser, self.id())
except: # pylint: disable=bare-except
pass
|
Python
| 0.000003
|
@@ -4905,54 +4905,48 @@
s
-elenium driver logs, and the captured har file
+ource html, and the selenium driver logs
.%0A
|
28455c541b45ef6ca8e098702e0b7ea7c49a4a71
|
Update ASDF version.
|
versions/software/asdf.py
|
versions/software/asdf.py
|
from versions.software.utils import get_response, get_text_between
def name():
"""Return the precise name for the software."""
return 'asdf'
def installed_version():
"""Return the installed version of asdf."""
# I don't have a command-line version to run to get this from
return '3.3.1'
def latest_version():
"""Return the latest version of asdf available for download."""
url = 'https://common-lisp.net/project/asdf/archives/asdf.lisp'
source_code = get_response(url).text
return get_text_between(source_code, 'This is ASDF ', ':')
|
Python
| 0
|
@@ -305,9 +305,9 @@
3.3.
-1
+2
'%0A%0A%0A
|
4011c54fc1e20f9d2e9514c1344ce3ee5bf032db
|
fix docstring
|
lm_atm/__init__.py
|
lm_atm/__init__.py
|
"""The pyro solver for low Mach number atmospheric flow. This
implements as second-order approximate projection method. The general
flow is:
* create the limited slopes of rho, u and v (in both directions)
* get the advective velocities through a piecewise linear Godunov
method
* enforce the divergence constraint on the velocities through a
projection (the MAC projection)
* predict rho to edges and do the conservative update
* recompute the interface states using the new advective velocity
* update U in time to get the provisional velocity field
* project the final velocity to enforce the divergence constraint.
The projections are done using multigrid
"""
from .simulation import *
|
Python
| 0.000018
|
@@ -268,17 +268,16 @@
Godunov
-
%0A metho
@@ -346,11 +346,9 @@
gh a
- %0A
+%0A
pr
@@ -699,10 +699,8 @@
mport *%0A
-%0A%0A
|
9362511d420a297fc1ed27f0642c4dcd527b4aff
|
Swap incorrect argument
|
babel_util/scripts/wos_to_edge.py
|
babel_util/scripts/wos_to_edge.py
|
#!/usr/bin/env python3
from parsers.wos import WOSStream
from util.PajekFactory import PajekFactory
from util.misc import open_file, Benchmark
if __name__ == "__main__":
import argparse
import sys
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from WOS XML")
parser.add_argument('infile')
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), default=sys.stdout)
arguments = parser.parse_args()
with open_file(parser.infile) as f:
p = WOSStream(f)
for entry in p.parse():
for citation in entry["citations"]:
arguments.write("%s\t%s\n" % (entry["id"], citation))
|
Python
| 0.998647
|
@@ -476,22 +476,25 @@
en_file(
-p
ar
-ser
+guments
.infile)
|
48db4161ec662af6330d3c853db4482f7f459f9d
|
convert dates properly
|
generate/json_loader.py
|
generate/json_loader.py
|
import mimetypes
import os
import sys
import json
import urllib
import hashlib
import cStringIO
import unicodedata
import random
from django.db.models import get_model, FileField, ImageField
from django.db.models.fields.related import ForeignKey
from django.db.models.fields.related import ManyToManyField
from django.core.files.uploadedfile import InMemoryUploadedFile
SCRIPT_PATH = os.path.dirname( os.path.realpath( __file__ ) )
USE_CACHE = True
def load_file(field, source):
source = fetch_from_cache(source)
size = os.path.getsize(source)
f = cStringIO.StringIO()
f.write(open(source, 'r').read())
field_name = str(field)
file_name = source.split('/')[-1]
content_type=mimetypes.guess_type(file_name)[0]
elements = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456890'
file_name = '%s.%s' % (''.join([random.choice(elements) for n in range(8)]), file_name.split('.')[-1])
return InMemoryUploadedFile(f, field_name, file_name, content_type, size, None)
def fetch_from_cache(source):
destination = source
if source.startswith('http'):
destination = '%s/json_loader_cache/%s' % (SCRIPT_PATH, hashlib.md5(source).hexdigest())
if not USE_CACHE or not os.path.exists(destination):
#print "Fetching %s..." % source
f = open(destination, 'w')
f.write(urllib.urlopen(source).read())
f.close()
return destination
def generate_item(item):
app, model = item['model'].split('.')
model = get_model(app, model)
model_instance = model(pk='dummy_pk')
fields = {}
many_to_many_fields = {}
image_fields = {}
file_fields = {}
password_field = ''
for field, value in item['fields'].items():
if value.__class__ == list:
value_items = []
for item in value:
if item.__class__ == dict:
value_items.append(generate_item(item))
else:
value_items.append(item)
value = value_items
elif value.__class__ == dict:
value = generate_item(value)
model_field = model_instance._meta.get_field(field)
if isinstance(model_field, ManyToManyField):
many_to_many_fields[str(field)] = value
elif isinstance(model_field, ImageField):
if value:
image_fields[str(field)] = value
elif isinstance(model_field, FileField):
if value:
file_fields[str(field)] = value
elif field == 'password':
password_field = value
else:
fields[str(field)] = value
obj, created = model.objects.get_or_create(**fields)
if created:
#print "Created %s" % obj
for field, value in many_to_many_fields.items():
obj_field = getattr(obj, field)
if value.__class__ == list:
for val in value:
obj_field.add(val)
else:
obj_field.add(value)
for field, value in image_fields.items():
field_attr = getattr(obj, field)
f = load_file(field, value)
field_attr.save(f.name, f)
for field, value in file_fields.items():
field_attr = getattr(obj, field)
f = load_file(field, value)
field_attr.save(f.name, f)
if password_field:
obj.set_password(password_field)
obj.save()
return obj
def load_json(source, data_formatter=None):
if source.__class__ == str:
source = fetch_from_cache(source)
source = open(source, 'r')
data = source.read()
json_data = json.loads(data)
source.close()
elif source.__class__ == list:
source = [str(item).replace("False", "false").replace("True", "true").replace("'", '"') for item in source]
json_data = json.loads("[%s]" % ','.join(source))
if data_formatter:
json_data = data_formatter(json_data)
i = 1
previous_status = ""
for item in json_data:
generate_item(item)
status = "Generating items, please wait... %s%%" % (100 * i / len(json_data))
if status != previous_status:
sys.stdout.write("\b" * len(status))
sys.stdout.write(status)
sys.stdout.flush()
i += 1
print ""
|
Python
| 0.999722
|
@@ -122,16 +122,46 @@
t random
+%0Afrom datetime import datetime
%0A%0Afrom d
@@ -193,16 +193,42 @@
t_model,
+ DateField, DateTimeField,
FileFie
@@ -2646,32 +2646,563 @@
d_field = value%0A
+ elif isinstance(model_field, DateTimeField):%0A try:%0A fields%5Bstr(field)%5D = datetime.strptime(value, %22%25Y-%25m-%25d %25H:%25M:%25S.%25f%22)%0A except ValueError:%0A fields%5Bstr(field)%5D = datetime.strptime(value, %22%25Y-%25m-%25d %25H:%25M:%25S%22)%0A elif isinstance(model_field, DateField):%0A try:%0A fields%5Bstr(field)%5D = datetime.strptime(value, %22%25Y-%25m-%25d%22).date()%0A except ValueError:%0A fields%5Bstr(field)%5D = datetime.strptime(value, %22%25Y-%25m-%25d %25H:%25M:%25S%22)%0A
else:%0A
|
e5214b07ae60d16f796b68a519ce719ed09838fd
|
Fix aggregation not expanding into a actual list
|
localized_fields/fields/field.py
|
localized_fields/fields/field.py
|
import json
from typing import Union
from django.conf import settings
from django.db.utils import IntegrityError
from psqlextra.fields import HStoreField
from ..forms import LocalizedFieldForm
from ..value import LocalizedValue
from ..descriptor import LocalizedValueDescriptor
class LocalizedField(HStoreField):
"""A field that has the same value in multiple languages.
Internally this is stored as a :see:HStoreField where there
is a key for every language."""
Meta = None
# The class to wrap instance attributes in. Accessing to field attribute in
# model instance will always return an instance of attr_class.
attr_class = LocalizedValue
# The descriptor to use for accessing the attribute off of the class.
descriptor_class = LocalizedValueDescriptor
def __init__(self, *args, **kwargs):
"""Initializes a new instance of :see:LocalizedField."""
super(LocalizedField, self).__init__(*args, **kwargs)
def contribute_to_class(self, model, name, **kwargs):
"""Adds this field to the specifed model.
Arguments:
cls:
The model to add the field to.
name:
The name of the field to add.
"""
super(LocalizedField, self).contribute_to_class(model, name, **kwargs)
setattr(model, self.name, self.descriptor_class(self))
@classmethod
def from_db_value(cls, value, *_):
"""Turns the specified database value into its Python
equivalent.
Arguments:
value:
The value that is stored in the database and
needs to be converted to its Python equivalent.
Returns:
A :see:LocalizedValue instance containing the
data extracted from the database.
"""
if not value:
if getattr(settings, 'LOCALIZED_FIELDS_EXPERIMENTAL', False):
return None
else:
return cls.attr_class()
return cls.attr_class(value)
def to_python(self, value: Union[dict, str, None]) -> LocalizedValue:
"""Turns the specified database value into its Python
equivalent.
Arguments:
value:
The value that is stored in the database and
needs to be converted to its Python equivalent.
Returns:
A :see:LocalizedValue instance containing the
data extracted from the database.
"""
# first let the base class handle the deserialization, this is in case we
# get specified a json string representing a dict
try:
deserialized_value = super(LocalizedField, self).to_python(value)
except json.JSONDecodeError:
deserialized_value = value
if not deserialized_value:
return self.attr_class()
return self.attr_class(deserialized_value)
def get_prep_value(self, value: LocalizedValue) -> dict:
"""Turns the specified value into something the database
can store.
If an illegal value (non-LocalizedValue instance) is
specified, we'll treat it as an empty :see:LocalizedValue
instance, on which the validation will fail.
Arguments:
value:
The :see:LocalizedValue instance to serialize
into a data type that the database can understand.
Returns:
A dictionary containing a key for every language,
extracted from the specified value.
"""
# default to None if this is an unknown type
if not isinstance(value, LocalizedValue) and value:
value = None
if value:
cleaned_value = self.clean(value)
self.validate(cleaned_value)
else:
cleaned_value = value
return super(LocalizedField, self).get_prep_value(
cleaned_value.__dict__ if cleaned_value else None
)
def clean(self, value, *_):
"""Cleans the specified value into something we
can store in the database.
For example, when all the language fields are
left empty, and the field is allows to be null,
we will store None instead of empty keys.
Arguments:
value:
The value to clean.
Returns:
The cleaned value, ready for database storage.
"""
if not value or not isinstance(value, LocalizedValue):
return None
# are any of the language fiels None/empty?
is_all_null = True
for lang_code, _ in settings.LANGUAGES:
if value.get(lang_code):
is_all_null = False
break
# all fields have been left empty and we support
# null values, let's return null to represent that
if is_all_null and self.null:
return None
return value
def validate(self, value: LocalizedValue, *_):
"""Validates that the value for the primary language
has been filled in.
Exceptions are raises in order to notify the user
of invalid values.
Arguments:
value:
The value to validate.
"""
if self.null:
return
primary_lang_val = getattr(value, settings.LANGUAGE_CODE)
if not primary_lang_val:
raise IntegrityError(
'null value in column "%s.%s" violates not-null constraint' % (
self.name,
settings.LANGUAGE_CODE
)
)
def formfield(self, **kwargs):
"""Gets the form field associated with this field."""
defaults = {
'form_class': LocalizedFieldForm
}
defaults.update(kwargs)
return super().formfield(**defaults)
def deconstruct(self):
"""Gets the values to pass to :see:__init__ when
re-creating this object."""
name, path, args, kwargs = super(
LocalizedField, self).deconstruct()
if self.uniqueness:
kwargs['uniqueness'] = self.uniqueness
return name, path, args, kwargs
|
Python
| 0.000424
|
@@ -1990,32 +1990,672 @@
s.attr_class()%0A%0A
+ # we can get a list if an aggregation expression was used..%0A # if we the expression was flattened when only one key was selected%0A # then we don't wrap each value in a localized value, otherwise we do%0A if isinstance(value, list):%0A result = %5B%5D%0A for inner_val in value:%0A if isinstance(inner_val, dict):%0A if inner_value is None:%0A result.append(None)%0A else:%0A result.append(cls.attr_class(inner_val))%0A else:%0A result.append(inner_val)%0A%0A return result%0A%0A
return c
|
c638f309dbe7621243f0b46555439506b12d5d37
|
check that COOP solar rad values are good, non-negative
|
scripts/iemre/grid_rsds.py
|
scripts/iemre/grid_rsds.py
|
"""Do the gridding of Solar Radiation Data
Called from RUN_MIDNIGHT.sh
"""
import netCDF4
import pygrib
import pyproj
import datetime
import psycopg2
import pytz
import os
import sys
import numpy as np
from pyiem import iemre
from scipy.interpolate import NearestNDInterpolator
P4326 = pyproj.Proj(init="epsg:4326")
LCC = pyproj.Proj(("+lon_0=-97.5 +y_0=0.0 +R=6367470. +proj=lcc +x_0=0.0"
" +units=m +lat_2=38.5 +lat_1=38.5 +lat_0=38.5"))
SWITCH_DATE = datetime.datetime(2014, 10, 10, 20)
SWITCH_DATE = SWITCH_DATE.replace(tzinfo=pytz.timezone("UTC"))
def do_coop(ts):
"""Use COOP solar radiation data"""
pgconn = psycopg2.connect(database='coop', host='iemdb', user='nobody')
cursor = pgconn.cursor()
cursor.execute("""SELECT ST_x(geom), ST_y(geom),
coalesce(narr_srad, merra_srad) from alldata a JOIN stations t
ON (a.station = t.id) WHERE
day = %s and t.network ~* 'CLIMATE' and substr(id, 3, 1) != 'C'
and substr(id, 3, 4) != '0000'
""", (ts.strftime("%Y-%m-%d"), ))
lons = []
lats = []
vals = []
for row in cursor:
lons.append(row[0])
lats.append(row[1])
vals.append(row[2])
nn = NearestNDInterpolator((np.array(lons), np.array(lats)),
np.array(vals))
xi, yi = np.meshgrid(iemre.XAXIS, iemre.YAXIS)
nc = netCDF4.Dataset("/mesonet/data/iemre/%s_mw_daily.nc" % (ts.year,),
'a')
offset = iemre.daily_offset(ts)
# Data above is MJ / d / m-2, we want W / m-2
nc.variables['rsds'][offset, :, :] = nn(xi, yi) * 1000000. / 86400.
nc.close()
def do_hrrr(ts):
"""Convert the hourly HRRR data to IEMRE grid"""
total = None
xaxis = None
yaxis = None
for hr in range(5, 23): # Only need 5 AM to 10 PM for solar
utc = ts.replace(hour=hr).astimezone(pytz.timezone("UTC"))
fn = utc.strftime(("/mesonet/ARCHIVE/data/%Y/%m/%d/model/hrrr/%H/"
"hrrr.t%Hz.3kmf00.grib2"))
if not os.path.isfile(fn):
# print 'HRRR file %s missing' % (fn,)
continue
grbs = pygrib.open(fn)
try:
if utc >= SWITCH_DATE:
grb = grbs.select(name='Downward short-wave radiation flux')
else:
grb = grbs.select(parameterNumber=192)
except ValueError:
print 'coop/hrrr_solarrad.py %s had no solar rad' % (fn,)
continue
if len(grb) == 0:
print 'Could not find SWDOWN in HRR %s' % (fn,)
continue
g = grb[0]
if total is None:
total = g.values
lat1 = g['latitudeOfFirstGridPointInDegrees']
lon1 = g['longitudeOfFirstGridPointInDegrees']
llcrnrx, llcrnry = LCC(lon1, lat1)
nx = g['Nx']
ny = g['Ny']
dx = g['DxInMetres']
dy = g['DyInMetres']
xaxis = llcrnrx + dx * np.arange(nx)
yaxis = llcrnry + dy * np.arange(ny)
else:
total += g.values
if total is None:
print 'coop/hrrr_solarrad.py found no HRRR data for %s' % (
ts.strftime("%d %b %Y"), )
return
# We wanna store as W m-2, so we just average out the data by hour
total = total / 24.0
nc = netCDF4.Dataset("/mesonet/data/iemre/%s_mw_daily.nc" % (ts.year,),
'a')
offset = iemre.daily_offset(ts)
data = nc.variables['rsds'][offset, :, :]
for i, lon in enumerate(iemre.XAXIS):
for j, lat in enumerate(iemre.YAXIS):
(x, y) = LCC(lon, lat)
i2 = np.digitize([x], xaxis)[0]
j2 = np.digitize([y], yaxis)[0]
data[j, i] = total[j2, i2]
nc.variables['rsds'][offset] = data
nc.close()
if __name__ == '__main__':
if len(sys.argv) == 4:
sts = datetime.datetime(int(sys.argv[1]), int(sys.argv[2]),
int(sys.argv[3]), 12)
else:
sts = datetime.datetime.now() - datetime.timedelta(days=1)
sts = sts.replace(hour=12)
sts = sts.replace(tzinfo=pytz.timezone("America/Chicago"))
if sts.year >= 2014:
do_hrrr(sts)
else:
do_coop(sts)
|
Python
| 0.999981
|
@@ -1104,24 +1104,86 @@
in cursor:%0A
+ if row%5B2%5D is None or row%5B2%5D %3C 0:%0A continue%0A
lons
|
8a92b08229119b21d7f79d1010fe73039bdd0d74
|
Fix test regression from fixing #132 and #135.
|
south/tests/modelsparser.py
|
south/tests/modelsparser.py
|
# -*- coding: UTF-8 -*-
import unittest
from south.db import db
from south.tests import Monkeypatcher
from south.tests.fakeapp.models import HorribleModel, Other1, Other2
from south.modelsparser import get_model_fields, get_model_meta
class TestModelParsing(Monkeypatcher):
"""
Tests parsing of models.py files against the test one.
"""
def test_fields(self):
fields = get_model_fields(HorribleModel)
self.assertEqual(
fields,
{
'id': ('models.AutoField', [], {'primary_key': 'True'}),
'name': ('models.CharField', [], {'max_length': '255'}),
'short_name': ('models.CharField', [], {'max_length': '50'}),
'slug': ('models.SlugField', [], {'unique': 'True'}),
'o1': ('models.ForeignKey', ['Other1'], {}),
'o2': ('models.ForeignKey', ["'Other2'"], {}),
'user': ('models.ForeignKey', ['User'], {'related_name': '"horribles"'}),
'code': ('models.CharField', [], {'max_length': '25', 'default': "'\\xe2\\x86\\x91\\xe2\\x86\\x91\\xe2\\x86\\x93\\xe2\\x86\\x93\\xe2\\x86\\x90\\xe2\\x86\\x92\\xe2\\x86\\x90\\xe2\\x86\\x92BA'"}),
'class_attr': ('models.IntegerField', [], {'default': '0'}),
'func': ('models.CharField', [], {'default': "'yays'", 'max_length': '25'}),
'choiced': ('models.CharField', [], {'max_length': '20', 'choices': 'choices'}),
'multiline': ('models.TextField', [], {}),
},
)
fields2 = get_model_fields(Other2)
self.assertEqual(
fields2,
{'close_but_no_cigar': ('models.PositiveIntegerField', [], {'primary_key': 'True'})},
)
fields3 = get_model_fields(Other1)
self.assertEqual(
fields3,
{'id': ('models.AutoField', [], {'primary_key': 'True'})},
)
def test_meta(self):
meta = get_model_meta(HorribleModel)
self.assertEqual(
meta,
{'db_table': '"my_fave"', 'verbose_name': '"Dr. Strangelove,"+"""or how I learned to stop worrying\nand love the bomb"""'},
)
|
Python
| 0
|
@@ -1446,14 +1446,20 @@
': %22
-'yays'
+default_func
%22, '
|
70868f7162bfd90978b89da8d48f0cf78dfc7658
|
remove white space from gene ids
|
chanjo_report/server/blueprints/report/views.py
|
chanjo_report/server/blueprints/report/views.py
|
# -*- coding: utf-8 -*-
from __future__ import division
import datetime
import logging
from chanjo.store.api import filter_samples
from chanjo.store import Exon, Gene
from flask import abort, Blueprint, render_template, request, url_for
from flask_weasyprint import render_pdf
from chanjo_report.server.extensions import api
logger = logging.getLogger(__name__)
report_bp = Blueprint('report', __name__, template_folder='templates',
static_folder='static', static_url_path='/static/report')
@report_bp.route('/')
def index():
sample_objs = api.samples()
gene_objs = api.query(Gene).limit(50)
return render_template('report/index.html', samples=sample_objs,
genes=gene_objs)
@report_bp.route('/<gene_id>')
def gene(gene_id):
"""Display coverage information on a gene."""
sample_vals = api.gene(gene_id)
return render_template('report/gene.html', samples=sample_vals,
gene_id=gene_id)
@report_bp.route('/group/<group_id>')
@report_bp.route('/samples')
def group(group_id=None):
"""Generate a coverage report for a group of samples.
It's possible to map existing group and sample ids to display ids
by passing them as key/value pair request args.
"""
gene_ids = request.args.get('gene_ids', [])
if gene_ids:
gene_ids = gene_ids.split(',')
sample_ids = request.args.get('sample_ids', [])
if sample_ids:
sample_ids = sample_ids.split(',')
try:
level = int(request.args.get('level'))
except (ValueError, TypeError):
level = 10
# generate id map
id_map = {key.lstrip('alt_'): value for key, value in request.args.items()
if key.startswith('alt_')}
customizations = {
'level': level,
'gene_ids': gene_ids,
'panel_name': request.args.get('panel_name'),
'sample_ids': sample_ids,
'show_genes': 'show_genes' in request.args,
'id_map': id_map
}
logger.debug('fetch samples for group %s', group_id)
sample_objs = api.samples(group_id=group_id,
sample_ids=customizations['sample_ids'])
sample_dict = {sample_obj.sample_id: sample_obj
for sample_obj in sample_objs}
logger.debug('generate base queries for report')
group_query = filter_samples(api.query(), group_id=group_id,
sample_ids=customizations['sample_ids'])
if customizations['gene_ids']:
exon_ids = [exon_obj.exon_id for exon_obj
in api.gene_exons(*customizations['gene_ids'])]
panel_query = group_query.filter(Exon.exon_id.in_(exon_ids))
else:
panel_query = group_query
exon_ids = None
logger.debug('generate general stats (gene panel)')
key_metrics = api.means(panel_query)
levels = api.completeness_levels()
if not customizations['level'] in [item[0] for item in levels]:
return abort(400, ('completeness level not supported: {}'
.format(customizations['level'])))
logger.debug('calculate diagnostic yield for each sample')
tx_samples = [(sample_obj,
api.diagnostic_yield(sample_obj.sample_id,
exon_ids=exon_ids,
level=customizations['level']))
for sample_obj in sample_objs]
return render_template(
'report/report.html',
samples=sample_dict,
key_metrics=key_metrics,
customizations=customizations,
levels=levels,
diagnostic_yield=tx_samples,
genders=api.sex_check(group_id=group_id,
sample_ids=customizations['sample_ids']),
created_at=datetime.date.today(),
group_id=group_id,
)
@report_bp.route('/<route>/<filter_id>.pdf')
def pdf(route, filter_id):
# make a PDF from another view
if route == 'group':
response = render_pdf(url_for('report.group', group_id=filter_id,
**request.args))
else:
return abort(404)
# check if the request is to download the file right away
if 'dl' in request.args:
fname = "coverage-report_{}.pdf".format(filter_id)
header = "attachment; filename={}".format(fname)
response.headers['Content-Disposition'] = header
return response
|
Python
| 0.000114
|
@@ -1350,16 +1350,48 @@
ne_ids =
+ %5Bgene_id.strip() for gene_id in
gene_id
@@ -1398,24 +1398,25 @@
s.split(',')
+%5D
%0A sample_
|
7b6a16f2dc418e7898d5cca248228d50becf9d05
|
Add a method representation() for transition calendars.
|
calexicon/calendars/historical.py
|
calexicon/calendars/historical.py
|
from datetime import date
from base import Calendar
from calexicon.dates import InvalidDate, DateWithCalendar
from main import JulianCalendar, ProlepticGregorianCalendar
class SwitchDateWithCalendar(DateWithCalendar):
def __str__(self):
return "%s (%s - %s)" % (
self.calendar.date_display_string(self._date),
self.calendar.display_name,
self.calendar.period_string(self._date)
)
class JulianToGregorianCalendar(Calendar):
def date(self, year, month, day):
gregorian_date = date(year, month, day)
if gregorian_date < self.first_gregorian_day:
julian_date = JulianCalendar().date(year, month, day)
if not julian_date < self.first_gregorian_day:
raise InvalidDate("This is a 'missing day' when the calendars changed.")
return self.from_date(julian_date._date)
return self.from_date(gregorian_date)
@classmethod
def date_display_string(cls, d):
if d >= cls.first_gregorian_day:
return ProlepticGregorianCalendar.date_display_string(d)
return JulianCalendar.date_display_string(d)
@classmethod
def period_string(cls, d):
if d >= cls.first_gregorian_day:
return 'Gregorian'
else:
return 'Julian'
def from_date(self, d):
return SwitchDateWithCalendar(self.__class__, d)
class EnglishHistoricalCalendar(JulianToGregorianCalendar):
display_name = "English Historical Calendar"
first_gregorian_day = date(1752, 9, 14)
class SpanishHistoricalCalendar(JulianToGregorianCalendar):
display_name = "Spanish Historical Calendar"
first_gregorian_day = date(1582, 10, 15)
class FrenchHistoricalCalendar(JulianToGregorianCalendar):
display_name = "French Historical Calendar"
first_gregorian_day = date(1582, 12, 20)
|
Python
| 0
|
@@ -1147,16 +1147,219 @@
ing(d)%0A%0A
+ @classmethod%0A def representation(cls, d):%0A if d %3E= cls.first_gregorian_day:%0A return ProlepticGregorianCalendar.representation(d)%0A return JulianCalendar.representation(d)%0A%0A
@cla
|
cc3d03d8750b436cf26633f1d785f14d39cb2bde
|
reduce the appearances of 1/n
|
tchisla.py
|
tchisla.py
|
import math
from fractions import Fraction
from itertools import count, product, combinations_with_replacement, chain, islice
from functools import reduce
from utils import sqrt, factorial
__all__ = ["Tchisla"]
MAX = 1 << 128
MAX_DIGITS = 128
MAX_CONCAT = 39
MAX_FACTORIAL = 34
class Tchisla:
def __init__(self, n, target):
self.n = n
self.target = target
self.solutions = {}
self.visited = [[]]
self.number_printed = set()
def insert(self, x, depth, expression):
self.solutions[x] = depth, expression
self.visited[depth].append(x)
if x == self.target:
self.solution_found(self.target, True)
return True
def check(self, x, depth, expression):
if x.numerator > MAX or x.denominator > MAX or x in self.solutions:
return
if self.insert(x, depth, expression):
return True
z = sqrt(x.denominator)
if z is not None:
y = sqrt(x.numerator)
if y is not None and self.check(Fraction(y, z, False), depth, ("sqrt", x)):
return True
if x.denominator == 1 and x <= MAX_FACTORIAL:
y = Fraction(factorial(int(x)))
if self.check(y, depth, ("factorial", x)):
return True
def exponent(self, p, q, depth):
if q.denominator != 1 or p == 1:
return
p_digits = math.log2(max(p.numerator, p.denominator))
q_int = q.numerator
exp = (("^", p, q), ("^", p, ("-", q)))
while p_digits * q_int > MAX_DIGITS:
if q_int & 1 == 0:
q_int >>= 1
exp = (("sqrt", exp[0]), ("sqrt", exp[1]))
else:
return
x = p ** q_int
if self.check(x, depth, exp[0]):
return True
if self.check(x ** -1, depth, exp[1]):
return True
def binary(self, p, q, depth):
if self.check(p + q, depth, ("+", p, q)):
return True
if p > q and self.check(p - q, depth, ("-", p, q)):
return True
elif p < q and self.check(q - p, depth, ("-", q, p)):
return True
if self.check(p * q, depth, ("*", p, q)):
return True
quotient = p / q
if self.check(quotient, depth, ("/", p, q)):
return True
if self.check(quotient ** -1, depth, ("/", q, p)):
return True
if self.exponent(p, q, depth):
return True
if self.exponent(q, p, depth):
return True
def search(self, depth):
self.visited.append([])
if depth <= MAX_CONCAT:
m = Fraction((10 ** depth - 1) // 9 * self.n)
if self.check(m, depth, ()):
return True
for d1 in range(1, (depth + 1) >> 1):
d2 = depth - d1
for p, q in product(self.visited[d1], self.visited[d2]):
if self.binary(p, q, depth):
return True
if depth & 1 == 0:
for p, q in combinations_with_replacement(self.visited[depth >> 1], 2):
if self.binary(p, q, depth):
return True
def solve(self):
for depth in count(1):
if self.search(depth):
return
@staticmethod
def number_printer(n):
if type(n) is tuple:
if len(n) == 2:
if n[0] == "sqrt":
return "sqrt(" + Tchisla.number_printer(n[1]) + ")"
elif n[0] == "-":
return "-" + Tchisla.number_printer(n[1])
elif len(n) == 3:
return Tchisla.number_printer(n[1]) + n[0] + Tchisla.number_printer(n[2])
else:
return str(n)
def printer(self, n):
depth, expression = self.solutions[n]
string = str(depth) + ": " + str(n)
if expression == ():
return string
string += " = "
if len(expression) == 2:
method, operator = expression
if method == "sqrt":
return string + "sqrt(" + Tchisla.number_printer(operator) + ")"
elif method == "factorial":
return string + str(operator) + "!"
elif len(expression) == 3:
method, op1, op2 = expression
return string + Tchisla.number_printer(op1) + " " + method + " " + Tchisla.number_printer(op2)
@staticmethod
def number_dfs(expression):
if type(expression) is tuple:
return chain.from_iterable(map(Tchisla.number_dfs, islice(expression, 1, None)))
else:
return (expression,)
def solution_found(self, n, force_print = False):
if n in self.number_printed:
return
depth, expression = self.solutions[n]
if expression or force_print:
print(self.printer(n))
self.number_printed.add(n)
for x in Tchisla.number_dfs(expression):
self.solution_found(x)
|
Python
| 0.999999
|
@@ -1288,32 +1288,297 @@
return True%0A%0A
+ def quotient(self, p, q, depth):%0A if p %3C q:%0A p, q = q, p%0A quotient = p / q%0A if self.check(quotient, depth, (%22/%22, p, q)):%0A return True%0A if self.check(quotient ** -1, depth, (%22/%22, q, p)):%0A return True%0A%0A
def exponent
@@ -2517,33 +2517,8 @@
rue%0A
- quotient = p / q%0A
@@ -2525,38 +2525,32 @@
if self.
-check(
quotient
, depth, (%22/
@@ -2541,111 +2541,20 @@
ient
+(p, q
, depth
-, (%22/%22, p, q)):%0A return True%0A if self.check(quotient ** -1, depth, (%22/%22, q, p)
):%0A
|
daed100280b615ab7bd50bbf54d7f40f1d5d2a42
|
Add CAN_DETECT
|
bears/python/PyDocStyleBear.py
|
bears/python/PyDocStyleBear.py
|
from coalib.bearlib.abstractions.Lint import Lint
from coalib.bears.LocalBear import LocalBear
from coalib.bears.requirements.PipRequirement import PipRequirement
from coalib.settings.Setting import typed_list
class PyDocStyleBear(LocalBear, Lint):
executable = 'pydocstyle'
output_regex = r'(.*\.py):(?P<line>\d+) (.+):\n\s+(?P<message>.*)'
use_stderr = True
LANGUAGES = {"Python", "Python 2", "Python 3"}
REQUIREMENTS = {PipRequirement('pydocstyle', '1.*')}
AUTHORS = {'The coala developers'}
AUTHORS_EMAILS = {'coala-devel@googlegroups.com'}
LICENSE = 'AGPL-3.0'
def run(self,
filename,
file,
pydocstyle_select: typed_list(str)=(),
pydocstyle_ignore: typed_list(str)=()):
'''
Checks python docstrings.
:param pydocstyle_select: List of checked errors by specifying
which errors to check for.
:param pydocstyle_ignore: List of checked errors by specifying
which errors to ignore.
Note: pydocstyle_select and pydocstyle_ignore are mutually exclusive.
They cannot be used together.
'''
self.arguments = '{filename}'
if pydocstyle_ignore and pydocstyle_select:
self.err("The arguments pydocstyle_select and pydocstyle_ignore "
"are both given but mutually exclusive.")
return
elif pydocstyle_ignore:
ignore = ','.join(part.strip() for part in pydocstyle_ignore)
self.arguments += " --ignore={}".format(ignore)
elif pydocstyle_select:
select = ','.join(part.strip() for part in pydocstyle_select)
self.arguments += " --select={} ".format(select)
return self.lint(filename, file)
|
Python
| 0.000006
|
@@ -592,16 +592,65 @@
GPL-3.0'
+%0A CAN_DETECT = %7B'Formatting', 'Documentation'%7D
%0A%0A de
|
51872cd1a966f10976200dcdf9998a9119072d43
|
write warnings to stderr, not stdout (which might be muted)
|
export.py
|
export.py
|
#!/usr/bin/env python
import optparse
import os
import sys
import starbound
def main():
p = optparse.OptionParser()
p.add_option('-d', '--destination', dest='path',
help='Destination directory')
options, arguments = p.parse_args()
if len(arguments) != 1:
raise ValueError('Only one argument is supported (package path)')
package_path = arguments[0]
base = options.path if options.path else '.'
with starbound.open_file(package_path) as package:
if not isinstance(package, starbound.Package):
raise ValueError('Provided path is not a package')
print 'Loading index...'
# Get the paths from the index in the database.
paths = list(package.get_index())
print 'Index loaded. Extracting %d files...' % len(paths)
num_files = 0
percentage_count = max(len(paths) // 100, 1)
for path in paths:
dest_path = base + path
dir_path = os.path.dirname(dest_path)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
try:
data = package.get(path)
except:
print
print 'Failed to read', path
continue
with open(dest_path, 'w') as file:
file.write(data)
num_files += 1
if not num_files % percentage_count:
sys.stdout.write('.')
sys.stdout.flush()
print
print 'Extracted %d files.' % num_files
if __name__ == '__main__':
main()
|
Python
| 0
|
@@ -1180,29 +1180,153 @@
-print
+# break the dots in case std%7Bout,err%7D are the same tty:%0A sys.stdout.write('%5Cn')%0A sys.stdout.flush()
%0A
@@ -1336,17 +1336,34 @@
print
-'
+%3E%3Esys.stderr, 'W:
Failed t
|
8785cade9bfe7cc3c54db0d0a068f99c5883ef1b
|
Allow locations to be imported from codelists management page
|
maediprojects/views/codelists.py
|
maediprojects/views/codelists.py
|
from flask import Flask, render_template, flash, request, Markup, \
session, redirect, url_for, escape, Response, abort, send_file, jsonify
from flask.ext.login import login_required, current_user
from maediprojects import app, db, models
from maediprojects.query import activity as qactivity
from maediprojects.query import location as qlocation
from maediprojects.lib import codelists
import json
@app.route("/codelists/")
@login_required
def codelists_management():
return render_template("codelists.html",
loggedinuser=current_user,
codelist_codes = codelists.get_db_codelists(),
codelist_names = codelists.get_db_codelist_names()
)
|
Python
| 0
|
@@ -718,33 +718,790 @@
es()
-%0A
+,%0A countries = codelists.get_codelists()%5B%22Country%22%5D,%0A countries_locations = qlocation.get_countries_locations()%0A )%0A%0A@app.route(%22/codelists/import_locations/%22, methods=%5B%22POST%22%5D)%0A@login_required%0Adef import_locations():%0A existing_countries = list(map(lambda l: l.country.code, %0A qlocation.get_countries_locations()))%0A country_code = request.form.get(%22country%22)%0A if not country_code in existing_countries:%0A qlocation.import_locations(country_code)%0A flash(%22Locations successfully set up for that county!%22, %22success%22)%0A else:%0A flash(%22Locations for that country were not imported, because they have already been imported!%22, %22danger%22)%0A return redirect(url_for(%22codelists_management%22)
)%0A
|
bcedbe27c4fcd5a4ddb9312670b86b2548903192
|
Remove category
|
pinax/ratings/templatetags/pinax_ratings_tags.py
|
pinax/ratings/templatetags/pinax_ratings_tags.py
|
from decimal import Decimal
from django import template
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.urls import reverse
from ..categories import category_value
from ..models import OverallRating, Rating
register = template.Library()
def user_rating_value(user, obj, category=""):
try:
ct = ContentType.objects.get_for_model(obj)
if category:
rating = Rating.objects.get(
object_id=obj.pk,
content_type=ct,
user=user,
category=category_value(obj, category)
).rating
else:
rating = Rating.objects.filter(
object_id=obj.pk,
content_type=ct,
user=user
).aggregate(r=models.Avg("rating"))["r"]
rating = Decimal(str(rating or "0"))
except Rating.DoesNotExist:
rating = 0
return rating
@register.simple_tag
def user_rating(user, object, category=""):
"""
Usage:
{% user_rating user obj [category] as var %}
"""
return user_rating_value(user, object, category)
@register.simple_tag
def overall_rating(object, category=""):
"""
Usage:
{% overall_rating obj [category] as var %}
"""
try:
ct = ContentType.objects.get_for_model(object)
if category:
rating = OverallRating.objects.get(
object_id=object.pk,
content_type=ct,
category=category_value(object, category)
).rating or 0
else:
rating = OverallRating.objects.filter(
object_id=object.pk,
content_type=ct
).aggregate(r=models.Avg("rating"))["r"]
rating = Decimal(str(rating or "0"))
except OverallRating.DoesNotExist:
rating = 0
return rating
def rating_post_url(user, obj):
ct = ContentType.objects.get_for_model(obj)
post_url = reverse(
"pinax_ratings:rate",
kwargs={
"content_type_id": ct.pk,
"object_id": obj.pk
}
)
return post_url
@register.inclusion_tag("pinax/ratings/_script.html")
def user_rating_js(user, obj, category=""):
post_url = rating_post_url(user, obj)
rating = user_rating_value(user, obj, category)
return {
"obj": obj,
"post_url": post_url,
"category": category,
"the_user_rating": rating,
"STATIC_URL": settings.STATIC_URL,
}
@register.simple_tag
def ratings(obj):
ct = ContentType.objects.get_for_model(obj)
try:
return OverallRating.objects.get(
content_type=ct,
object_id=obj.pk,
category=""
).ratings.all()
except OverallRating.DoesNotExist:
return []
@register.simple_tag
def user_rating_url(user, obj):
return rating_post_url(user, obj)
@register.simple_tag
def rating_count(obj):
"""
Total amount of users who have submitted a positive rating for this object.
Usage:
{% rating_count obj %}
"""
count = Rating.objects.filter(
object_id=obj.pk,
content_type=ContentType.objects.get_for_model(obj),
).exclude(rating=0).count()
return count
|
Python
| 0
|
@@ -2755,33 +2755,8 @@
j.pk
-,%0A category=%22%22
%0A
|
e50d42032669d84c344e13863ccb8122b79b8b4a
|
prepare for release
|
auxlib/__about__.py
|
auxlib/__about__.py
|
# -*- coding: utf-8 -*-
"""auxiliary library to the python standard library"""
from __future__ import absolute_import, division, print_function
import os
import sys
import warnings
__all__ = ["__title__", "__author__", "__email__", "__license__", "__copyright__",
"__homepage__"]
__title__ = "auxlib"
__author__ = 'Kale Franz'
__email__ = 'kale@franz.io'
__homepage__ = 'https://github.com/kalefranz/auxlib'
__license__ = "ISC"
__copyright__ = "(c) 2015 Kale Franz. All rights reserved."
__summary__ = locals().__doc__
|
Python
| 0
|
@@ -140,45 +140,8 @@
tion
-%0Aimport os%0Aimport sys%0Aimport warnings
%0A%0A__
|
01d7850ccf5b23c448a898a1a23533e8207e8e49
|
Bump version to 1.7.2
|
betfairlightweight/__init__.py
|
betfairlightweight/__init__.py
|
import logging
from .apiclient import APIClient
from .exceptions import BetfairError
from .streaming import StreamListener
from . import filters
__title__ = 'betfairlightweight'
__version__ = '1.7.1'
__author__ = 'Liam Pauling'
# Set default logging handler to avoid "No handler found" warnings.
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
|
Python
| 0
|
@@ -192,17 +192,17 @@
= '1.7.
-1
+2
'%0A__auth
|
975933d579bfcfb9354174ea3788964980107098
|
Remove duplicate fast flag from kubernetes build
|
scenarios/kubernetes_build.py
|
scenarios/kubernetes_build.py
|
#!/usr/bin/env python
# Copyright 2016 The Kubernetes Authors.
#
# 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.
# Need to figure out why this only fails on travis
# pylint: disable=bad-continuation
"""Builds kubernetes with specified config"""
import argparse
import os
import re
import subprocess
import sys
def check(*cmd):
"""Log and run the command, raising on errors."""
print >>sys.stderr, 'Run:', cmd
subprocess.check_call(cmd)
def check_no_stdout(*cmd):
"""Log and run the command, suppress stdout & stderr, raising on errors."""
print >>sys.stderr, 'Run:', cmd
null = open(os.devnull, 'w')
subprocess.check_call(cmd, stdout=null, stderr=null)
def check_output(*cmd):
"""Log and run the command, raising on errors, return output"""
print >>sys.stderr, 'Run:', cmd
return subprocess.check_output(cmd)
def check_build_exists(gcs, suffix, fast):
""" check if a k8s/federation build with same version
already exists in remote path
"""
if not os.path.exists('hack/print-workspace-status.sh'):
print >>sys.stderr, 'hack/print-workspace-status.sh not found, continue'
return False
version = ''
try:
match = re.search(
r'gitVersion ([^\n]+)',
check_output('hack/print-workspace-status.sh')
)
if match:
version = match.group(1)
except subprocess.CalledProcessError as exc:
# fallback with doing a real build
print >>sys.stderr, 'Failed to get k8s version, continue: %s' % exc
return False
if version:
if not gcs:
gcs = 'kubernetes-release-dev'
gcs = 'gs://' + gcs
mode = 'ci'
if fast:
mode += '/fast'
if suffix:
mode += suffix
gcs = os.path.join(gcs, mode, version)
try:
check_no_stdout('gsutil', 'ls', gcs)
check_no_stdout('gsutil', 'ls', gcs + "/kubernetes.tar.gz")
check_no_stdout('gsutil', 'ls', gcs + "/bin")
return True
except subprocess.CalledProcessError as exc:
print >>sys.stderr, (
'gcs path %s (or some files under it) does not exist yet, continue' % gcs)
return False
def main(args):
# pylint: disable=too-many-branches
"""Build and push kubernetes.
This is a python port of the kubernetes/hack/jenkins/build.sh script.
"""
if os.path.split(os.getcwd())[-1] != 'kubernetes' and \
os.path.split(os.getcwd())[-1] != 'federation':
print >>sys.stderr, (
'Scenario should only run from either kubernetes or federation directory!')
sys.exit(1)
# pre-check if target build exists in gcs bucket or not
# if so, don't make duplicated builds
if check_build_exists(args.release, args.suffix, args.fast):
print >>sys.stderr, 'build already exists, exit'
sys.exit(0)
env = {
# Skip gcloud update checking; do we still need this?
'CLOUDSDK_COMPONENT_MANAGER_DISABLE_UPDATE_CHECK': 'true',
# Don't run any unit/integration tests when building
'KUBE_RELEASE_RUN_TESTS': 'n',
}
push_build_args = ['--nomock', '--verbose', '--ci']
if args.suffix:
push_build_args.append('--gcs-suffix=%s' % args.suffix)
if args.federation:
# TODO: do we need to set these?
env['PROJECT'] = args.federation
env['FEDERATION_PUSH_REPO_BASE'] = 'gcr.io/%s' % args.federation
push_build_args.append('--federation')
if args.release_kind:
push_build_args.append('--release-kind=%s' % args.release_kind)
if args.release:
push_build_args.append('--bucket=%s' % args.release)
if args.registry:
push_build_args.append('--docker-registry=%s' % args.registry)
if args.extra_publish_file:
push_build_args.append('--extra-publish-file=%s' % args.extra_publish_file)
if args.fast:
push_build_args.append('--fast')
if args.allow_dup:
push_build_args.append('--allow-dup')
if args.skip_update_latest:
push_build_args.append('--noupdatelatest')
if args.register_gcloud_helper:
# Configure docker client for gcr.io authentication to allow communication
# with non-public registries.
check_no_stdout('gcloud', 'auth', 'configure-docker')
for key, value in env.items():
os.environ[key] = value
check('make', 'clean')
if args.fast:
check('make', 'quick-release')
else:
check('make', 'release')
check(args.push_build_script, *push_build_args)
if __name__ == '__main__':
PARSER = argparse.ArgumentParser(
'Build and push.')
PARSER.add_argument('--fast', action='store_true', help='Build quickly')
PARSER.add_argument(
'--release', help='Upload binaries to the specified gs:// path')
PARSER.add_argument(
'--suffix', help='Append suffix to the upload path if set')
PARSER.add_argument(
'--federation',
help='Push federation images to the specified project')
PARSER.add_argument(
'--release-kind',
default='kubernetes',
help='The release kind to push to GCS. Supported values are kubernetes or federation')
PARSER.add_argument(
'--registry', help='Push images to the specified docker registry')
PARSER.add_argument(
'--extra-publish-file', help='Additional version file uploads to')
PARSER.add_argument(
'--fast', action='store_true', help='Specifies a fast build')
PARSER.add_argument(
'--allow-dup', action='store_true', help='Allow overwriting if the build exists on gcs')
PARSER.add_argument(
'--skip-update-latest', action='store_true', help='Do not update the latest file')
PARSER.add_argument(
'--push-build-script', default='../release/push-build.sh', help='location of push-build.sh')
PARSER.add_argument(
'--register-gcloud-helper', action='store_true',
help='Register gcloud as docker credentials helper')
ARGS = PARSER.parse_args()
main(ARGS)
|
Python
| 0
|
@@ -5188,85 +5188,8 @@
.')%0A
- PARSER.add_argument('--fast', action='store_true', help='Build quickly')%0A
|
b59fa7ea9648b654b40a68fdc79f546039aeb7d8
|
Update handling of APINAME variable in api_config_pattern variable (#105)
|
pipeline/pipelines/batch_generation_pipeline.py
|
pipeline/pipelines/batch_generation_pipeline.py
|
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Pipelines that run GAPIC"""
import yaml
import glob
from pipeline.pipelines import code_generation_pipeline as code_gen
from taskflow.patterns import linear_flow
from pipeline.utils import config_util, task_utils
class BatchPipeline(code_gen.CodeGenerationPipelineBase):
def __init__(self, make_pipeline_tasks_func, **kwargs):
task_factory = BatchTaskFactory(make_pipeline_tasks_func)
super(BatchPipeline, self).__init__(
task_factory, **kwargs)
class BatchTaskFactory(code_gen.TaskFactoryBase):
def __init__(self, make_pipeline_tasks_func):
self.make_pipeline_tasks_func = make_pipeline_tasks_func
super(BatchTaskFactory, self).__init__()
def get_tasks(self, **kwargs):
# TODO(michaelbausor): convert to unordered flow if necessary
batch_flow = linear_flow.Flow('BatchFlow')
for single_flow in self.get_language_api_flows(**kwargs):
batch_flow.add(single_flow)
# TODO(michaelbausor): add task to create Github PR once staging repo
# is public on Github
final_tasks = []
flow = [batch_flow]
flow += task_utils.instantiate_tasks(final_tasks, kwargs)
return flow
def get_language_api_flows(self, batch_apis, batch_languages,
api_config_pattern, artman_language_yaml,
**kwargs):
repo_root = kwargs['repo_root']
artman_config_yamls = _get_artman_config_filenames(
api_config_pattern, batch_apis)
for api_kwargs in _get_api_kwarg_dicts(
artman_config_yamls,
batch_languages,
artman_language_yaml,
repo_root):
api_kwargs.update(kwargs)
tasks = self.make_pipeline_tasks_func(**api_kwargs)
single_flow = linear_flow.Flow('SingleLanguageApiFlow')
single_flow.add(*tasks)
yield single_flow
def get_validate_kwargs(self, **kwargs):
return ['batch_apis', 'batch_languages', 'api_config_pattern',
'artman_language_yaml', 'stage_output']
def get_invalid_kwargs(self, **kwargs):
return ['language']
def _get_api_kwarg_dicts(
artman_config_yamls, batch_languages, artman_language_yaml, repo_root):
for language in _get_languages(artman_language_yaml, batch_languages):
lang_config = _load_artman_config(artman_language_yaml,
language,
repo_root)
# TODO(michaelbausor): change default to True once most API and
# language combinations are supported
if not lang_config.get('enable_batch_generation', False):
continue
for api_config_yaml in artman_config_yamls:
api_config = _load_artman_config(api_config_yaml,
language,
repo_root)
# TODO(michaelbausor): change default to True once most API and
# language combinations are supported
if not api_config.get('enable_batch_generation', False):
continue
api_kwargs = lang_config.copy()
api_kwargs.update(api_config)
api_kwargs['language'] = language
yield api_kwargs
def _get_languages(artman_language_yaml, batch_languages):
if batch_languages == '*':
with open(artman_language_yaml) as config_file:
batch_languages = sorted(yaml.load(config_file).keys())
if 'common' in batch_languages:
batch_languages.remove('common')
return batch_languages
else:
return batch_languages.split(',')
def _get_artman_config_filenames(api_config_pattern, batch_apis):
if batch_apis == '*':
return sorted(glob.glob(api_config_pattern))
else:
return [config_util.var_replace(api_config_pattern, {'APINAME': api})
for api in batch_apis.split(',')]
def _load_artman_config(artman_yaml, language, repo_root):
sections = ['common']
repl_vars = {'REPOROOT': repo_root}
return config_util.load_config_spec(
artman_yaml, sections, repl_vars, language)
|
Python
| 0.000001
|
@@ -4432,32 +4432,171 @@
ch_apis == '*':%0A
+ glob_pattern = config_util.var_replace(api_config_pattern,%0A %7B'API_SHORT_NAME': '*'%7D)%0A
return s
@@ -4611,26 +4611,20 @@
ob.glob(
-api_config
+glob
_pattern
@@ -4695,22 +4695,69 @@
pattern,
- %7B'API
+%0A %7B'API_SHORT_
NAME': a
|
24f546168b428580ccee05ba28f15e96fb5f64c9
|
Create a financial year
|
scorecard/tests/test_views.py
|
scorecard/tests/test_views.py
|
import json
from django.test import (
TransactionTestCase,
Client,
override_settings,
)
from . import (
import_data,
)
from .resources import (
GeographyResource,
MunicipalityProfileResource,
MedianGroupResource,
RatingCountGroupResource,
)
@override_settings(
SITE_ID=2,
STATICFILES_STORAGE="django.contrib.staticfiles.storage.StaticFilesStorage",
)
class GeographyDetailViewTestCase(TransactionTestCase):
serialized_rollback = True
def test_context(self):
# Import sample data
import_data(
GeographyResource,
"views/scorecard_geography.csv",
)
import_data(
MunicipalityProfileResource,
"views/municipality_profile.csv",
)
import_data(
MedianGroupResource,
"views/median_group.csv",
)
import_data(
RatingCountGroupResource,
"views/rating_count_group.csv",
)
# Make request
client = Client()
response = client.get("/profiles/municipality-CPT-city-of-cape-town/")
context = response.context
page_data = json.loads(context["page_data_json"])
# Test for amount types
self.assertIsInstance(page_data["amount_types_v1"], dict)
# Test for cube names
self.assertIsInstance(page_data["cube_names"], dict)
# Test for municipality category descriptions
self.assertIsInstance(page_data["municipal_category_descriptions"], dict)
|
Python
| 0.000002
|
@@ -4,16 +4,64 @@
ort json
+%0Afrom infrastructure.models import FinancialYear
%0A%0Afrom d
@@ -1013,32 +1013,104 @@
csv%22,%0A )%0A
+ FinancialYear.objects.create(budget_year=%222049/2050%22, active=1)%0A
# Make r
|
70482d032d1acef1570b16551bf170a0a271a7ec
|
Put the 'import *' back into test-settings.py
|
humbug/test-settings.py
|
humbug/test-settings.py
|
from settings import DATABASES
DATABASES['default']["NAME"] = "zephyr/tests/zephyrdb.test"
|
Python
| 0.000002
|
@@ -14,25 +14,17 @@
import
-DATABASES
+*
%0A%0ADATABA
|
7c74017bc0d76ecb34e3fab44767290f51d98a09
|
Decrease get_updates timeout for client test suite
|
humbug/test_settings.py
|
humbug/test_settings.py
|
from settings import *
DATABASES["default"] = {"NAME": "zephyr/tests/zephyrdb.test",
"ENGINE": "django.db.backends.sqlite3",
"OPTIONS": { "timeout": 20, },}
TORNADO_SERVER = 'http://localhost:9983'
|
Python
| 0
|
@@ -241,8 +241,142 @@
t:9983'%0A
+%0A# Decrease the get_updates timeout to 1 second.%0A# This allows CasperJS to proceed quickly to the next test step.%0APOLL_TIMEOUT = 1000%0A
|
9279930fa8153ca082728d3ac8479519c5db26b8
|
remove graph override=
|
hypergan/graph/graph.py
|
hypergan/graph/graph.py
|
from hypergan.util.ops import *
from hypergan.util.hc_tf import *
import tensorflow as tf
import hypergan.util.wavegan as wavegan
import hyperchamber as hc
TINY = 1e-12
class Graph:
def __init__(self, gan):
self.gan = gan
def generator(self, z, reuse=False):
config = self.gan.config
x_dims = config.x_dims
output_channels = config.channels
batch_size = config.batch_size
with(tf.variable_scope("generator", reuse=reuse)):
if 'y' in self.gan.graph:
z = tf.concat(axis=1, values=[z, self.gan.graph.y])
generator = hc.Config(hc.lookup_functions(config.generator))
nets = generator.create(generator, self.gan, z)
return nets
def discriminator(self, x, f,z,g,gz):
config = self.gan.config
graph = self.gan.graph
batch_size = config.batch_size*2
single_batch_size = config.batch_size
channels = config.channels
if self.gan.graph.xa is not None:
x = self.gan.graph.xa
print('---', x)
# combine to one batch, per Ian's "Improved GAN"
xs = [x]
gs = g
graph.xs=xs
graph.gs=gs
g = g[-1]
if len(gs) > 1:
for i in gs:
resized = tf.image.resize_images(xs[-1],[int(xs[-1].get_shape()[1]//2),int(xs[-1].get_shape()[2]//2)], 1)
xs.append(resized)
xs.pop()
gs.reverse()
discriminators = []
for i, discriminator in enumerate(config.discriminators):
discriminator = hc.Config(hc.lookup_functions(discriminator))
with(tf.variable_scope("discriminator")):
discriminators.append(discriminator.create(self.gan, discriminator, x, g, xs, gs,prefix="d_"+str(i)))
def split_d(net, i):
net = tf.slice(net, [single_batch_size*i, 0], [single_batch_size, -1])
return net
d_reals = [split_d(x, 0) for x in discriminators]
d_fakes = [split_d(x, 1) for x in discriminators]
net = tf.concat(axis=1, values=discriminators)
d_real = split_d(net, 0)
d_fake = split_d(net, 1)
return [d_real, d_fake, d_reals, d_fakes]
def create_z_encoding(self):
self.gan.graph.z = []
encoders = []
with(tf.variable_scope("encoder", reuse=False)):
for i, encoder in enumerate(self.gan.config.encoders):
encoder = hc.Config(hc.lookup_functions(encoder))
zs, z_base = encoder.create(encoder, self.gan)
encoders.append(zs)
self.gan.graph.z.append(z_base)
z_encoded = tf.concat(axis=1, values=encoders)
self.gan.graph.z_encoded = z_encoded
return z_encoded
# Used for building the tensorflow graph with only G
def create_generator(self, graph):
x = graph.x
f = graph.f
set_tensor("x", x)
config = self.gan.config
set_ops_globals(config.dtype, config.batch_size)
z = self.create_z_encoding()
graph.g = self.generator(args)
def create(self, graph):
x = graph.x
f = graph.f
config = self.gan.config
# This is a hack to set dtype across ops.py, since each tensorflow instruction needs a dtype argument
# TODO refactor
set_ops_globals(config.dtype, config.batch_size)
batch_size = config.batch_size
g_losses = []
extra_g_loss = []
d_losses = []
z = self.create_z_encoding()
# create generator
g = self.generator(z)
g_sample = g
with(tf.variable_scope("discriminator", reuse=False)):
d_real, d_fake, d_reals, d_fakes = self.discriminator(x, f, None, g, z)
self.gan.graph.d_real = d_real
self.gan.graph.d_fake = d_fake
self.gan.graph.d_reals = d_reals
self.gan.graph.d_fakes = d_fakes
for i, loss in enumerate(config.losses):
loss = hc.Config(hc.lookup_functions(loss))
d_loss, g_loss = loss.create(loss, self.gan)
if(d_loss is not None):
d_losses.append(tf.squeeze(d_loss))
if(g_loss is not None):
g_losses.append(tf.squeeze(g_loss))
g_reg_losses = [var for var in tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) if 'g_' in var.name]
d_reg_losses = [var for var in tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) if 'd_' in var.name]
extra_g_loss += g_reg_losses
g_loss = tf.reduce_mean(tf.add_n(g_losses))
for extra in extra_g_loss:
g_loss += extra
d_loss = tf.reduce_mean(tf.add_n(d_losses))
#for extra in d_reg_losses:
# d_loss += extra
joint_loss = tf.reduce_mean(tf.add_n(g_losses + d_losses))
summary = tf.global_variables()
def summary_reduce(s):
if(len(s.get_shape())==0):
return s
while(len(s.get_shape())>1):
s=tf.reduce_mean(s,1)
#s=tf.squeeze(s)
return tf.reduce_mean(s,0)
summary = [(s.get_shape(), s.name, s.dtype, summary_reduce(s)) for s in summary]
graph.d_loss=d_loss
graph.d_log=-tf.log(tf.abs(d_loss+TINY))
graph.f=f
graph.g=g_sample
graph.g_loss=g_loss
graph.hc_summary=summary
graph.joint_loss=joint_loss
g_vars = [var for var in tf.trainable_variables() if 'g_' in var.name]
d_vars = [var for var in tf.trainable_variables() if 'd_' in var.name]
v_vars = [var for var in tf.trainable_variables() if 'v_' in var.name]
g_vars += v_vars
trainer = hc.Config(hc.lookup_functions(config.trainer))
g_optimizer, d_optimizer = trainer.create(trainer, self.gan, d_vars, g_vars)
graph.d_optimizer=d_optimizer
graph.g_optimizer=g_optimizer
|
Python
| 0
|
@@ -975,84 +975,8 @@
els%0A
- if self.gan.graph.xa is not None:%0A x = self.gan.graph.xa%0A
|
1c472ee60b69c0ce629b456d26c8b585d67d02cb
|
Fix badges with static text
|
indico/modules/events/registration/badges.py
|
indico/modules/events/registration/badges.py
|
# This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico 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.
#
# Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals, division
import re
from collections import namedtuple
from itertools import izip, product
from reportlab.lib.units import cm
from reportlab.lib.utils import ImageReader
from indico.modules.designer.pdf import DesignerPDFBase
from indico.modules.events.registration.models.registrations import Registration
from indico.modules.events.registration.settings import DEFAULT_BADGE_SETTINGS
from indico.util.i18n import _
from indico.util.placeholders import get_placeholders
FONT_SIZE_RE = re.compile(r'(\d+)(pt)?')
ConfigData = namedtuple('ConfigData', list(DEFAULT_BADGE_SETTINGS))
def _get_font_size(text):
return int(FONT_SIZE_RE.match(text).group(1))
class RegistrantsListToBadgesPDF(DesignerPDFBase):
def __init__(self, template, config, event, registration_ids):
super(RegistrantsListToBadgesPDF, self).__init__(template, config)
self.event = event
self.registrations = (Registration.find(Registration.id.in_(registration_ids), Registration.is_active,
Registration.event_new == event)
.order_by(*Registration.order_by_name).all())
def _build_config(self, config_data):
return ConfigData(**config_data)
def _iter_position(self, canvas, n_horizonal, n_vertical):
"""Go over every possible position on the page."""
config = self.config
tpl_data = self.tpl_data
while True:
for n_x, n_y in product(xrange(n_horizonal), xrange(n_vertical)):
yield (config.left_margin + n_x * (tpl_data.width_cm + config.margin_columns),
config.top_margin + n_y * (tpl_data.height_cm + config.margin_rows))
canvas.showPage()
def _build_pdf(self, canvas):
config = self.config
tpl_data = self.tpl_data
available_width = self.width - (config.left_margin - config.right_margin + config.margin_columns + 0.01) * cm
n_horizontal = int(available_width / ((tpl_data.width_cm + config.margin_columns) * cm))
available_height = self.height - (config.top_margin - config.bottom_margin + config.margin_rows + 0.01) * cm
n_vertical = int(available_height / ((tpl_data.height_cm + config.margin_rows) * cm))
if not (n_horizontal and n_vertical):
raise ValueError(_("The template dimensions are too large for the page size you selected"))
# Print a badge for each registration
for registration, (x, y) in izip(self.registrations, self._iter_position(canvas, n_horizontal, n_vertical)):
self._draw_badge(canvas, registration, x * cm, y * cm)
def _draw_badge(self, canvas, registration, pos_x, pos_y):
"""Draw a badge for a given registration, at position pos_x, pos_y (top-left corner)."""
config = self.config
tpl_data = self.tpl_data
badge_rect = (pos_x, self.height - pos_y - tpl_data.height_cm * cm,
tpl_data.width_cm * cm, tpl_data.height_cm * cm)
if config.dashed_border:
canvas.saveState()
canvas.setDash(1, 5)
canvas.rect(*badge_rect)
canvas.restoreState()
if self.template.background_image:
with self.template.background_image.open() as f:
self._draw_background(canvas, ImageReader(f), *badge_rect)
placeholders = get_placeholders('designer-fields')
for item in tpl_data.items:
placeholder = placeholders.get(item['type'])
if placeholder:
if placeholder.group == 'registrant':
text = placeholder.render(registration)
else:
text = placeholder.render(registration.event_new)
elif tpl_data.text:
text = tpl_data.text
self._draw_item(canvas, item, text, pos_x, pos_y)
|
Python
| 0.000001
|
@@ -4543,29 +4543,28 @@
elif
-tpl_data.
+item%5B'
text
+'%5D
:%0A
@@ -4584,21 +4584,20 @@
t =
-tpl_data.
+item%5B'
text
+'%5D
%0A%0A
|
cd9374fba293f504e1b0a1112ca212fff77da7ef
|
Update plotlog.py
|
benchmark/paddle/image/plotlog.py
|
benchmark/paddle/image/plotlog.py
|
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import argparse
import matplotlib.pyplot as plt
def parse_args():
parser = argparse.ArgumentParser('Parse Log')
parser.add_argument(
'--file_path', '-f', type=str, help='the path of the log file')
parser.add_argument(
'--sample_rate',
'-s',
type=float,
default=1.0,
help='the rate to take samples from log')
parser.add_argument(
'--log_period', '-p', type=int, default=1, help='the period of log')
args = parser.parse_args()
return args
def parse_file(file_name):
loss = []
error = []
with open(file_name) as f:
for i, line in enumerate(f):
line = line.strip()
if not line.startswith('pass'):
continue
line_split = line.split(' ')
if len(line_split) != 5:
continue
loss_str = line_split[2][:-1]
cur_loss = float(loss_str.split('=')[-1])
loss.append(cur_loss)
err_str = line_split[3][:-1]
cur_err = float(err_str.split('=')[-1])
error.append(cur_err)
accuracy = [1.0 - err for err in error]
return loss, accuracy
def sample(metric, sample_rate):
interval = int(1.0 / sample_rate)
if interval > len(metric):
return metric[:1]
num = len(metric) / interval
idx = [interval * i for i in range(num)]
metric_sample = [metric[id] for id in idx]
return metric_sample
def plot_metric(metric, batch_id, graph_title, line_style='b-',
line_label='y',
line_num=1):
plt.figure()
plt.title(graph_title)
if line_num == 1:
plt.plot(batch_id, metric, line_style, line_label)
else:
for i in line_num:
plt.plot(batch_id, metric[i], line_style[i], line_label[i])
plt.xlabel('batch')
plt.ylabel(graph_title)
plt.legend()
plt.savefig(graph_title + '.jpg')
plt.close()
def main():
args = parse_args()
assert args.sample_rate > 0. and args.sample_rate <= 1.0, "The sample rate should in the range (0, 1]."
loss, accuracy = parse_file(args.file_path)
batch = [args.log_period * i for i in range(len(loss))]
batch_sample = sample(batch, args.sample_rate)
loss_sample = sample(loss, args.sample_rate)
accuracy_sample = sample(accuracy, args.sample_rate)
plot_metric(loss_sample, batch_sample, 'loss', line_label='loss')
plot_metric(accuracy_sample, batch_sample, 'accuracy', line_style='g-', line_label='accuracy')
if __name__ == '__main__':
main()
|
Python
| 0.000001
|
@@ -2105,48 +2105,8 @@
ric,
- batch_id, graph_title, line_style='b-',
%0A
@@ -2110,32 +2110,42 @@
+batch_id,%0A
@@ -2135,32 +2135,46 @@
%0A
+ graph_title,%0A
@@ -2182,50 +2182,52 @@
ine_
-label='y',%0A
+style='b-',%0A line_label='y',%0A
@@ -2403,24 +2403,30 @@
or i in
+range(
line_num
:%0A
@@ -2417,16 +2417,17 @@
line_num
+)
:%0A
@@ -3135,34 +3135,82 @@
ple,
- batch_sample, 'accuracy',
+%0A batch_sample,%0A 'accuracy',%0A
lin
@@ -3222,16 +3222,32 @@
le='g-',
+%0A
line_la
|
dfcc76dc1b3ca01859401bea4573d63ffadb419c
|
test group api DELETE method is not allowed for admin
|
billjobs/tests/tests_group_api.py
|
billjobs/tests/tests_group_api.py
|
from rest_framework import status
from billjobs.tests.generics import GenericAPIStatusCode
class GroupAPIAnonymousStatusCode(GenericAPIStatusCode):
"""
Tests status code returned by /groups endpoint for anonymous user
Permissions are tested in tests_api.py
"""
def setUp(self):
super().setUp()
self.url = self.endpoints['groups']
self.data = {'name': 'group name'}
def test_api_group_put_is_405(self):
"""
Test group api with PUT method return HTTP_405_METHOD_NOT_ALLOWED
"""
super().status_code_is(
'PUT', self.url, self.data, status.HTTP_405_METHOD_NOT_ALLOWED)
def test_api_group_delete_is_405(self):
"""
Test group api with DELETE method return HTTP_405_METHOD_NOT_ALLOWED
"""
super().status_code_is(
'DELETE', self.url, None, status.HTTP_405_METHOD_NOT_ALLOWED)
class GroupAPIUserStatusCode(GenericAPIStatusCode):
"""
Tests status code returned by /groups endpoint for user
Permissions are tested in tests_api.py
"""
def setUp(self):
super().setUp()
super().force_authenticate(self.user)
self.url = self.endpoints['groups']
self.data = {'name': 'group name'}
def test_api_group_put_is_405(self):
"""
Test group api with PUT method return HTTP_405_METHOD_NOT_ALLOWED
"""
super().status_code_is(
'PUT', self.url, self.data, status.HTTP_405_METHOD_NOT_ALLOWED)
def test_api_group_delete_is_405(self):
"""
Test group api with DELETE method return HTTP_405_METHOD_NOT_ALLOWED
"""
super().status_code_is(
'DELETE', self.url, None, status.HTTP_405_METHOD_NOT_ALLOWED)
class GroupAPIAdminStatusCode(GenericAPIStatusCode):
"""
Tests status code returned by /groups endpoint for admin
"""
def setUp(self):
super().setUp()
super().force_authenticate(self.admin)
self.url = self.endpoints['groups']
self.data = {'name': 'group name'}
def test_api_group_put_is_405(self):
"""
Test group api with PUT method return HTTP_405_METHOD_NOT_ALLOWED
"""
super().status_code_is(
'PUT', self.url, self.data, status.HTTP_405_METHOD_NOT_ALLOWED)
|
Python
| 0.000001
|
@@ -2314,28 +2314,322 @@
TTP_405_METHOD_NOT_ALLOWED)%0A
+%0A def test_api_group_delete_is_405(self):%0A %22%22%22%0A Test group api with DELETE method return HTTP_405_METHOD_NOT_ALLOWED%0A %22%22%22%0A super().status_code_is(%0A 'DELETE', self.url, self.data,%0A status.HTTP_405_METHOD_NOT_ALLOWED%0A )%0A
|
4e539a2c35484fedbee2284e894b2e60635de83c
|
create initial models
|
mdot/models.py
|
mdot/models.py
|
from django.db import models
# Create your models here.
|
Python
| 0.000001
|
@@ -26,32 +26,1780 @@
els%0A
-%0A# Create your models here.%0A
+from django.contrib.auth.models import User%0Afrom django.forms import ModelForm%0A%0A# Create your models here.%0A%0Aclass Sponsor(models.Model):%0A name = models.CharField(max_length = 50)%0A netid = models.CharField(max_length = 8)%0A title = models.CharField(max_length = 50)%0A email = models.EmailField(max_length = 30)%0A department = models.CharField(max_length = 30)%0A unit = models.CharField(max_length = 30)%0A%0A%0Aclass Manager(models.Model):%0A name = models.CharField(max_length = 50)%0A netid = models.CharField(max_length = 8)%0A%0A%0Aclass App(models.Model):%0A # define plarforms%0A name = models.CharField(max_length = 50)%0A primary_language = models.CharField(max_length = 20) # are we using abbreviations?%0A request_date = models.DateTimeField(auto_now_add = True)%0A requester = models.ForeignKey(User)%0A app_manager = models.ForeignKey(Manager)%0A app_sponsor = models.ForeignKey(Sponsor)%0A app_sponser_agreed_date = models.DateTimeField(auto_now = True)%0A app_sponser_agreed = models.BooleanField(default = False)%0A%0A%0Aclass Agreement(models.Model):%0A app = models.ForeignKey(App)%0A agree_time = models.DateTimeField(auto_now_add = True)%0A%0A%0Aclass SponsorForm(ModelForm):%0A class Meta:%0A model = Sponsor%0A fields = '__all__'%0A labels = %7B%0A %7D%0A help_texts = %7B%0A%0A %7D%0A error_messages = %7B%0A%0A %7D%0A%0A%0Aclass ManagerForm(ModelForm):%0A class Meta:%0A model = Manager%0A fields = '__all__'%0A labels = %7B%0A %7D%0A help_texts = %7B%0A%0A %7D%0A error_messages = %7B%0A%0A %7D%0A%0A%0Aclass AppForm(ModelForm):%0A class Meta:%0A model = App%0A fields = %5B'name', 'primary_language'%5D%0A labels = %7B%0A %7D%0A help_texts = %7B%0A%0A %7D%0A error_messages = %7B%0A%0A %7D
|
5e68e35bade60e1c291739123c3ee7b2905bc6cf
|
Remove leading and trailing whitespace from keyworder match groups.
|
lib/rapidsms/parsers/keyworder.py
|
lib/rapidsms/parsers/keyworder.py
|
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import re
class Keyworder(object):
TOKEN_MAP = [
("slug", "([a-z0-9\-]+)"),
("letters", "([a-z]+)"),
("numbers", "(\d+)"),
("whatever", "(.+)")]
def __init__(self):
self.regexen = []
self.prefix = ""
self.pattern = "^%s$"
def prepare(self, prefix, suffix):
# no prefix is defined, so match
# only the suffix (so simple!)
if prefix == "":
str = suffix
# we have a prefix, but no suffix,
# so accept JUST the prefix
elif suffix == "":
str = prefix
# the most common case; we have both a
# prefix and suffix, so simpley join
# them with a space
else: str = prefix + " " + suffix
# also assume that one space means
# "any amount of whitespace"
str = str.replace(" ", "\s+")
# replace friendly tokens with real chunks
# of regex, to make the patterns more readable
for token, regex in self.TOKEN_MAP:
str = str.replace("(%s)" % token, regex)
return re.compile(self.pattern % str, re.IGNORECASE)
def __call__(self, *regex_strs):
def decorator(func):
# make the current prefix into something
# iterable (so multiple prefixes can be
# specified as list, or single as string)
prefixen = self.prefix
if not hasattr(self.prefix, "__iter__"):
prefixen = [self.prefix]
# store all of the regular expressions which
# will match this function, as attributes on
# the function itself
if not hasattr(func, "regexen"):
setattr(func, "regexen", [])
# iterate and add all combinations of
# prefix and regex for this keyword
for prefix in prefixen:
for rstr in regex_strs:
regex = self.prepare(prefix, rstr)
getattr(func, "regexen").append(regex)
#print "Handler: %s" % regex.pattern
self.regexen.append((regex, func))
return func
return decorator
def match(self, sself, str):
for pat, func in self.regexen:
match = pat.match(str)
if match:
return (func, match.groups())
# TODO proper logging??
#print "No method called %s" % (str)
# a semantic way to add a default
# handler (when nothing else is matched)
def blank(self):
return self.__call__("")
# another semantic way to add a catch-all
# most useful with a prefix for catching
# invalid syntax and responding with help
def invalid(self):
return self.__call__("(whatever)")
|
Python
| 0
|
@@ -2396,36 +2396,153 @@
-return (func, match.groups()
+# clean up leading and trailing whitespace%0A groups = map(lambda x: x.strip(), match.groups())%0A return (func, groups
)%0A
|
f3bdf87a7c615647673a20d21b35c06bccb44db0
|
Fix instrumentation for commands when running admin script.
|
instrument.py
|
instrument.py
|
from newrelic.agent import (background_task, function_trace,
add_custom_parameter, wrap_function_trace, wrap_background_task,
wrap_function_wrapper, current_transaction, ExternalTrace,
FunctionTraceWrapper)
def wrapper_register_ip(wrapped, instance, args, kwargs):
def _bind_params(domain, hostname, ipaddr):
return domain, hostname, ipaddr
domain, hostname, ipaddr = _bind_params(*args, **kwargs)
add_custom_parameter('domain', domain)
add_custom_parameter('hostname', hostname)
add_custom_parameter('ipaddr', ipaddr)
return wrapped(*args, **kwargs)
def instrument_dyndns53(module):
wrap_function_trace(module, 'initialise_database')
wrap_function_trace(module, 'download_database')
wrap_function_trace(module, 'upload_database')
wrap_function_trace(module, 'register_ip')
wrap_function_trace(module, 'BasicAuthDatabase.check_credentials')
wrap_background_task(module, 'upload_database_command')
wrap_background_task(module, 'download_database_command')
wrap_function_wrapper(module, 'register_ip', wrapper_register_ip)
def wrap_object_function_traces(obj, names):
for name in names:
setattr(obj, name, FunctionTraceWrapper(getattr(obj, name)))
def wrapper_AWSAuthConnection_make_request(wrapped, instance, args, kwargs):
transaction = current_transaction()
if transaction is None:
return wrapped(*args, **kwargs)
def _bind_params(method, path, *args, **kwargs):
return method, path
method, path = _bind_params(*args, **kwargs)
url = '%s://%s%s' % (instance.protocol, instance.host, path)
with ExternalTrace(transaction, 'boto', url, method):
return wrapped(*args, **kwargs)
def instrument_boto_connection(module):
wrap_function_wrapper(module, 'AWSAuthConnection.make_request',
wrapper_AWSAuthConnection_make_request)
def instrument_boto_route53_connection(module):
wrap_object_function_traces(module.Route53Connection,
['get_all_hosted_zones', 'get_hosted_zone',
'get_hosted_zone_by_name', 'create_hosted_zone',
'delete_hosted_zone', 'get_all_rrsets', 'change_rrsets',
'get_change', 'create_zone', 'get_zone', 'get_zones'])
def instrument_boto_s3_bucket(module):
wrap_object_function_traces(module.Bucket,
['get_key', 'list', 'list_versions', 'list_multipart_uploads',
'get_all_keys', 'get_all_versions', 'get_all_multipart_uploads',
'new_key', 'delete_keys', 'delete_key', 'copy_key',
'set_canned_acl', 'get_xml_acl', 'set_xml_acl', 'set_acl',
'get_acl', 'set_subresource', 'get_subresource', 'make_public',
'add_email_grant', 'add_user_grant', 'list_grants',
'get_location', 'set_xml_logging', 'enable_logging',
'disable_logging', 'get_logging_status', 'set_as_logging_target',
'get_request_payment', 'set_request_payment',
'configure_versioning', 'get_versioning_status',
'configure_lifecycle', 'get_lifecycle_config',
'delete_lifecycle_configuration', 'configure_website',
'set_website_configuration', 'set_website_configuration_xml',
'get_website_configuration', 'get_website_configuration_obj',
'get_website_configuration_with_xml',
'get_website_configuration_xml',
'delete_website_configuration', 'get_website_endpoint',
'get_policy', 'set_policy', 'delete_policy', 'set_cors_xml',
'set_cors', 'get_cors_xml', 'get_cors', 'delete_cors',
'initiate_multipart_upload', 'complete_multipart_upload',
'cancel_multipart_upload', 'delete', 'get_tags', 'get_xml_tags',
'set_xml_tags', 'set_tags', 'delete_tags'])
def instrument_boto_s3_connection(module):
wrap_object_function_traces(module.S3Connection,
['get_all_buckets', 'get_canonical_user_id', 'get_bucket',
'lookup', 'create_bucket', 'delete_bucket'])
def instrument_boto_s3_key(module):
wrap_object_function_traces(module.Key,
['open_read', 'open', 'close', 'change_storage_class', 'copy',
'exists', 'delete', 'set_acl', 'get_acl', 'get_xml_acl',
'set_xml_acl', 'set_canned_acl', 'get_redirect',
'set_redirect', 'make_public', 'send_file',
'set_contents_from_stream', 'set_contents_from_file',
'set_contents_from_filename', 'set_contents_from_string',
'get_file', 'get_torrent_file', 'get_contents_to_file',
'get_contents_to_filename', 'get_contents_as_string',
'add_email_grant', 'add_user_grant', 'set_remote_metadata',
'restore'])
def instrument_boto(module):
wrap_object_function_traces(module, ['connect_s3', 'connect_route53'])
|
Python
| 0
|
@@ -105,22 +105,17 @@
_trace,
-wrap_b
+B
ackgroun
@@ -115,21 +115,27 @@
ckground
-_t
+T
ask
+Wrapper
,%0A
@@ -932,190 +932,191 @@
rap_
-background_task(module, 'upload_database_command')%0A wrap_background_task(module, 'download_database_command')%0A%0A wrap_function_wrapper(module, 'register_ip', wrapper_register_ip
+function_wrapper(module, 'register_ip', wrapper_register_ip)%0A%0A for name, callback in list(module._commands.items()):%0A module._commands%5Bname%5D = BackgroundTaskWrapper(callback
)%0A%0Ad
|
c3cc948ceede66a70eadc300e558a42c8b06769b
|
Update change_names_miseq.py
|
scripts/change_names_miseq.py
|
scripts/change_names_miseq.py
|
#import sys
import os
import argparse
import shutil
parser = argparse.ArgumentParser(description='This program takes Miseq fastq files and renames them as sample.read_direction.#.fastq and keeps a log of the change')
parser.add_argument('-s',action='store',dest='s',help='The sorce directory containing the original fastq files')
parser.add_argument('-f',action='store',dest='f',help='The final directory that will hold the renamed fastq files')
parser.add_argument('-run',action='store_true',dest='test',default=False,help='Boolean switch to run program, without this the program runs in test mode: the log is made but no files are renamed')
parser.add_argument('-gz',action='store_true',dest='zip',default=False,help='Boolean switch. Activate when working with .gz files')
args=parser.parse_args()
s=args.s
f=args.f
test=args.test
zip=args.zip
# input argument is fastq directory
if not os.path.exists(f):
os.makedirs(f)
outfile = open(f+'renaming_log.txt','w')
#os.chdir(sys.argv[1])
if test==False:
print "running in test mode add option -r to run"
for filename in os.listdir(s):
print filename
name=filename.split("_L")
good_name = name[0].split("_")[0]
lane_junk = name[1]
read_number=lane_junk.split("_R")
fastq_number=read_number[1][4]
read_number=read_number[1][0]
if zip==True:
perfect_name= good_name.replace("-","_")+"."+read_number+"."+fastq_number+".fastq.gz"
else:
perfect_name= good_name.replace("-","_")+"."+read_number+"."+fastq_number+".fastq"
# Write file to new name
print("COPYING "+ s+filename + " to "+f+perfect_name)
outfile.write(s+filename + "\t COPIED to \t" + f+perfect_name + "\n")
if test==True:
shutil.copy(s+filename,f+perfect_name)
outfile.close()
|
Python
| 0
|
@@ -1090,16 +1090,17 @@
ir(s):%0A
+#
print
|
9a7fe0e881298dc92a97782586508dec249fa53e
|
Fix the breaking PayPal tests caused by card expiration in the past.
|
billing/tests/pay_pal_tests.py
|
billing/tests/pay_pal_tests.py
|
from django.test import TestCase
from billing import get_gateway, get_integration, CreditCard
from billing.signals import *
from paypal.pro.models import PayPalNVP
from billing.gateway import CardNotSupported
from billing.utils.credit_card import Visa
from paypal.pro.tests import RequestFactory
from django.template import Template, Context
from django.utils.html import strip_spaces_between_tags
from django.core.urlresolvers import reverse
import datetime
RF = RequestFactory()
request = RF.get("/", REMOTE_ADDR="192.168.1.1")
fake_options = {
"request": request,
"email": "testuser@fakedomain.com",
"billing_address": {
"name": "PayPal User",
"address1": "Street 1",
"city": "Mountain View",
"state": "CA",
"country": "US",
"zip": "94043"
},
# "shipping_address": {
# "name": "PayPal User",
# "address1": "Street 1",
# "city": "Mountain View",
# "state": "CA",
# "country": "US",
# "zip": "94043"
# },
}
class PayPalGatewayTestCase(TestCase):
def setUp(self):
self.merchant = get_gateway("pay_pal")
self.merchant.test_mode = True
self.credit_card = CreditCard(first_name="Test", last_name="User",
month=10, year=2011,
number="4500775008976759",
verification_value="000")
def testCardSupported(self):
self.credit_card.number = "5019222222222222"
self.assertRaises(CardNotSupported,
lambda : self.merchant.purchase(1000, self.credit_card))
def testCardValidated(self):
self.merchant.test_mode = False
self.credit_card.number = "4222222222222123"
self.assertFalse(self.merchant.validate_card(self.credit_card))
def testCardType(self):
self.merchant.validate_card(self.credit_card)
self.assertEquals(self.credit_card.card_type, Visa)
def testPurchase(self):
resp = self.merchant.purchase(1, self.credit_card,
options = fake_options)
self.assertEquals(resp["status"], "SUCCESS")
self.assertNotEquals(resp["response"].correlationid, "0")
self.assertTrue(isinstance(resp["response"], PayPalNVP))
def testPaymentSuccessfulSignal(self):
received_signals = []
def receive(sender, **kwargs):
received_signals.append(kwargs.get("signal"))
transaction_was_successful.connect(receive)
resp = self.merchant.purchase(1, self.credit_card,
options = fake_options)
self.assertEquals(received_signals, [transaction_was_successful])
def testPaymentUnSuccessfulSignal(self):
received_signals = []
def receive(sender, **kwargs):
received_signals.append(kwargs.get("signal"))
transaction_was_unsuccessful.connect(receive)
resp = self.merchant.purchase(105.02, self.credit_card,
options = fake_options)
self.assertEquals(received_signals, [transaction_was_unsuccessful])
def testCreditCardExpired(self):
resp = self.merchant.purchase(105.02, self.credit_card,
options = fake_options)
self.assertNotEquals(resp["status"], "SUCCESS")
class PayPalWebsiteStandardsTestCase(TestCase):
urls = "billing.tests.test_urls"
def setUp(self):
self.today = datetime.datetime.today().strftime("%Y-%m-%d")
self.pws = get_integration("pay_pal")
self.pws.test_mode = True
fields = {"cmd": "_xclick",
'notify_url': 'http://localhost/paypal-ipn-handler/',
'return_url': 'http://localhost/offsite/paypal/done/',
'cancel_return': 'http://localhost/offsite/paypal/',
'amount': 1,
'item_name': "Test Item",
'invoice': self.today,}
self.pws.add_fields(fields)
def testRenderForm(self):
tmpl = Template("{% load billing_tags %}{% paypal obj %}")
form = tmpl.render(Context({"obj": self.pws}))
pregen_form = """<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post"><input type="hidden" name="business" value="probiz_1273571007_biz@uswaretech.com" id="id_business" /><input type="hidden" name="amount" value="1" id="id_amount" /><input type="hidden" name="item_name" value="Test Item" id="id_item_name" /><input type="hidden" name="notify_url" value="http://localhost/paypal-ipn-handler/" id="id_notify_url" /><input type="hidden" name="cancel_return" value="http://localhost/offsite/paypal/" id="id_cancel_return" /><input type="hidden" name="return" value="http://localhost/offsite/paypal/done/" id="id_return_url" /><input type="hidden" name="invoice" value="%(today)s" id="id_invoice" /><input type="hidden" name="cmd" value="_xclick" id="id_cmd" /><input type="hidden" name="charset" value="utf-8" id="id_charset" /><input type="hidden" name="currency_code" value="USD" id="id_currency_code" /><input type="hidden" name="no_shipping" value="1" id="id_no_shipping" /><input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="Buy it Now" /></form>""" % ( {"today": self.today} )
self.assertEquals(pregen_form, strip_spaces_between_tags(form).strip())
def testIPNURLSetup(self):
self.assertEquals(reverse("paypal-ipn"), "/paypal-ipn-url/")
|
Python
| 0
|
@@ -1308,17 +1308,17 @@
year=201
-1
+7
, %0A
|
6d0bc825a1fd9184bf7b4007bfa82b69e5c7cb35
|
fix search to use sites
|
binstar_client/commands/search.py
|
binstar_client/commands/search.py
|
'''
Search binstar for packages
'''
from binstar_client.utils import get_binstar
from binstar_client.utils.pprint import pprint_packages
import logging
log = logging.getLogger('binstar.search')
def search(args):
binstar = get_binstar()
log.info("Run 'binstar show <USER/PACKAGE>' to get more details:")
packages = binstar.search(args.name, package_type=args.package_type)
pprint_packages(packages)
log.info("Found %i packages" % len(packages))
def add_parser(subparsers):
parser1 = subparsers.add_parser('search',
help='Search binstar',
description=__doc__)
parser1.add_argument('name', nargs=1, help='Search string')
parser1.add_argument('-t', '--package-type', choices=['conda', 'pypi'],
help='only search for packages of this type')
parser1.set_defaults(main=search)
|
Python
| 0
|
@@ -206,20 +206,16 @@
(args):%0A
-
%0A bin
@@ -233,17 +233,22 @@
binstar(
-)
+args)%0A
%0A log
|
83e071dd64807d1064fdd60ee0788f385b5f9334
|
Remove noise
|
bin/symlinks.py
|
bin/symlinks.py
|
#! /usr/bin/env python
import os
import fnmatch
def link(source, dest):
try:
if not os.path.exists(dest):
print("linking " + source + " to " + dest)
os.symlink(source,dest)
except:
print("fail")
def dotlink(source):
dest = os.environ['HOME'] + "/." + os.path.basename(source.split('.symlink')[0])
if os.path.exists(dest):
current_target = os.path.realpath(dest)
if current_target != source:
link(source,dest)
else:
print("skipping " + source + " already links to " + dest)
else:
link(source,dest)
def find(pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
for name in dirs:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
def setup():
dotfiles_root = os.environ['HOME'] + '/dotfiles'
print("Finding linkables...")
linkables = find('*.symlink', dotfiles_root)
print("Done.")
for x in linkables:
dotlink(x)
if __name__ == "__main__":
setup()
|
Python
| 0.000094
|
@@ -493,92 +493,8 @@
st)%0A
- else:%0A print(%22skipping %22 + source + %22 already links to %22 + dest)%0A
|
f2235451f014019f08b53ffa962529dc3bfb4f87
|
simplify the on_change method as suggested by O. Dony
|
addons/sale_order_dates/sale_order_dates.py
|
addons/sale_order_dates/sale_order_dates.py
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# 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/>.
#
##############################################################################
from datetime import datetime, timedelta
from osv import fields, osv
from tools.translate import _
from tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT
class sale_order_dates(osv.osv):
"""Add several date fields to Sale Orders, computed or user-entered"""
_inherit = 'sale.order'
def copy(self, cr, uid, id, default=None, context=None):
"""Don't copy the requested date along with the Sale Order"""
if default is None:
default = {}
else:
default = default.copy()
default['requested_date'] = False
return super(sale_order_dates, self).copy(cr, uid, id, default=default,
context=context)
def _order_line_move_date(self, cr, uid, line):
"""Compute the expected date from the requested date, not the order date"""
order=line.order_id
if order and order.requested_date:
date_planned = datetime.strptime(order.requested_date,
DEFAULT_SERVER_DATE_FORMAT)
date_planned -= timedelta(days=order.company_id.security_lead)
return date_planned.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
else:
return super(sale_order_dates, self)._order_line_move_date(cr, uid, line)
def _get_effective_date(self, cr, uid, ids, name, arg, context=None):
"""Read the shipping date from the related packings"""
# XXX would be better if it returned the date the picking was processed
res = {}
dates_list = []
for order in self.browse(cr, uid, ids, context=context):
dates_list = []
for pick in order.picking_ids:
dates_list.append(pick.date)
if dates_list:
res[order.id] = min(dates_list)
else:
res[order.id] = False
return res
def _get_commitment_date(self, cr, uid, ids, name, arg, context=None):
"""Compute the commitment date"""
res = {}
dates_list = []
for order in self.browse(cr, uid, ids, context=context):
dates_list = []
for line in order.order_line:
dt = (datetime.strptime(order.date_order,
DEFAULT_SERVER_DATE_FORMAT)
+ timedelta(days=line.delay or 0.0) )
dt_s = dt.strftime(DEFAULT_SERVER_DATE_FORMAT)
dates_list.append(dt_s)
if dates_list:
res[order.id] = min(dates_list)
return res
def onchange_requested_date(self, cr, uid, ids, requested_date,
commitment_date, context=None):
"""Warn if the requested dates is sooner than the commitment date"""
if (requested_date and commitment_date
and requested_date < commitment_date):
lang = self.pool.get("res.users").browse(cr, uid, uid,
context=context).context_lang
if lang:
lang_ids = self.pool.get('res.lang').search(cr, uid,
[('code', '=', lang)])
date_format = self.pool.get("res.lang").browse(cr, uid,
lang_ids, context=context)[0].date_format
# Parse the dates...
req_date_formated = datetime.strptime(requested_date,
DEFAULT_SERVER_DATE_FORMAT)
com_date_formated = datetime.strptime(commitment_date,
DEFAULT_SERVER_DATE_FORMAT)
# ... and reformat them according to the user's language
req_date_formated = req_date_formated.strftime(date_format)
com_date_formated = com_date_formated.strftime(date_format)
else:
req_date_formated = requested_date
com_date_formated = commitment_date
return {'warning': {
'title': _('Requested date is too soon!'),
'message': _("The date requested by the customer (%s) is "
"sooner than the commitment date (%s). You may be "
"unable to honor the customer's request." %
(req_date_formated, com_date_formated))
}
}
else:
return {}
_columns = {
'commitment_date': fields.function(_get_commitment_date, store=True,
type='date', string='Commitment Date',
help="Date by which the products is sure to be delivered. This is "
"a date that you can promise to the customer, based on the "
"Product Lead Times."),
'requested_date': fields.date('Requested Date',
readonly=True, states={'draft': [('readonly', False)]},
help="Date by which the customer has requested the items to be "
"delivered.\n"
"When this Order gets confirmed, the Delivery Order's "
"expected date will be computed based on this date and the "
"Company's Security Delay.\n"
"Leave this field empty if you want the Delivery Order to be "
"processed as soon as possible. In that case the expected "
"date will be computed using the default method: based on "
"the Product Lead Times and the Company's Security Delay."),
'effective_date': fields.function(_get_effective_date, type='date',
store=True, string='Effective Date',
help="Date on which the first Delivery Order was created."),
}
sale_order_dates()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Python
| 0.001094
|
@@ -3906,1150 +3906,8 @@
e):%0A
- lang = self.pool.get(%22res.users%22).browse(cr, uid, uid,%0A context=context).context_lang%0A if lang:%0A lang_ids = self.pool.get('res.lang').search(cr, uid,%0A %5B('code', '=', lang)%5D)%0A date_format = self.pool.get(%22res.lang%22).browse(cr, uid,%0A lang_ids, context=context)%5B0%5D.date_format%0A # Parse the dates...%0A req_date_formated = datetime.strptime(requested_date,%0A DEFAULT_SERVER_DATE_FORMAT)%0A com_date_formated = datetime.strptime(commitment_date,%0A DEFAULT_SERVER_DATE_FORMAT)%0A # ... and reformat them according to the user's language%0A req_date_formated = req_date_formated.strftime(date_format)%0A com_date_formated = com_date_formated.strftime(date_format)%0A else:%0A req_date_formated = requested_date%0A com_date_formated = commitment_date%0A
@@ -4058,21 +4058,16 @@
customer
- (%25s)
is %22%0A
@@ -4129,13 +4129,8 @@
date
- (%25s)
. Yo
@@ -4214,83 +4214,8 @@
st.%22
- %25 %0A (req_date_formated, com_date_formated)
)%0A
|
6f7d0ce060a29af86bd7cf98de6b6b23bb248fdd
|
Add missing Bus import in can/__init__.py
|
cantools/database/can/__init__.py
|
cantools/database/can/__init__.py
|
from .database import Database
from .message import Message
from .message import EncodeError
from .message import DecodeError
from .signal import Signal
from .node import Node
|
Python
| 0.00005
|
@@ -169,8 +169,29 @@
rt Node%0A
+from .bus import Bus%0A
|
903130b5802f34f619187635fb4b205184abd3d9
|
Add an example check
|
example/example.py
|
example/example.py
|
import netuitive
import time
import os
ApiClient = netuitive.Client(url=os.environ.get('API_URL'), api_key=os.environ.get('CUSTOM_API_KEY'))
MyElement = netuitive.Element()
MyElement.add_attribute('Language', 'Python')
MyElement.add_attribute('app_version', '7.0')
MyElement.add_relation('my_child_element')
MyElement.add_tag('Production', 'True')
MyElement.add_tag('app_tier', 'True')
timestamp = int(time.mktime(time.localtime()))
MyElement.add_sample('app.error', timestamp, 1, host='appserver01')
MyElement.add_sample('app.request', timestamp, 10, host='appserver01')
ApiClient.post(MyElement)
MyElement.clear_samples()
MyEvent = netuitive.Event('appserver01', 'INFO', 'test event','this is a test message', 'INFO')
ApiClient.post_event(MyEvent)
if ApiClient.time_insync():
print('we have time sync with the server')
|
Python
| 0
|
@@ -754,16 +754,102 @@
Event)%0A%0A
+MyCheck = netuitive.Check('heartbeat', 'element', 60)%0A%0AApiClient.post_check(MyCheck)%0A%0A
if ApiCl
|
c01d7215ac2408af31ddb68c72590fcbe0b35739
|
Update application_initializations.py
|
niftynet/engine/application_initializations.py
|
niftynet/engine/application_initializations.py
|
import tensorflow as tf
from tensorflow.python.ops import init_ops
"""
all classes and docs are taken from
https://github.com/tensorflow/tensorflow/blob/r1.3/tensorflow/python/ops/init_ops.py
"""
class Constant(object):
@staticmethod
def get_instance(args):
value = float(args.get('value'), 0.0)
return tf.constant_initializer(value)
class Zeros(object):
@staticmethod
def get_instance(args):
return tf.constant_initializer(0.0)
class Ones(object):
@staticmethod
def get_instance(args):
return tf.constant_initializer(1.0)
#todo
#random_uniform_initializer = RandomUniform
#random_normal_initializer = RandomNormal
#truncated_normal_initializer = TruncatedNormal
class UniformUnitScaling(object):
"""Initializer that generates tensors without scaling variance.
When initializing a deep network, it is in principle advantageous to keep
the scale of the input variance constant, so it does not explode or diminish
by reaching the final layer. If the input is `x` and the operation `x * W`,
and we want to initialize `W` uniformly at random, we need to pick `W` from
[-sqrt(3) / sqrt(dim), sqrt(3) / sqrt(dim)]
to keep the scale intact, where `dim = W.shape[0]` (the size of the input).
A similar calculation for convolutional networks gives an analogous result
with `dim` equal to the product of the first 3 dimensions. When
nonlinearities are present, we need to multiply this by a constant `factor`.
See [Sussillo et al., 2014](https://arxiv.org/abs/1412.6558)
([pdf](http://arxiv.org/pdf/1412.6558.pdf)) for deeper motivation, experiments
and the calculation of constants. In section 2.3 there, the constants were
numerically computed: for a linear layer it's 1.0, relu: ~1.43, tanh: ~1.15.
Args:
factor: Float. A multiplicative factor by which the values will be scaled.
seed: A Python integer. Used to create random seeds. See
@{tf.set_random_seed}
for behavior.
dtype: The data type. Only floating point types are supported.
"""
@staticmethod
def get_instance(args):
factor = float(args.get('factor'),1.0)
return init_ops.uniform_unit_scaling_initializer(factor)
class Orthogonal(object):
"""Initializer that generates an orthogonal matrix.
If the shape of the tensor to initialize is two-dimensional, i is initialized
with an orthogonal matrix obtained from the singular value decomposition of a
matrix of uniform random numbers.
If the shape of the tensor to initialize is more than two-dimensional,
a matrix of shape `(shape[0] * ... * shape[n - 2], shape[n - 1])`
is initialized, where `n` is the length of the shape vector.
The matrix is subsequently reshaped to give a tensor of the desired shape.
Args:
gain: multiplicative factor to apply to the orthogonal matrix
dtype: The type of the output.
seed: A Python integer. Used to create random seeds. See
@{tf.set_random_seed}
for behavior.
"""
@staticmethod
def get_instance(args):
gain = float(args.get('gain', 1.0))
return init_ops.orthogonal_initializer(gain)
class VarianceScaling(object):
"""Initializer capable of adapting its scale to the shape of weights tensors.
With `distribution="normal"`, samples are drawn from a truncated normal
distribution centered on zero, with `stddev = sqrt(scale / n)`
where n is:
- number of input units in the weight tensor, if mode = "fan_in"
- number of output units, if mode = "fan_out"
- average of the numbers of input and output units, if mode = "fan_avg"
With `distribution="uniform"`, samples are drawn from a uniform distribution
within [-limit, limit], with `limit = sqrt(3 * scale / n)`.
Arguments:
scale: Scaling factor (positive float).
mode: One of "fan_in", "fan_out", "fan_avg".
distribution: Random distribution to use. One of "normal", "uniform".
seed: A Python integer. Used to create random seeds. See
@{tf.set_random_seed}
for behavior.
dtype: The data type. Only floating point types are supported.
Raises:
ValueError: In case of an invalid value for the "scale", mode" or
"distribution" arguments.
"""
@staticmethod
def get_instance(args):
scale = float(args.get('scale', 1.0))
mode = args.get('mode', "fan_in")
assert(mode in ["fan_in", "fan_out", "fan_avg"])
distribution = args.get('distribution', "normal")
assert(distribution in ["normal", "uniform"])
return init_ops.variance_scaling_initializer(scale, mode, distribution)
class GlorotNormal(object):
"""The Glorot normal initializer, also called Xavier normal initializer.
It draws samples from a truncated normal distribution centered on 0
with `stddev = sqrt(2 / (fan_in + fan_out))`
where `fan_in` is the number of input units in the weight tensor
and `fan_out` is the number of output units in the weight tensor.
Reference: http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf
Arguments:
seed: A Python integer. Used to create random seeds. See
@{tf.set_random_seed}
for behavior.
dtype: The data type. Only floating point types are supported.
Returns:
An initializer.
"""
@staticmethod
def get_instance(args):
return init_ops.glorot_normal_initializer()
class GlorotUniform(object):
"""The Glorot uniform initializer, also called Xavier uniform initializer.
It draws samples from a uniform distribution within [-limit, limit]
where `limit` is `sqrt(6 / (fan_in + fan_out))`
where `fan_in` is the number of input units in the weight tensor
and `fan_out` is the number of output units in the weight tensor.
Reference: http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf
Arguments:
seed: A Python integer. Used to create random seeds. See
@{tf.set_random_seed}
for behavior.
dtype: The data type. Only floating point types are supported.
Returns:
An initializer.
"""
@staticmethod
def get_instance(args):
return init_ops.glorot_uniform_initializer()
|
Python
| 0.000001
|
@@ -303,15 +303,15 @@
lue'
-)
, 0.0)
+)
%0A
@@ -2173,14 +2173,14 @@
tor'
-)
,1.0)
+)
%0A
|
5869cd6bd043e9eee5bbddc4c2c82c9576c35535
|
error if customer without countries
|
addons/website_customer/controllers/main.py
|
addons/website_customer/controllers/main.py
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import werkzeug.urls
from odoo import http
from odoo.addons.website.models.website import unslug
from odoo.tools.translate import _
from odoo.http import request
class WebsiteCustomer(http.Controller):
_references_per_page = 20
@http.route([
'/customers',
'/customers/page/<int:page>',
'/customers/country/<int:country_id>',
'/customers/country/<country_name>-<int:country_id>',
'/customers/country/<int:country_id>/page/<int:page>',
'/customers/country/<country_name>-<int:country_id>/page/<int:page>',
'/customers/tag/<tag_id>',
'/customers/tag/<tag_id>/page/<int:page>',
'/customers/tag/<tag_id>/country/<int:country_id>',
'/customers/tag/<tag_id>/country/<country_name>-<int:country_id>',
'/customers/tag/<tag_id>/country/<int:country_id>/page/<int:page>',
'/customers/tag/<tag_id>/country/<country_name>-<int:country_id>/page/<int:page>',
], type='http', auth="public", website=True)
def customers(self, country_id=0, page=0, country_name='', tag_id=0, **post):
Country = request.env['res.country']
Tag = request.env['res.partner.tag']
Partner = request.env['res.partner']
partner_name = post.get('search', '')
domain = [('website_published', '=', True), ('assigned_partner_id', '!=', False)]
if partner_name:
domain += [
'|',
('name', 'ilike', post.get("search")),
('website_description', 'ilike', post.get("search"))
]
if tag_id:
tag_id = unslug(tag_id)[1] or 0
domain += [('tag_ids', 'in', tag_id)]
# group by country, based on customers found with the search(domain)
countries = Partner.sudo().read_group(domain, ["id", "country_id"], groupby="country_id", orderby="country_id")
country_count = Partner.sudo().search_count(domain)
if country_id:
domain += [('country_id', '=', country_id)]
curr_country = Country.browse(country_id)
if country_id not in map(lambda x: x['country_id'][0], countries):
if curr_country.exists():
countries.append({
'country_id_count': 0,
'country_id': (curr_country.id, curr_country.name)
})
countries.sort(key=lambda d: d['country_id'] and d['country_id'][1])
countries.insert(0, {
'country_id_count': country_count,
'country_id': (0, _("All Countries"))
})
# search customers to display
partner_count = Partner.sudo().search_count(domain)
# pager
url = '/customers'
if country_id:
url += '/country/%s' % country_id
pager = request.website.pager(
url=url, total=partner_count, page=page, step=self._references_per_page,
scope=7, url_args=post
)
partners = Partner.sudo().search(domain, offset=pager['offset'], limit=self._references_per_page)
google_map_partner_ids = ','.join(map(str, partners.ids))
google_maps_api_key = request.env['ir.config_parameter'].sudo().get_param('google_maps_api_key')
tags = Tag.search([('website_published', '=', True), ('partner_ids', 'in', partners.ids)], order='classname, name ASC')
tag = tag_id and Tag.browse(tag_id) or False
values = {
'countries': countries,
'current_country_id': country_id or 0,
'current_country': curr_country if country_id else False,
'partners': partners,
'google_map_partner_ids': google_map_partner_ids,
'pager': pager,
'post': post,
'search_path': "?%s" % werkzeug.url_encode(post),
'tag': tag,
'tags': tags,
'google_maps_api_key': google_maps_api_key,
}
return request.render("website_customer.index", values)
# Do not use semantic controller due to SUPERUSER_ID
@http.route(['/customers/<partner_id>'], type='http', auth="public", website=True)
def partners_detail(self, partner_id, **post):
_, partner_id = unslug(partner_id)
if partner_id:
partner = request.env['res.partner'].sudo().browse(partner_id)
if partner.exists() and partner.website_published:
values = {}
values['main_object'] = values['partner'] = partner
return request.render("website_customer.details", values)
return self.customers(**post)
|
Python
| 0.999999
|
@@ -2199,22 +2199,9 @@
in
-map(lambda x:
+(
x%5B'c
@@ -2214,17 +2214,25 @@
_id'%5D%5B0%5D
-,
+ for x in
countri
@@ -2233,16 +2233,35 @@
ountries
+ if x%5B'country_id'%5D
):%0A
|
7764c0a7fac551a95439881e53c1b0c28d13d239
|
Handle file existing on symlink
|
mesonbuild/scripts/yelphelper.py
|
mesonbuild/scripts/yelphelper.py
|
# Copyright 2016 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import subprocess
import shutil
import argparse
from .. import mlog
from . import destdir_join
parser = argparse.ArgumentParser()
parser.add_argument('command')
parser.add_argument('--id', dest='project_id')
parser.add_argument('--subdir', dest='subdir')
parser.add_argument('--installdir', dest='install_dir')
parser.add_argument('--sources', dest='sources')
parser.add_argument('--media', dest='media', default='')
parser.add_argument('--langs', dest='langs', default='')
parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False)
def build_pot(srcdir, project_id, sources):
# Must be relative paths
sources = [os.path.join('C', source) for source in sources]
outfile = os.path.join(srcdir, project_id + '.pot')
subprocess.call(['itstool', '-o', outfile] + sources)
def update_po(srcdir, project_id, langs):
potfile = os.path.join(srcdir, project_id + '.pot')
for lang in langs:
pofile = os.path.join(srcdir, lang, lang + '.po')
subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile])
def build_translations(srcdir, blddir, langs):
for lang in langs:
outdir = os.path.join(blddir, lang)
os.makedirs(outdir, exist_ok=True)
subprocess.call([
'msgfmt', os.path.join(srcdir, lang, lang + '.po'),
'-o', os.path.join(outdir, lang + '.gmo')
])
def merge_translations(blddir, sources, langs):
for lang in langs:
subprocess.call([
'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'),
'-o', os.path.join(blddir, lang)
] + sources)
def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks):
c_install_dir = os.path.join(install_dir, 'C', project_id)
for lang in langs + ['C']:
indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id))
os.makedirs(indir, exist_ok=True)
for source in sources:
infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source)
outfile = os.path.join(indir, source)
mlog.log('Installing %s to %s' % (infile, outfile))
shutil.copyfile(infile, outfile)
shutil.copystat(infile, outfile)
for m in media:
infile = os.path.join(srcdir, lang, m)
outfile = os.path.join(indir, m)
if not os.path.exists(infile):
if lang == 'C':
mlog.warning('Media file "%s" did not exist in C directory' % m)
continue
elif symlinks:
srcfile = os.path.join(c_install_dir, m)
mlog.log('Symlinking %s to %s.' % (outfile, srcfile))
if '/' in m or '\\' in m:
os.makedirs(os.path.dirname(outfile), exist_ok=True)
try:
os.symlink(srcfile, outfile)
continue
except (NotImplementedError, OSError):
mlog.warning('Symlinking not supported, falling back to copying')
else:
# Lang doesn't have media file so copy it over 'C' one
infile = os.path.join(srcdir, 'C', m)
mlog.log('Installing %s to %s' % (infile, outfile))
if '/' in m or '\\' in m:
os.makedirs(os.path.dirname(outfile), exist_ok=True)
shutil.copyfile(infile, outfile)
shutil.copystat(infile, outfile)
def run(args):
options = parser.parse_args(args)
langs = options.langs.split('@@') if options.langs else []
media = options.media.split('@@') if options.media else []
sources = options.sources.split('@@')
destdir = os.environ.get('DESTDIR', '')
src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir)
build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir)
abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources]
if options.command == 'pot':
build_pot(src_subdir, options.project_id, sources)
elif options.command == 'update-po':
build_pot(src_subdir, options.project_id, sources)
update_po(src_subdir, options.project_id, langs)
elif options.command == 'build':
if langs:
build_translations(src_subdir, build_subdir, langs)
elif options.command == 'install':
install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir)
if langs:
build_translations(src_subdir, build_subdir, langs)
merge_translations(build_subdir, abs_sources, langs)
install_help(src_subdir, build_subdir, sources, media, langs, install_dir,
destdir, options.project_id, options.symlinks)
|
Python
| 0
|
@@ -3461,16 +3461,201 @@
try:%0A
+ try:%0A os.symlink(srcfile, outfile)%0A except FileExistsError:%0A os.remove(outfile)%0A
|
306bfdd744ba71439cf569528c9e091d4e9c691e
|
Use the logger
|
bin/tools/amount_to_text_en.py
|
bin/tools/amount_to_text_en.py
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2008 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# $Id$
#
# 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/>.
#
##############################################################################
#-------------------------------------------------------------
#ENGLISH
#-------------------------------------------------------------
ones = {
0: '', 1:'One', 2:'Two', 3:'Three', 4:'Four', 5:'Five', 6:'Six', 7:'Seven', 8:'Eight', 9:'Nine',
10:'Ten', 11:'Eleven', 12:'Twelve', 13:'Thirteen', 14:'Forteen', 15:'Fifteen', 16:'Sixteen', 17:"Seventeen",18:"Eighteen",19:"Nineteen",
}
tens = {
1: 'Ten', 2: 'Twenty ', 3:'Thirty', 4:'Forty', 5:'Fifty', 6: 'Sixty', 7 : 'Seventy', 8:'Eighty' ,9: 'Ninety'}
hundred = {
0:'',1: 'One Hundred', 2: 'Two Hundred', 3: 'Three Hundred', 4 :'Four Hundred', 5: 'Five Hundred', 6: 'Six Hundred', 7 :'Seven Hundred', 8:' Eight Hundred ', 9:'Nine Hundred '
}
thousands ={
0:'',1: 'One Thousand'
}
lacs = {
0:'',1: 'Lac'
}
def _100_to_text(number):
if number in ones:
return ones[number]
else:
if number%10>0:
return tens[number / 10]+'-'+ones[number % 10]
else:
return tens[number / 10]
def _1000_to_text(number):
d = _100_to_text(number % 100)
d2 = number/100
if d2>0 and d:
return hundred[d2]+' '+d
elif d2>1 and not(d):
return hundred[d2]+'s'
else:
return hundred[d2] or d
def _10000_to_text(number):
if number==0:
return 'zero'
part1 = _1000_to_text(number % 1000)
part2 = thousands.get(number / 1000, _1000_to_text(number / 1000)+' Thousands')
if part2 and part1:
part1 = ' '+part1
return part2+part1
def _1000000_to_text(number):
if number==0:
return 'zero'
part1 = _10000_to_text(number % 100000)
part2 = lacs.get(number / 100000, _10000_to_text(number / 100000)+' Lacs')
if part2 and part1:
part1 = ' '+part1
return part2+part1
def amount_to_text(number, currency):
lacs_number = int(number)
units_name = currency
if lacs_number > 1:
units_name += 's'
lacs = _1000000_to_text(lacs_number)
lacs = lacs_number and '%s %s' % (lacs, units_name) or ''
units_number = int(number * 10000) % 10000
units = _10000_to_text(units_number)
units = units_number and '%s %s' % (units, units_name) or ''
cents_number = int(number * 100) % 100
cents_name = (cents_number > 1) and 'cents' or 'cent'
cents = _100_to_text(cents_number)
cents = cents_number and '%s %s' % (cents, cents_name) or ''
return lacs
#-------------------------------------------------------------
# Generic functions
#-------------------------------------------------------------
_translate_funcs = {'en' : amount_to_text}
#TODO: we should use the country AND language (ex: septante VS soixante dix)
#TODO: we should use en by default, but the translation func is yet to be implemented
def amount_to_text(nbr, lang='en', currency='euro'):
"""
Converts an integer to its textual representation, using the language set in the context if any.
Example:
1654: thousands six cent cinquante-quatre.
"""
if nbr > 10000000:
#TODO: use logger
print "WARNING: number too large '%d', can't translate it!" % (nbr,)
return str(nbr)
if not _translate_funcs.has_key(lang):
#TODO: use logger
print "WARNING: no translation function found for lang: '%s'" % (lang,)
#TODO: (default should be en) same as above
lang = 'en'
return _translate_funcs[lang](nbr, currency)
if __name__=='__main__':
from sys import argv
lang = 'nl'
if len(argv) < 2:
for i in range(1,200):
print i, ">>", int_to_text(i, lang)
for i in range(200,999999,139):
print i, ">>", int_to_text(i, lang)
else:
print int_to_text(int(argv[1]), lang)
|
Python
| 0
|
@@ -3988,24 +3988,42 @@
re.%0A %22%22%22%0A
+ import netsvc%0A
if nbr %3E
@@ -4037,55 +4037,83 @@
00:%0A
-#TODO: use logger
+
-%0A
- print %22
+netsvc.Logger().notifyChannel('translate', netsvc.LOG_
WARNING
-: n
+, _(%22N
umbe
@@ -4133,17 +4133,19 @@
%25d', can
-'
+ no
t transl
@@ -4154,18 +4154,10 @@
e it
-!%22 %25 (nbr,
+%22)
)%0A
@@ -4230,54 +4230,82 @@
g):%0A
-#TODO: use logger
-%0A
- print %22
+netsvc.Logger().notifyChannel('translate', netsvc.LOG_
WARNING
-:
+, _(%22
no t
@@ -4355,17 +4355,27 @@
(lang,)
-%0A
+))%0A
#TODO: (
|
38b09d43d74ba9550c548dc33648ea7f4217bdc0
|
Replaced assert_ by assertEqual and assertTrue
|
blaze/compute/tests/test_where.py
|
blaze/compute/tests/test_where.py
|
from __future__ import absolute_import, division, print_function
import unittest
import numpy as np
from numpy.testing import assert_array_equal, assert_allclose
from dynd import nd, ndt
import blaze
import unittest
import tempfile
import os
import glob
import blaze
import blz
from blaze.optional_packages import tables_is_here
if tables_is_here:
import tables
# Useful superclass for disk-based tests
class createTables(unittest.TestCase):
disk = None
open = False
def setUp(self):
self.dtype = 'i4,f8'
self.npt = np.fromiter(((i, i*2.) for i in range(self.N)),
dtype=self.dtype, count=self.N)
if self.disk == 'BLZ':
prefix = 'blaze-' + self.__class__.__name__
suffix = '.blz'
path = tempfile.mkdtemp(suffix=suffix, prefix=prefix)
os.rmdir(path)
if self.open:
table = blz.fromiter(
((i, i*2.) for i in range(self.N)), dtype=self.dtype,
count=self.N, rootdir=path)
self.ddesc = blaze.BLZ_DDesc(table, mode='r')
else:
self.ddesc = blaze.BLZ_DDesc(path, mode='w')
a = blaze.array([(i, i*2.) for i in range(self.N)],
'var * {f0: int32, f1: float64}',
ddesc=self.ddesc)
elif self.disk == 'HDF5' and tables_is_here:
prefix = 'hdf5-' + self.__class__.__name__
suffix = '.hdf5'
dpath = "/table"
h, path = tempfile.mkstemp(suffix=suffix, prefix=prefix)
os.close(h) # close the not needed file handle
if self.open:
with tables.open_file(path, "w") as h5f:
ra = np.fromiter(
((i, i*2.) for i in range(self.N)), dtype=self.dtype,
count=self.N)
h5f.create_table('/', dpath[1:], ra)
self.ddesc = blaze.HDF5_DDesc(path, dpath, mode='r')
else:
self.ddesc = blaze.HDF5_DDesc(path, dpath, mode='w')
a = blaze.array([(i, i*2.) for i in range(self.N)],
'var * {f0: int32, f1: float64}',
ddesc=self.ddesc)
else:
table = blz.fromiter(
((i, i*2.) for i in range(self.N)), dtype=self.dtype,
count=self.N)
self.ddesc = blaze.BLZ_DDesc(table, mode='r')
def tearDown(self):
self.ddesc.remove()
# Check for tables in-memory (BLZ)
class whereTest(createTables):
N = 1000
def test00(self):
"""Testing the dshape attribute of a streamed array"""
t = blaze.array(self.ddesc)
st = t.where("f0 < 10")
self.assert_(isinstance(st, blaze.Array))
self.assert_(isinstance(st.ddesc, blaze.Stream_DDesc))
self.assert_(t.dshape.measure == st.dshape.measure)
def test01(self):
"""Testing with a filter in only one field"""
t = blaze.array(self.ddesc)
st = t.where("f0 < 10")
cr = [tuple(i.values()) for i in st]
nr = [tuple(i) for i in self.npt[self.npt['f0'] < 10]]
#print("cr:", cr)
#print("nr:", nr)
self.assert_(cr == nr, "where does not work correctly")
def test02(self):
"""Testing with two fields"""
t = blaze.array(self.ddesc)
st = t.where("(f0 < 10) & (f1 > 4)")
cr = [tuple(i.values()) for i in st]
nr = [tuple(i) for i in self.npt[
(self.npt['f0'] < 10) & (self.npt['f1'] > 4)]]
self.assert_(cr == nr, "where does not work correctly")
# Check for tables on-disk (BLZ)
class whereBLZDiskTest(whereTest):
disk = "BLZ"
# Check for tables on-disk (HDF5)
class whereHDF5DiskTest(whereTest):
disk = "HDF5"
# Check for tables on-disk, using existing BLZ files
class whereBLZDiskOpenTest(whereTest):
disk = "BLZ"
open = True
# Check for tables on-disk, using existng HDF5 files
class whereHDF5DiskOpenTest(whereTest):
disk = "HDF5"
open = True
if __name__ == '__main__':
unittest.main()
|
Python
| 0.999991
|
@@ -98,70 +98,8 @@
s np
-%0Afrom numpy.testing import assert_array_equal, assert_allclose
%0A%0Afr
@@ -2750,33 +2750,36 @@
self.assert
-_
+True
(isinstance(st,
@@ -2811,17 +2811,20 @@
f.assert
-_
+True
(isinsta
@@ -2877,17 +2877,21 @@
f.assert
-_
+Equal
(t.dshap
@@ -2899,19 +2899,17 @@
.measure
- ==
+,
st.dsha
@@ -3177,60 +3177,8 @@
0%5D%5D%0A
- #print(%22cr:%22, cr)%0A #print(%22nr:%22, nr)%0A
@@ -3184,39 +3184,41 @@
self.assert
-_(cr ==
+Equal(cr,
nr, %22where does
@@ -3550,15 +3550,17 @@
sert
-_(cr ==
+Equal(cr,
nr,
|
6909fc497041761eadb5a8b8947eeb21b7fdbcc8
|
use GetManager method in example
|
examples/avatar.py
|
examples/avatar.py
|
"""
Telepathy example which requests the avatar for the user's own handle and
displays it in a Gtk window.
"""
import dbus.glib
import gtk
import sys
from telepathy.constants import CONNECTION_STATUS_CONNECTED
from telepathy.interfaces import (
CONN_MGR_INTERFACE, CONN_INTERFACE, CONN_INTERFACE_AVATARS)
import telepathy.client
def parse_account(s):
lines = s.splitlines()
pairs = []
for line in lines:
k, v = line.split(':', 1)
k = k.strip()
v = v.strip()
pairs.append((k, v))
return dict(pairs)
def window_closed_cb(window):
gtk.main_quit()
def status_changed_cb(state, reason):
if state != CONNECTION_STATUS_CONNECTED:
return
handle = conn[CONN_INTERFACE].GetSelfHandle()
tokens = conn[CONN_INTERFACE_AVATARS].GetAvatarTokens([handle])
print 'token:', tokens[0]
image, mime = conn[CONN_INTERFACE_AVATARS].RequestAvatar(handle)
image = ''.join(chr(i) for i in image)
window = gtk.Window()
loader = gtk.gdk.PixbufLoader()
loader.write(image)
loader.close()
image = gtk.Image()
image.set_from_pixbuf(loader.get_pixbuf())
window.add(image)
window.show_all()
window.connect('destroy', gtk.main_quit)
if __name__ == '__main__':
if len(sys.argv) > 1:
account_file = sys.argv[1]
else:
account_file = 'account'
reg = telepathy.client.ManagerRegistry()
reg.LoadManagers()
account = parse_account(file(account_file).read())
manager = account['manager']
protocol = account['protocol']
del account['manager']
del account['protocol']
mgr_bus_name = reg.GetBusName(manager)
mgr_object_path = reg.GetObjectPath(manager)
mgr = telepathy.client.ConnectionManager(mgr_bus_name, mgr_object_path)
conn_bus_name, conn_object_path = mgr[CONN_MGR_INTERFACE].Connect(
protocol, account)
conn = telepathy.client.Connection(conn_bus_name, conn_object_path)
conn[CONN_INTERFACE].connect_to_signal('StatusChanged', status_changed_cb)
gtk.main()
conn[CONN_INTERFACE].Disconnect()
|
Python
| 0.000002
|
@@ -1614,25 +1614,16 @@
%0A mgr
-_bus_name
= reg.G
@@ -1628,149 +1628,23 @@
.Get
-BusName(manager)%0A mgr_object_path = reg.GetObjectPath(manager)%0A%0A mgr = telepathy.client.ConnectionManager(mgr_bus_name, mgr_object_path
+Manager(manager
)%0A
|
390e5001a90b1e54cad713cd822feb1dced1015e
|
update examples/batman -- now available by invitation as well
|
examples/batman.py
|
examples/batman.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
"""
Chat with Batman
In this example we create following commands with some lines of code:
- command: whoareyou
- response: I'm Batman!
- command: cave
- response: The Batcave is silent...
- command: cave give me some echo
- response: The Batcave echoes, 'give me some echo'
- command: signal
- response: NANA NANA NANA NANA
- also uploads an image to the chat room
- command: suicide
- delayed response: Going back to Hell
- also stops the bot itself on the server
Multiple questions are adressed in this example:
- How to build a dynamic response? Look at the command ``cave``, where
the message pushed to the chat room depends on the input received. This
is done with regular python code in the member function ``execute()``.
- How to upload files? The command ``signal`` demonstrates how to
attach a link or a file to a message. Here we use public image, yet the
same would work for the upload of a local file.
- What about long-lasting commands? In that case, you can set the command
attribute ``is_interactive`` to False. On command submission, the bot
will execute it in the background. Look for example at the command
``suicide``, where Batman is waiting for some seconds before acting.
- How to load multiple commands? Since each command is a separate object,
you can add them as a list bundle to the bot.
To run this script you have to provide a custom configuration, or set
environment variables instead::
- ``CHAT_ROOM_MODERATORS`` - Mention at least your e-mail address
- ``CISCO_SPARK_BOT_TOKEN`` - Received from Cisco Spark on bot registration
- ``SERVER_URL`` - Public link used by Cisco Spark to reach your server
The token is specific to your run-time, please visit Cisco Spark for
Developers to get more details:
https://developer.ciscospark.com/
For example, if you run this script under Linux or macOs with support from
ngrok for exposing services to the Internet::
export CHAT_ROOM_MODERATORS="alice@acme.com"
export CISCO_SPARK_BOT_TOKEN="<token id from Cisco Spark for Developers>"
export SERVER_URL="http://1a107f21.ngrok.io"
python batman.py
Credit: https://developer.ciscospark.com/blog/blog-details-8110.html
"""
import os
import time
from shellbot import Engine, ShellBot, Context, Command
Context.set_logger()
#
# create a bot and load commands
#
class Batman(Command):
keyword = 'whoareyou'
information_message = u"I'm Batman!"
class Batcave(Command):
keyword = 'cave'
information_message = u"The Batcave is silent..."
def execute(self, bot, arguments=None):
if arguments:
bot.say(u"The Batcave echoes, '{0}'".format(arguments))
else:
bot.say(self.information_message)
class Batsignal(Command):
keyword = 'signal'
information_message = u"NANA NANA NANA NANA"
information_file = "https://upload.wikimedia.org/wikipedia/en/c/c6/Bat-signal_1989_film.jpg"
def execute(self, bot, arguments=None):
bot.say(self.information_message,
file=self.information_file)
class Batsuicide(Command):
keyword = 'suicide'
information_message = u"Go back to Hell"
def execute(self, bot, arguments=None):
bot.say(self.information_message)
bot.dispose()
engine = Engine(
type='spark',
commands=[Batman(), Batcave(), Batsignal(), Batsuicide()])
# load configuration
#
os.environ['BOT_ON_START'] = 'You can now chat with Batman'
os.environ['BOT_ON_STOP'] = 'Batman is now quitting the room, bye'
os.environ['CHAT_ROOM_TITLE'] = 'Chat with Batman'
engine.configure()
# initialise a chat room
#
bot = engine.bond(reset=True)
# run the bot
#
engine.run()
# delete the chat room when the bot is stopped
#
bot.dispose()
|
Python
| 0
|
@@ -4228,13 +4228,13 @@
_ON_
-START
+ENTER
'%5D =
@@ -4288,12 +4288,12 @@
_ON_
-STOP
+EXIT
'%5D =
@@ -4447,12 +4447,15 @@
ine.
-bond
+get_bot
(res
|
298a55b28fcc04e4085e14c6f2999e14cc224d60
|
Replace previous bash command to new one (#7005)
|
lib/spack/spack/platforms/cray.py
|
lib/spack/spack/platforms/cray.py
|
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
import re
import llnl.util.tty as tty
from spack.paths import build_env_path
from spack.util.executable import which
from spack.architecture import Platform, Target, NoPlatformError
from spack.operating_systems.cray_frontend import CrayFrontend
from spack.operating_systems.cnl import Cnl
from spack.util.module_cmd import get_module_cmd, unload_module
def _get_modules_in_modulecmd_output(output):
'''Return list of valid modules parsed from modulecmd output string.'''
return [i for i in output.splitlines()
if len(i.split()) == 1]
def _fill_craype_targets_from_modules(targets, modules):
'''Extend CrayPE CPU targets list with those found in list of modules.'''
# Craype- module prefixes that are not valid CPU targets.
non_targets = ('hugepages', 'network', 'target', 'accel', 'xtpe')
pattern = r'craype-(?!{0})(\S*)'.format('|'.join(non_targets))
for mod in modules:
if 'craype-' in mod:
targets.extend(re.findall(pattern, mod))
class Cray(Platform):
priority = 10
def __init__(self):
''' Create a Cray system platform.
Target names should use craype target names but not include the
'craype-' prefix. Uses first viable target from:
self
envars [SPACK_FRONT_END, SPACK_BACK_END]
configuration file "targets.yaml" with keys 'front_end', 'back_end'
scanning /etc/bash/bashrc.local for back_end only
'''
super(Cray, self).__init__('cray')
# Make all craype targets available.
for target in self._avail_targets():
name = target.replace('-', '_')
self.add_target(name, Target(name, 'craype-%s' % target))
self.add_target("x86_64", Target("x86_64"))
self.add_target("front_end", Target("x86_64"))
self.front_end = "x86_64"
# Get aliased targets from config or best guess from environment:
for name in ('front_end', 'back_end'):
_target = getattr(self, name, None)
if _target is None:
_target = os.environ.get('SPACK_' + name.upper())
if _target is None and name == 'back_end':
_target = self._default_target_from_env()
if _target is not None:
safe_name = _target.replace('-', '_')
setattr(self, name, safe_name)
self.add_target(name, self.targets[safe_name])
if self.back_end is not None:
self.default = self.back_end
self.add_target('default', self.targets[self.back_end])
else:
raise NoPlatformError()
front_distro = CrayFrontend()
back_distro = Cnl()
self.default_os = str(back_distro)
self.back_os = self.default_os
self.front_os = str(front_distro)
self.add_operating_system(self.back_os, back_distro)
self.add_operating_system(self.front_os, front_distro)
@classmethod
def setup_platform_environment(cls, pkg, env):
""" Change the linker to default dynamic to be more
similar to linux/standard linker behavior
"""
# Unload these modules to prevent any silent linking or unnecessary
# I/O profiling in the case of darshan.
modules_to_unload = ["cray-mpich", "darshan", "cray-libsci"]
for module in modules_to_unload:
unload_module(module)
env.set('CRAYPE_LINK_TYPE', 'dynamic')
cray_wrapper_names = os.path.join(build_env_path, 'cray')
if os.path.isdir(cray_wrapper_names):
env.prepend_path('PATH', cray_wrapper_names)
env.prepend_path('SPACK_ENV_PATH', cray_wrapper_names)
# Makes spack installed pkg-config work on Crays
env.append_path("PKG_CONFIG_PATH", "/usr/lib64/pkgconfig")
env.append_path("PKG_CONFIG_PATH", "/usr/local/lib64/pkgconfig")
@classmethod
def detect(cls):
return os.environ.get('CRAYPE_VERSION') is not None
def _default_target_from_env(self):
'''Set and return the default CrayPE target loaded in a clean login
session.
A bash subshell is launched with a wiped environment and the list of
loaded modules is parsed for the first acceptable CrayPE target.
'''
# Based on the incantation:
# echo "$(env - USER=$USER /bin/bash -l -c 'module list -lt')"
if getattr(self, 'default', None) is None:
env = which('env')
env.add_default_arg('-')
# CAUTION - $USER is generally needed in the sub-environment.
# There may be other variables needed for general success.
output = env('USER=%s' % os.environ['USER'],
'HOME=%s' % os.environ['HOME'],
'/bin/bash', '--noprofile', '--norc', '-c',
'. /etc/profile; module list -lt',
output=str, error=str)
self._defmods = _get_modules_in_modulecmd_output(output)
targets = []
_fill_craype_targets_from_modules(targets, self._defmods)
self.default = targets[0] if targets else None
tty.debug("Found default modules:",
*[" %s" % mod for mod in self._defmods])
return self.default
def _avail_targets(self):
'''Return a list of available CrayPE CPU targets.'''
if getattr(self, '_craype_targets', None) is None:
module = get_module_cmd()
output = module('avail', '-t', 'craype-', output=str, error=str)
craype_modules = _get_modules_in_modulecmd_output(output)
self._craype_targets = targets = []
_fill_craype_targets_from_modules(targets, craype_modules)
return self._craype_targets
|
Python
| 0.000001
|
@@ -4497,509 +4497,178 @@
#
-Based on the incantation:%0A # echo %22$(env - USER=$USER /bin/bash -l -c 'module list -lt')%22%0A if getattr(self, 'default', None) is None:%0A env = which('env')%0A env.add_default_arg('-')%0A # CAUTION - $USER is generally needed in the sub-environment.%0A # There may be other variables needed for general success.%0A output = env('USER=%25s' %25 os.environ%5B'USER'%5D,%0A 'HOME=%25s' %25 os.environ%5B'HOME'%5D,%0A '
+env -i /bin/bash -lc echo $CRAY_CPU_TARGET 2%3E /dev/null%0A if getattr(self, 'default', None) is None:%0A env = which('env')%0A output = env(%22-i%22, %22
/bin
@@ -4676,486 +4676,202 @@
bash
-', '--noprofile', '--norc', '-c',%0A '. /etc/profile; module list -lt',%0A output=str, error=str)%0A self._defmods = _get_modules_in_modulecmd_output(output)%0A targets = %5B%5D%0A _fill_craype_targets_from_modules(targets, self._defmods)%0A self.default = targets%5B0%5D if targets else None%0A tty.debug(%22Found default modules:%22,%0A *%5B%22 %25s%22 %25 mod for mod in
+%22, %22-lc%22, %22echo $CRAY_CPU_TARGET%22,%0A output=str, error=os.devnull)%0A self.default = output.strip()%0A tty.debug(%22Found default module:%25s%22 %25
self.
-_
def
-mods%5D
+ault
)%0A
|
26c8839edf0f756c746dee1e13f4332f0f3bf706
|
Update bashdoor.py
|
lib/modules/python/privesc/multi/bashdoor.py
|
lib/modules/python/privesc/multi/bashdoor.py
|
class Module:
def __init__(self, mainMenu, params=[]):
# metadata info about the module, not modified during runtime
self.info = {
# name for the module that will appear in module menus
'Name': 'bashdoor',
# list of one or more authors for the module
'Author': ['@n00py'],
# more verbose multi-line description of the module
'Description': 'Creates an alias in the .bash_profile to cause the sudo command to execute a stager and pass through the origional command back to sudo',
# True if the module needs to run in the background
'Background' : False,
# File extension to save the file as
'OutputExtension' : "",
# if the module needs administrative privileges
'NeedsAdmin' : False,
# True if the method doesn't touch disk/is reasonably opsec safe
'OpsecSafe' : False,
# the module language
'Language' : 'python',
# the minimum language version needed
'MinLanguageVersion' : '2.6',
# list of any references/other comments
'Comments': []
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
'Description' : 'Agent to execute module on.',
'Required' : True,
'Value' : ''
},
'SafeChecks': {
'Description': 'Switch. Checks for LittleSnitch or a SandBox, exit the staging process if true. Defaults to True.',
'Required': True,
'Value': 'True'
},
'Listener' : {
'Description' : 'Listener to use.',
'Required' : True,
'Value' : ''
},
'UserAgent' : {
'Description' : 'User-agent string to use for the staging request (default, none, or other).',
'Required' : False,
'Value' : 'default'
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
# During instantiation, any settable option parameters
# are passed as an object set to the module and the
# options dictionary is automatically set. This is mostly
# in case options are passed on the command line
if params:
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value
def generate(self):
# extract all of our options
listenerName = self.options['Listener']['Value']
userAgent = self.options['UserAgent']['Value']
safeChecks = self.options['SafeChecks']['Value']
# generate the launcher code
launcher = self.mainMenu.stagers.generate_launcher(listenerName, language='python', encode=True, userAgent=userAgent, safeChecks=safeChecks)
launcher = launcher.replace('"', '\\"')
script = '''
import os
from random import choice
from string import ascii_uppercase
home = os.getenv("HOME")
randomStr = ''.join(choice(ascii_uppercase) for i in range(12))
bashlocation = home + "/Library/iTunes/." + randomStr + ".sh"
with open(home + "/.bash_profile", "a") as profile:
profile.write("alias sudo='sudo sh -c '\\\\''" + bashlocation + " & exec \\"$@\\"'\\\\'' sh'")
launcher = "%s"
stager = "#!/bin/bash\\n"
stager += launcher
with open(bashlocation, 'w') as f:
f.write(stager)
f.close()
os.chmod(bashlocation, 0755)
''' % (launcher)
return script
|
Python
| 0
|
@@ -3602,15 +3602,8 @@
ary/
-iTunes/
.%22 +
|
cda7e0d2242e5cc3dafca63a3af01f150fcd37be
|
Fix seeds for new names
|
server/seed.py
|
server/seed.py
|
from tables import *
fira = Font(name='Fira Sans Regular', family_id=1, author_id=1)
fira.tags.append(Tag(text='#pretty', type='opinion'))
fira.tags.append(Tag(text='Latin', type='language'))
thread1 = Thread(title='I don\'t like this word')
thread1.glyphs.append(Glyph(name='A', version_hash='9c7075ca420f30aedb27c48102466313fa4d12c8', font_id=1))
thread1.glyphs.append(Glyph(name='a', version_hash='9c7075ca420f30aedb27c48102466313fa4d12c8', font_id=1))
thread1.glyphs.append(Glyph(name='s', version_hash='9c7075ca420f30aedb27c48102466313fa4d12c8', font_id=1))
entities = [
User(name='Eva', password='eveisevil'),
User(name='Tom', password='safepwissafe'),
Family(name='Fira'),
fira,
thread1,
Codepoint(value=0x0041, size=12.5, features='liga', thread_id=1, font_id=1),
Codepoint(value=0x0061, size=12.5, features='liga', thread_id=1, font_id=1),
Codepoint(value=0x0073, size=12.5, features='liga', thread_id=1, font_id=1),
Comment(text='why would anyone comment on aas', author_id=2, thread_id=1),
Comment(text='because.', author_id=1, thread_id=1),
SampleText(title='Evil Wizards', text='Mad wizards brew evil jack with horses', author_id=2)
]
|
Python
| 0.000137
|
@@ -27,17 +27,21 @@
= Font(
-n
+fontN
ame='Fir
@@ -265,25 +265,30 @@
ppend(Glyph(
-n
+glyphN
ame='A', ver
@@ -377,25 +377,30 @@
ppend(Glyph(
-n
+glyphN
ame='a', ver
@@ -493,17 +493,22 @@
d(Glyph(
-n
+glyphN
ame='s',
@@ -596,25 +596,29 @@
%5B%0A User(
-n
+userN
ame='Eva', p
@@ -648,17 +648,21 @@
User(
-n
+userN
ame='Tom
@@ -701,17 +701,23 @@
Family(
-n
+familyN
ame='Fir
@@ -750,33 +750,40 @@
,%0A Codepoint(
-v
+unicodeV
alue=0x0041, siz
@@ -779,17 +779,22 @@
0x0041,
-s
+pointS
ize=12.5
@@ -843,33 +843,40 @@
,%0A Codepoint(
-v
+unicodeV
alue=0x0061, siz
@@ -872,17 +872,22 @@
0x0061,
-s
+pointS
ize=12.5
@@ -944,17 +944,24 @@
depoint(
-v
+unicodeV
alue=0x0
@@ -965,17 +965,22 @@
0x0073,
-s
+pointS
ize=12.5
|
67f535f92d79de05aa10e86da3cdd635bc71537b
|
Use proper stacklevel for deprecation warnings
|
w3lib/util.py
|
w3lib/util.py
|
from warnings import warn
def str_to_unicode(text, encoding=None, errors='strict'):
warn(
"The w3lib.utils.str_to_unicode function is deprecated and "
"will be removed in a future release.",
DeprecationWarning
)
if encoding is None:
encoding = 'utf-8'
if isinstance(text, bytes):
return text.decode(encoding, errors)
return text
def unicode_to_str(text, encoding=None, errors='strict'):
warn(
"The w3lib.utils.unicode_to_str function is deprecated and "
"will be removed in a future release.",
DeprecationWarning
)
if encoding is None:
encoding = 'utf-8'
if isinstance(text, str):
return text.encode(encoding, errors)
return text
def to_unicode(text, encoding=None, errors='strict'):
"""Return the unicode representation of a bytes object `text`. If `text`
is already an unicode object, return it as-is."""
if isinstance(text, str):
return text
if not isinstance(text, (bytes, str)):
raise TypeError('to_unicode must receive a bytes, str or unicode '
'object, got %s' % type(text).__name__)
if encoding is None:
encoding = 'utf-8'
return text.decode(encoding, errors)
def to_bytes(text, encoding=None, errors='strict'):
"""Return the binary representation of `text`. If `text`
is already a bytes object, return it as-is."""
if isinstance(text, bytes):
return text
if not isinstance(text, str):
raise TypeError('to_bytes must receive a unicode, str or bytes '
'object, got %s' % type(text).__name__)
if encoding is None:
encoding = 'utf-8'
return text.encode(encoding, errors)
def to_native_str(text, encoding=None, errors='strict'):
""" Return str representation of `text` """
warn(
"The w3lib.utils.to_native_str function is deprecated and "
"will be removed in a future release. Please use "
"w3lib.utils.to_unicode instead.",
DeprecationWarning
)
return to_unicode(text, encoding, errors)
|
Python
| 0.000001
|
@@ -224,32 +224,55 @@
precationWarning
+,%0A stacklevel=2,
%0A )%0A if en
@@ -611,32 +611,55 @@
precationWarning
+,%0A stacklevel=2,
%0A )%0A if en
@@ -2096,16 +2096,39 @@
nWarning
+,%0A stacklevel=2,
%0A )%0A
|
bc4cebcd5d6d0657f8e16a895fca31aad8e4ac16
|
Add OG help texts
|
meta/models.py
|
meta/models.py
|
# -*- coding: utf-8 -*-
from django.contrib.contenttypes import generic
from django.db import models
from django.forms.models import model_to_dict
from .settings import CONTENT_MODELS
###
# MODELS
###
class BaseMetatag(models.Model):
'''
This class represent the whole meta tags class.
url is og:url
title is og:title
image is og:image
object_type is og:type
site_name is og:site_name
'''
# Meta properties values
author = models.CharField(max_length=155, blank=True)
description = models.CharField(max_length=155, blank=True)
keywords = models.CharField(
max_length=155,
blank=True,
help_text='A list of comma separated keywords'
)
# OG properties values
url = models.CharField(max_length=50, blank=True)
title = models.CharField(max_length=50, blank=True)
image = models.CharField(max_length=50, blank=True)
type = models.CharField(max_length=50, blank=True)
site_name = models.CharField(max_length=50, blank=True)
class Meta:
abstract = True
def build_tags(self):
obj_dict = model_to_dict(self)
def _values(names):
return [{
'name': name,
'value': value
} for name, value in obj_dict.items() if name in names and
value.strip() != ''
]
return {
'metatags': _values(['author', 'description', 'keywords']),
'ogtags': _values(['url', 'title', 'image', 'type', 'site_name'])
}
class MetatagModelInstance(BaseMetatag):
content_type = models.ForeignKey(
'contenttypes.ContentType',
limit_choices_to={'model__in': CONTENT_MODELS}
)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
class Meta:
unique_together = ('content_type', 'object_id')
verbose_name = 'Metadata for Model'
def __unicode__(self):
return u'{} :: {}'.format(
self.content_object.__class__.__name__,
self.content_object.__unicode__()
)
class MetatagPath(BaseMetatag):
path = models.CharField(db_index=True, max_length=255)
class Meta:
ordering = ('path', )
verbose_name = 'Metadata for Path'
def __unicode__(self):
return self.path
def save(self, *args, **kwargs):
if not self.path.startswith('/'):
self.path = '/{}'.format(self.path)
if not self.path.endswith('/'):
self.path += '/'
super(MetatagPath, self).save(*args, **kwargs)
|
Python
| 0
|
@@ -295,128 +295,8 @@
s.%0A%0A
- url is og:url%0A title is og:title%0A image is og:image%0A object_type is og:type%0A site_name is og:site_name%0A%0A
@@ -310,16 +310,19 @@
# Meta
+tag
propert
@@ -596,17 +596,23 @@
)%0A%0A
-#
+'''%0A
OG prop
@@ -629,287 +629,1035 @@
ues%0A
- url = models.CharField(max_length=50, blank=True)%0A title = models.CharField(max_length=50, blank=True)%0A image = models.CharField(max_length=50, blank=True)%0A type = models.CharField(max_length=50, blank=True)%0A site_name = models.CharField(max_length=50, blank=True
+%0A url is og:url%0A title is og:title%0A image is og:image%0A object_type is og:type%0A site_name is og:site_name%0A%0A '''%0A%0A url = models.CharField(max_length=50, blank=True, help_text=(%0A 'The title of your object as it should appear within the graph, e.g., '%0A '%22The Rock%22.'%0A ))%0A title = models.CharField(max_length=50, blank=True, help_text=(%0A 'The type of your object, e.g., %22video.movie%22.'%0A ))%0A image = models.CharField(max_length=50, blank=True, help_text=(%0A 'An image URL which should represent your object within the graph.'%0A ))%0A type = models.CharField(max_length=50, blank=True, help_text=(%0A 'The canonical URL of your object that will be used as its permanent '%0A 'ID in the graph, e.g., %22http://www.imdb.com/title/tt0117500/%22.'%0A ))%0A site_name = models.CharField(max_length=50, blank=True, help_text=(%0A 'If your object is part of a larger web site, the name which should '%0A 'be displayed for the overall site. e.g., %22IMDb%22.'%0A )
)%0A%0A
|
cdb92202470fe2b2a89b80cd1cec89d51f19d18e
|
Update urls.py
|
contentcuration/contentcuration/urls.py
|
contentcuration/contentcuration/urls.py
|
"""URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.conf import settings
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.core.urlresolvers import reverse_lazy
from rest_framework import routers, viewsets
from rest_framework.permissions import AllowAny
from contentcuration.models import ContentNode, License, Channel, File, FileFormat, FormatPreset, ContentTag, Exercise, AssessmentItem, ContentKind, Language, User, Invitation
import serializers
import views
from contentcuration import api
from rest_framework_bulk.routes import BulkRouter
from rest_framework_bulk.generics import BulkModelViewSet
class LicenseViewSet(viewsets.ModelViewSet):
queryset = License.objects.all()
serializer_class = serializers.LicenseSerializer
class LanguageViewSet(viewsets.ModelViewSet):
queryset = Language.objects.all()
serializer_class = serializers.LanguageSerializer
class ChannelViewSet(viewsets.ModelViewSet):
queryset = Channel.objects.all()
serializer_class = serializers.ChannelSerializer
class FileViewSet(BulkModelViewSet):
queryset = File.objects.all()
serializer_class = serializers.FileSerializer
class FileFormatViewSet(viewsets.ModelViewSet):
queryset = FileFormat.objects.all()
serializer_class = serializers.FileFormatSerializer
class FormatPresetViewSet(viewsets.ModelViewSet):
queryset = FormatPreset.objects.all()
serializer_class = serializers.FormatPresetSerializer
class ContentKindViewSet(viewsets.ModelViewSet):
queryset = ContentKind.objects.all()
serializer_class = serializers.ContentKindSerializer
class ContentNodeViewSet(BulkModelViewSet):
queryset = ContentNode.objects.all()
serializer_class = serializers.ContentNodeSerializer
class TagViewSet(viewsets.ModelViewSet):
queryset = ContentTag.objects.all()
serializer_class = serializers.TagSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = serializers.UserSerializer
class InvitationViewSet(viewsets.ModelViewSet):
queryset = Invitation.objects.all()
serializer_class = serializers.InvitationSerializer
class ExerciseViewSet(viewsets.ModelViewSet):
queryset = Exercise.objects.all()
serializer_class = serializers.ExerciseSerializer
permission_classes = [AllowAny]
class AssessmentItemViewSet(BulkModelViewSet):
queryset = AssessmentItem.objects.all()
serializer_class = serializers.AssessmentItemSerializer
router = routers.DefaultRouter(trailing_slash=False)
router.register(r'license', LicenseViewSet)
router.register(r'language', LanguageViewSet)
router.register(r'channel', ChannelViewSet)
router.register(r'exercise', ExerciseViewSet)
router.register(r'fileformat', FileFormatViewSet)
router.register(r'preset', FormatPresetViewSet)
router.register(r'tag', TagViewSet)
router.register(r'contentkind', ContentKindViewSet)
router.register(r'user', UserViewSet)
router.register(r'invitation', InvitationViewSet)
bulkrouter = BulkRouter(trailing_slash=False)
bulkrouter.register(r'assessmentitem', AssessmentItemViewSet)
bulkrouter.register(r'contentnode', ContentNodeViewSet)
bulkrouter.register(r'file', FileViewSet)
urlpatterns = [
url(r'^$', views.base, name='base'),
url(r'^test/', views.testpage, name='test'),
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include(router.urls)),
url(r'^api/', include(bulkrouter.urls)),
url(r'^api/duplicate_nodes/$', views.duplicate_nodes, name='duplicate_nodes'),
url(r'^api/publish_channel/$', views.publish_channel, name='publish_channel'),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'exercises/$', views.exercise_list, name='exercise_list'),
url(r'exercises/(?P<exercise_id>\w+)', views.exercise, name='exercise'),
url(r'^file_upload/', views.file_upload, name="file_upload"),
url(r'^file_create/', views.file_create, name="file_create"),
url(r'^accounts/logout/$', auth_views.logout, {'template_name': 'registration/logout.html'}),
url(r'^accounts/password/reset/$',auth_views.password_reset,{'post_reset_redirect': reverse_lazy('auth_password_reset_done'),'html_email_template_name': 'registration/password_reset_email.html'}, name='auth_password_reset'),
url(r'^accounts/register/$', views.UserRegistrationView.as_view(), name='registration_register'),
url(r'^accounts/', include('registration.backends.hmac.urls')),
url(r'^channels/$', views.channel_list, name='channels'),
url(r'^channels/(?P<channel_id>[^/]+)', views.channel, name='channel'),
url(r'^thumbnail_upload/', views.thumbnail_upload, name='thumbnail_upload'),
url(r'^exercise_image_upload/', views.exercise_image_upload, name='exercise_image_upload'),
url(r'^api/send_invitation_email/$', views.send_invitation_email, name='send_invitation_email'),
url(r'^accept_invitation/(?P<user_id>[^/]+)/(?P<invitation_link>[^/]+)/(?P<channel_id>[^/]+)$', views.InvitationAcceptView.as_view(), name="accept_invitation"),
url(r'^new/accept_invitation/(?P<user_id>[^/]+)/(?P<invitation_link>[^/]+)/(?P<channel_id>[^/]+)$', views.InvitationRegisterView.as_view(), name="accept_invitation_and_registration"),
url(r'^decline_invitation/(?P<invitation_link>[^/]+)$', views.decline_invitation, name="decline_invitation"),
url(r'^invitation_fail$', views.fail_invitation, name="fail_invitation"),
url(r'^api/internal/file_diff$', views.file_diff, name="file_diff"),
url(r'^api/internal/file_upload$', views.api_file_upload, name="api_file_upload"),
url(r'^api/internal/create_channel$', views.api_create_channel_endpoint, name="api_create_channel"),
url(r'^open_channel/(?P<invitation_id>[^/]+)/(?P<channel_id>[^/]+)$', views.api_open_channel, name="open_channel"),
url(r'^open_fail$', views.fail_open_channel, name="fail_open_channel"),
]
urlpatterns += [url(r'^jsreverse/$', 'django_js_reverse.views.urls_js', name='js_reverse')]
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += [
url(r'^' + settings.STORAGE_URL[1:-1] + '(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STORAGE_ROOT})]
|
Python
| 0.000002
|
@@ -1091,26 +1091,82 @@
ort
-serializers%0Aimport
+contentcuration.serializers as serializers%0Aimport contentcuration.views as
vie
|
24f7d137c7a0f58625543858b8f4a09f1dead859
|
Update client.py
|
examples/client.py
|
examples/client.py
|
from controlhost import Client
with Client('131.188.161.241') as client:
client.subscribe('foo')
try:
while True:
prefix, message = client.get_message()
print prefix.tag
print prefix.length
print message
except KeyboardInterrupt:
client._disconnect()
|
Python
| 0.000001
|
@@ -43,21 +43,15 @@
t('1
-31.188.161.24
+27.0.0.
1')
|
535640d2d26beec2c8aa56386473abf4858419de
|
Fix mixed indentation.
|
bitey/loader.py
|
bitey/loader.py
|
# loader.py
"""
Import hook loader for LLVM bitcode files.
Use the install() method to install the loader into sys.meta_path. Use
the remove() method to uninstall it.
"""
import sys
import os.path
import imp
from . import bind
def _check_magic(filename):
if os.path.exists(filename):
magic = open(filename,"rb").read(4)
if magic == b'\xde\xc0\x17\x0b':
return True
elif magic[:2] == b'\x42\x43':
return True
else:
return False
else:
return False
def build_module(fullname, bitcode, preload=None, postload=None):
'''
Creates a new module from bitcode supplied as a simple byte-string.
'''
name = fullname.split(".")[-1]
mod = imp.new_module(name)
if preload:
exec(preload, mod.__dict__, mod.__dict__)
bind.wrap_llvm_bitcode(bitcode, mod)
if postload:
exec(postload, mod.__dict__, mod.__dict__)
return mod
class LLVMLoader(object):
"""
Load LLVM compiled bitcode and autogenerate a ctypes binding
"""
def __init__(self, pkg, name, source, preload, postload):
self.package = pkg
self.name = name
self.fullname = '.'.join((pkg,name))
self.source = source
self.preload = preload
self.postload = postload
@classmethod
def find_module(cls, fullname, paths = None):
if paths is None:
paths = sys.path
names = fullname.split('.')
modname = names[-1]
for f in paths:
path = os.path.join(os.path.realpath(f), modname)
source = path + '.o'
if _check_magic(source):
preload = path + ".pre.py"
postload = path + ".post.py"
return cls('.'.join(names[:-1]), modname, source, preload, postload)
def get_code(self, module):
pass
def get_data(self, module):
pass
def get_filename(self, name):
return self.source
def get_source(self, name):
with open(self.source, 'rb') as f:
return f.read()
def is_package(self, *args, **kw):
return False
def load_module(self, fullname):
if fullname in sys.modules:
return sys.modules[fullname]
preload = None
postload = None
# Get the preload file (if any)
if os.path.exists(self.preload):
with open(self.preload) as f:
preload = f.read()
# Get the bit-code
with open(self.source, 'rb') as f:
bitcode = f.read()
# Get the postload file (if any)
if os.path.exists(self.postload):
with open(self.postload) as f:
postload = f.read()
mod = build_module(fullname, bitcode, preload, postload)
sys.modules[fullname] = mod
mod.__loader__ = self
mod.__file__ = self.source
return mod
def install():
if LLVMLoader not in sys.meta_path:
sys.meta_path.append(LLVMLoader)
def remove():
sys.meta_path.remove(LLVMLoader)
|
Python
| 0.000001
|
@@ -285,17 +285,24 @@
ename):%0A
-%09
+
magic =
@@ -506,17 +506,24 @@
else:%0A
-%09
+
return F
@@ -1112,17 +1112,24 @@
tload):%0A
-%09
+
self.pac
@@ -1139,17 +1139,24 @@
e = pkg%0A
-%09
+
self.nam
@@ -1164,17 +1164,24 @@
= name%0A
-%09
+
self.ful
@@ -1209,17 +1209,24 @@
,name))%0A
-%09
+
self.sou
@@ -1370,17 +1370,24 @@
None):%0A
-%09
+
if paths
@@ -1396,17 +1396,24 @@
s None:%0A
-%09
+
path
@@ -1637,9 +1637,16 @@
.o'%0A
-%09
+
|
a475173ce00b2d6686c601ffc46a8d2bc3ed0a7f
|
Switch back to development version
|
dogen/version.py
|
dogen/version.py
|
version = "2.0.0"
|
Python
| 0
|
@@ -10,9 +10,16 @@
%222.
-0.0
+1.0rc1.dev
%22%0A
|
57807697362d084afa92e45e24be155e5615e07f
|
make mv command work under Windows
|
src/CommandLineOperator.py
|
src/CommandLineOperator.py
|
#!/usr/bin/env python
# encoding: utf-8
"""
CommandLineOperator.py
Created by Tomas Knapen on 2010-09-23.
Copyright (c) 2010 __MyCompanyName__. All rights reserved.
"""
import os, sys, subprocess, shutil
import tempfile, logging
import re
import scipy as sp
import numpy as np
import matplotlib.pylab as pl
from IPython import embed as shell
from Operator import *
from log import *
### Execute program in shell:
def ExecCommandLine(cmdline):
tmpf = tempfile.TemporaryFile()
try:
retcode = subprocess.call( cmdline, shell=True, bufsize=0, stdout = tmpf, stderr = tmpf)
finally:
tmpf.close()
if retcode > 0:
raise ValueError( 'Process: '+cmdline+' returned error code: '+str(retcode) )
return retcode
class CommandLineOperator( Operator ):
def __init__(self, input_object, cmd, **kwargs):
"""
CommandLineOperator can take a Nii file as input but will use only the variable input_file_name
"""
super(CommandLineOperator, self).__init__(input_object = input_object, **kwargs)
if self.input_object.__class__.__name__ == 'NiftiImage':
self.input_file_name = self.input_object.filename
self.logger.info(self.__repr__() + ' initialized with ' + os.path.split(self.input_file_name)[-1])
elif self.input_object.__class__.__name__ == 'str':
self.input_file_name = self.input_object
self.logger.info(self.__repr__() + ' initialized with file ' + os.path.split(self.input_file_name)[-1])
if not os.path.isfile(self.input_file_name):
self.logger.warning('input_file_name is not a file at initialization')
elif self.input_object.__class__.__name__ == 'list':
self.inputList = self.input_object
self.logger.info(self.__repr__() + ' initialized with files ' + str(self.inputList))
self.cmd = cmd
def configure(self):
"""
placeholder for configure
to be filled in by subclasses
"""
self.runcmd = self.cmd + ' ' + self.input_file_name
def execute(self, wait = True):
"""
placeholder for execute
to be filled in by subclasses
"""
self.logger.debug(self.__repr__() + 'executing command \n' + self.runcmd)
# print self.runcmd
# subprocess.call( self.runcmd, shell=True, bufsize=0, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
if not wait:
self.runcmd + '&'
ExecCommandLine(self.runcmd)
class EDF2ASCOperator( CommandLineOperator ):
"""
EDF2ASCOperator provides the tools to convert an edf file to a pair of output files,
one containing the gaze samples (.gaz) and another containing all the messages/events (.msg).
It requires edf2asc command-line executable, which is assumed to be on the $PATH.
Missing values are imputed as 0.0001, time is represented as a floating point number for 2000Hz sampling.
"""
def __init__(self, input_object, **kwargs):
super(EDF2ASCOperator, self).__init__(input_object = input_object, cmd = 'edf2asc', **kwargs)
def configure(self, gazeOutputFileName = None, messageOutputFileName = None, settings = ' -t -ftime -y -z -v '):
"""
configure creates commands self.gazcmd and self.msgcmd which,
when executed on the command line, convert the edf 2 an asc file,
taking either the sample data or the event data, respectively.
it also creates self.runcmd which can be used to run both above
commands in succession, and which will be executed when calling
'execute' (as per CommandLineOperator behavior)
"""
if gazeOutputFileName == None:
self.gazeOutputFileName = os.path.splitext(self.input_file_name)[0] + '.gaz'
else:
self.gazeOutputFileName = gazeOutputFileName
if messageOutputFileName == None:
self.messageOutputFileName = os.path.splitext(self.input_file_name)[0] + '.msg'
else:
self.messageOutputFileName = messageOutputFileName
standardOutputFileName = os.path.splitext(self.input_file_name)[0] + '.asc'
self.intermediatecmd = self.cmd
self.intermediatecmd += settings
if sys.platform.startswith('win')
self.gazcmd = self.intermediatecmd + '-s -miss 0.0001 -vel "'+self.input_file_name+'"; move ' + '"' + standardOutputFileName.replace('|', '\|') + '" "' + self.gazeOutputFileName.replace('|', '\|') + '"'
self.msgcmd = self.intermediatecmd + '-e "'+self.input_file_name+'"; move ' + '"' + standardOutputFileName.replace('|', '\|') + '" "' + self.messageOutputFileName.replace('|', '\|') + '"'
else:
self.gazcmd = self.intermediatecmd + '-s -miss 0.0001 -vel "'+self.input_file_name+'"; mv ' + '"' + standardOutputFileName.replace('|', '\|') + '" "' + self.gazeOutputFileName.replace('|', '\|') + '"'
self.msgcmd = self.intermediatecmd + '-e "'+self.input_file_name+'"; mv ' + '"' + standardOutputFileName.replace('|', '\|') + '" "' + self.messageOutputFileName.replace('|', '\|') + '"'
self.runcmd = self.gazcmd + '; ' + self.msgcmd
|
Python
| 0.000001
|
@@ -4304,16 +4304,17 @@
h('win')
+:
%0A
|
c7439eb0d8a88a3a3584a3e73ed9badc910dcd05
|
Move newrelic initialization to the very start of wsgi initialization
|
contentcuration/contentcuration/wsgi.py
|
contentcuration/contentcuration/wsgi.py
|
"""
WSGI config for contentcuration project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contentcuration.settings")
# Attach newrelic APM
try:
import newrelic.agent
newrelic.agent.initialize()
except ImportError:
pass
application = get_wsgi_application()
|
Python
| 0
|
@@ -235,12 +235,152 @@
ort
-os%0A%0A
+logging%0Aimport os%0A%0A# Attach newrelic APM%0Atry:%0A import newrelic.agent%0A%0A newrelic.agent.initialize()%0Aexcept ImportError:%0A pass%0A%0Atry:%0A
from
@@ -425,17 +425,20 @@
ication%0A
-%0A
+
os.envir
@@ -509,158 +509,129 @@
s%22)%0A
-%0A# Attach newrelic APM%0Atry:%0A import newrelic.agent%0A%0A newrelic.agent.initialize()%0Aexcept ImportError:%0A pass%0A%0Aapplication = get_wsgi_application(
+ application = get_wsgi_application()%0Aexcept ImportError:%0A logging.warn(%22Django's WSGI wasn't successfully imported!%22
)%0A
|
a765ddc7782f1e17aeba23b2a66b61986e20351c
|
Stop popen patch correctly in test_agent_linux_utils
|
neutron/tests/unit/test_agent_linux_utils.py
|
neutron/tests/unit/test_agent_linux_utils.py
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Nicira, 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.
# @author: Dan Wendlandt, Nicira, Inc.
import fixtures
import mock
from neutron.agent.linux import utils
from neutron.tests import base
class AgentUtilsExecuteTest(base.BaseTestCase):
def setUp(self):
super(AgentUtilsExecuteTest, self).setUp()
self.root_helper = "echo"
self.test_file = self.useFixture(
fixtures.TempDir()).join("test_execute.tmp")
open(self.test_file, 'w').close()
instance = mock.patch("subprocess.Popen.communicate")
self.mock_popen = instance.start()
self.addCleanup(self.mock_popen.stop)
def test_without_helper(self):
expected = "%s\n" % self.test_file
self.mock_popen.return_value = [expected, ""]
result = utils.execute(["ls", self.test_file])
self.assertEqual(result, expected)
def test_with_helper(self):
expected = "ls %s\n" % self.test_file
self.mock_popen.return_value = [expected, ""]
result = utils.execute(["ls", self.test_file],
self.root_helper)
self.assertEqual(result, expected)
def test_stderr_true(self):
expected = "%s\n" % self.test_file
self.mock_popen.return_value = [expected, ""]
out = utils.execute(["ls", self.test_file], return_stderr=True)
self.assertIsInstance(out, tuple)
self.assertEqual(out, (expected, ""))
def test_check_exit_code(self):
self.mock_popen.return_value = ["", ""]
stdout = utils.execute(["ls", self.test_file[:-1]],
check_exit_code=False)
self.assertEqual(stdout, "")
def test_execute_raises(self):
self.mock_popen.side_effect = RuntimeError
self.assertRaises(RuntimeError, utils.execute,
["ls", self.test_file[:-1]])
def test_process_input(self):
expected = "%s\n" % self.test_file[:-1]
self.mock_popen.return_value = [expected, ""]
result = utils.execute(["cat"], process_input="%s\n" %
self.test_file[:-1])
self.assertEqual(result, expected)
def test_with_addl_env(self):
expected = "%s\n" % self.test_file
self.mock_popen.return_value = [expected, ""]
result = utils.execute(["ls", self.test_file],
addl_env={'foo': 'bar'})
self.assertEqual(result, expected)
class AgentUtilsGetInterfaceMAC(base.BaseTestCase):
def test_get_interface_mac(self):
expect_val = '01:02:03:04:05:06'
with mock.patch('fcntl.ioctl') as ioctl:
ioctl.return_value = ''.join(['\x00' * 18,
'\x01\x02\x03\x04\x05\x06',
'\x00' * 232])
actual_val = utils.get_interface_mac('eth0')
self.assertEqual(actual_val, expect_val)
class AgentUtilsReplaceFile(base.BaseTestCase):
def test_replace_file(self):
# make file to replace
with mock.patch('tempfile.NamedTemporaryFile') as ntf:
ntf.return_value.name = '/baz'
with mock.patch('os.chmod') as chmod:
with mock.patch('os.rename') as rename:
utils.replace_file('/foo', 'bar')
expected = [mock.call('w+', dir='/', delete=False),
mock.call().write('bar'),
mock.call().close()]
ntf.assert_has_calls(expected)
chmod.assert_called_once_with('/baz', 0o644)
rename.assert_called_once_with('/baz', '/foo')
|
Python
| 0.000001
|
@@ -1086,24 +1086,33 @@
-instance
+self.mock_popen_p
= mock.
@@ -1179,16 +1179,25 @@
n =
-instance
+self.mock_popen_p
.sta
@@ -1240,16 +1240,18 @@
ck_popen
+_p
.stop)%0A%0A
|
55d54f67111583dab4209639ef8e3d6430ea7939
|
Handle oversteer in turns.
|
src/Command_Interpreter.py
|
src/Command_Interpreter.py
|
# Motor driver for QuickBot_Follow.
# John Brewer 3/31/16
# Copyright (C) 2016 Jera Design LLC
# All Rights Reserverd
import Motor_Driver
import sys
Motor_Driver.init_pins()
print "Ready"
while True:
line = sys.stdin.readline().rstrip()
if not line:
break;
if line == "left":
print "turn left"
Motor_Driver.move(-70, 70, 0.05)
elif line == "right":
print "turn right"
Motor_Driver.move(70, -70, 0.05)
elif line == "straight":
print "go straight"
Motor_Driver.move(100, 98, 0.095)
else:
print "STOP"
|
Python
| 0
|
@@ -143,16 +143,39 @@
port sys
+%0Afrom time import sleep
%0A%0AMotor_
@@ -209,16 +209,37 @@
Ready%22%0A%0A
+last = %22%22%0Acount = 0%0A%0A
while Tr
@@ -364,16 +364,186 @@
n left%22%0A
+ if last != %22left%22:%0A count = 10%0A last = %22left%22%0A continue%0A if count %3E 0:%0A count = count - 1%0A continue%0A
@@ -565,28 +565,26 @@
ve(-
-70, 70
+90, 88
, 0.0
-5
+1
)%0A
-el
if l
@@ -622,24 +622,196 @@
turn right%22%0A
+ if last != %22right%22:%0A count = 10%0A last = %22right%22%0A continue%0A if count %3E 0:%0A count = count - 1%0A continue%0A
Moto
@@ -828,29 +828,27 @@
ove(
-7
+9
0, -
-70
+88
, 0.0
-5
+1
)%0A
-el
if l
@@ -890,24 +890,50 @@
o straight%22%0A
+ last = %22straight%22%0A
Moto
@@ -950,21 +950,19 @@
ove(
-100, 9
+70, 6
8, 0.0
-9
5)%0A
@@ -991,8 +991,31 @@
%22STOP%22%0A
+# last = %22STOP%22%0A
|
262dc0ebe113056e21010e061234dd6989a80a70
|
modify API to add parents
|
src/obudget/budget_lines/handlers.py
|
src/obudget/budget_lines/handlers.py
|
from datetime import datetime
import urllib
from django.db.models import Q
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.core.cache import cache
from django.db.models import Count
from piston.resource import Resource
from piston.handler import BaseHandler
from piston.utils import rc
from obudget.budget_lines.models import BudgetLine
DEFAULT_PAGE_LEN = 20
def limit_by_request(qs, request):
if 'num' in request.GET or 'page' in request.GET:
num = int(request.GET.get('num',DEFAULT_PAGE_LEN))
page = int(request.GET.get('page',0))
return qs[page*num:(page+1)*num]
return qs
def year_by_request(qs, request):
if 'year' in request.GET:
year = int(request.GET['year'])
return qs.filter(year=year)
return qs
def text_by_request(qs, request):
if 'text' in request.GET:
text = request.GET['text']
return qs.filter(title__icontains = text)
return qs
def depth_by_request(qs, request, budget_code):
start_depth = len(budget_code)
depth = request.GET.get('depth',0)
full = request.GET.get('full',None) == '1'
if full:
depth = 20 # to be on the safe side
if depth != None:
max_depth = start_depth + int(depth)*2
qs = qs.filter( budget_id_len__lte = max_depth )
return qs
class BudgetLineHandler(BaseHandler):
'''
API Documentation:
------------------
<url>/<budget-code>/?<params>
params:
------
year - year selection
num - page size
page - page index
full - 1/0, bring full subtree(s)
depth - >0, bring x layers of subtree(s)
text - search term, bring entries which contain the text
'''
allowed_methods = ('GET')
model = BudgetLine
qs = BudgetLine.objects.all()
fields = ('title', 'budget_id',
'amount_allocated','amount_revised', 'amount_used',
'inflation_factor',
'year',)
def read(self, request, **kwargs):
budget_code = kwargs["id"]
qs = self.qs.filter(budget_id__startswith=budget_code).order_by('-year','budget_id_len','budget_id')
qs = depth_by_request(qs, request, budget_code)
qs = year_by_request(qs, request)
qs = text_by_request(qs, request)
qs = limit_by_request(qs, request)
return qs
budget_line_handler= Resource(BudgetLineHandler)
|
Python
| 0
|
@@ -1992,16 +1992,55 @@
'year',
+%0A 'parent',%0A
)%0A %0A
@@ -2421,16 +2421,319 @@
eturn qs
+%0A %0A @classmethod%0A def parent(self, line):%0A l = line.containing_line%0A parent = %5B%5D%0A while l != None:%0A parent.append(%7B 'budget_id' : l.budget_id, %0A 'title' : l.title %7D)%0A l = l.containing_line%0A return parent%0A%0A
%0A%0Abudget
|
6486a888cbcec7285df92020f76e3f1c5fbba0e2
|
Load exchange rates in test setup. Make it posible to use --keepdb
|
bluebottle/test/test_runner.py
|
bluebottle/test/test_runner.py
|
from django.test.runner import DiscoverRunner
from django.db import connection
from tenant_schemas.utils import get_tenant_model
from bluebottle.test.utils import InitProjectDataMixin
class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin):
def setup_databases(self, *args, **kwargs):
result = super(MultiTenantRunner, self).setup_databases(*args, **kwargs)
# Create secondary tenant
connection.set_schema_to_public()
tenant_domain = 'testserver2'
tenant2 = get_tenant_model()(
domain_url=tenant_domain,
schema_name='test2',
client_name='test2')
tenant2.save(
verbosity=self.verbosity)
# Add basic data for tenant
connection.set_tenant(tenant2)
self.init_projects()
# Create main tenant
connection.set_schema_to_public()
tenant_domain = 'testserver'
tenant = get_tenant_model()(
domain_url=tenant_domain,
schema_name='test',
client_name='test')
tenant.save(
verbosity=self.verbosity)
connection.set_tenant(tenant)
return result
|
Python
| 0
|
@@ -71,16 +71,51 @@
nnection
+%0Afrom django.core import management
%0A%0Afrom t
@@ -538,16 +538,26 @@
tenant2
+, _created
= get_t
@@ -561,32 +561,54 @@
t_tenant_model()
+.objects.get_or_create
(%0A do
@@ -926,32 +926,113 @@
hema_to_public()
+%0A%0A management.call_command('loaddata', 'exchange_rates.json', verbosity=1)
%0A tenant_
@@ -1067,16 +1067,26 @@
tenant
+, _created
= get_t
@@ -1098,16 +1098,38 @@
_model()
+.objects.get_or_create
(%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.