commit stringlengths 40 40 | subject stringlengths 1 1.49k | old_file stringlengths 4 311 | new_file stringlengths 4 311 | new_contents stringlengths 1 29.8k | old_contents stringlengths 0 9.9k | lang stringclasses 3 values | proba float64 0 1 |
|---|---|---|---|---|---|---|---|
8fb97bc0b3a22b912958974636051447170a0b02 | Add user_account to the user profile admin as a read-only field. | go/base/admin.py | go/base/admin.py | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from go.base.models import GoUser, UserProfile, UserOrganisation
from go.base.forms import GoUserCreationForm, GoUserChangeForm
class UserProfileInline(admin.StackedInline):
model = UserProfile
fields = ('organisation', 'is_admin', 'user_account')
readonly_fields = ('user_account',)
can_delete = False
class GoUserAdmin(UserAdmin):
# The forms to add and change user instances
inlines = (UserProfileInline,)
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference the removed 'username' field
fieldsets = (
(None, {'fields': ('email', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2')}
),
)
form = GoUserChangeForm
add_form = GoUserCreationForm
list_display = ('email', 'first_name', 'last_name', 'is_superuser',
'is_staff', 'is_active')
search_fields = ('email', 'first_name', 'last_name')
ordering = ('email',)
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'organisation', 'is_admin')
admin.site.register(GoUser, GoUserAdmin)
admin.site.register(UserProfile, UserProfileAdmin)
admin.site.register(UserOrganisation)
| from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from go.base.models import GoUser, UserProfile, UserOrganisation
from go.base.forms import GoUserCreationForm, GoUserChangeForm
class UserProfileInline(admin.StackedInline):
model = UserProfile
fields = ('organisation', 'is_admin')
can_delete = False
class GoUserAdmin(UserAdmin):
# The forms to add and change user instances
inlines = (UserProfileInline,)
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference the removed 'username' field
fieldsets = (
(None, {'fields': ('email', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2')}
),
)
form = GoUserChangeForm
add_form = GoUserCreationForm
list_display = ('email', 'first_name', 'last_name', 'is_superuser',
'is_staff', 'is_active')
search_fields = ('email', 'first_name', 'last_name')
ordering = ('email',)
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'organisation', 'is_admin')
admin.site.register(GoUser, GoUserAdmin)
admin.site.register(UserProfile, UserProfileAdmin)
admin.site.register(UserOrganisation)
| Python | 0 |
56d3db6aae71c88ff8b55bb1d173abc025be7e8c | Add test of a write command | jacquard/tests/test_cli.py | jacquard/tests/test_cli.py | import io
import unittest.mock
import contextlib
import textwrap
from jacquard.cli import main
from jacquard.storage.dummy import DummyStore
def test_smoke_cli_help():
try:
output = io.StringIO()
with contextlib.redirect_stdout(output):
main(['--help'])
except SystemExit:
pass
assert output.getvalue().startswith("usage: ")
def test_help_message_when_given_no_subcommand():
try:
output = io.StringIO()
with contextlib.redirect_stdout(output):
main([])
except SystemExit:
pass
assert output.getvalue().startswith("usage: ")
def test_run_basic_command():
config = unittest.mock.Mock()
config.storage = DummyStore('', data={
'foo': 'bar',
})
output = io.StringIO()
with contextlib.redirect_stdout(output):
main(['storage-dump'], config=config)
assert output.getvalue().strip() == textwrap.dedent("""
foo
===
'bar'
"""
).strip()
def test_run_write_command():
config = unittest.mock.Mock()
config.storage = DummyStore('', data={})
output = io.StringIO()
with contextlib.redirect_stdout(output):
main(['set-default', 'foo', '"bar"'], config=config)
assert output.getvalue() == ''
assert config.storage.data == {'defaults': '{"foo": "bar"}'}
| import io
import unittest.mock
import contextlib
import textwrap
from jacquard.cli import main
from jacquard.storage.dummy import DummyStore
def test_smoke_cli_help():
try:
output = io.StringIO()
with contextlib.redirect_stdout(output):
main(['--help'])
except SystemExit:
pass
assert output.getvalue().startswith("usage: ")
def test_help_message_when_given_no_subcommand():
try:
output = io.StringIO()
with contextlib.redirect_stdout(output):
main([])
except SystemExit:
pass
assert output.getvalue().startswith("usage: ")
def test_run_basic_command():
config = unittest.mock.Mock()
config.storage = DummyStore('', data={
'foo': 'bar',
})
output = io.StringIO()
with contextlib.redirect_stdout(output):
main(['storage-dump'], config=config)
assert output.getvalue().strip() == textwrap.dedent("""
foo
===
'bar'
"""
).strip()
| Python | 0.000268 |
ae7f8c0deaaec2cbc830113ea19f06ca6aa169c7 | Use `persist.errors` for the goto commands again | goto_commands.py | goto_commands.py | import sublime
import sublime_plugin
from itertools import dropwhile, takewhile
from .lint import persist
"""
Implement typical Goto Next Previous Error Commands.
"""
class SublimeLinterGotoError(sublime_plugin.WindowCommand):
def run(self, direction='next', count=1, wrap=False):
goto(self.window.active_view(), direction, count, wrap)
def goto(view, direction, count, wrap):
bid = view.buffer_id()
errors = persist.errors.get(bid)
if not errors:
flash(view, 'No problems')
return
cursor = view.sel()[0].begin()
# Filter regions under the cursor, bc we don't want to jump to them.
# Also filter duplicate start positions.
all_jump_positions = sorted({
error['region'].begin()
for error in errors
if not error['region'].contains(cursor)})
# Edge case: Since we filtered, it is possible we get here with nothing
# left. That is the case if we sit on the last remaining error, where we
# don't have anything to jump to and even `wrap` becomes a no-op.
if len(all_jump_positions) == 0:
flash(view, 'No more problems')
return
def before_current_pos(pos):
return pos < cursor
next_positions = dropwhile(before_current_pos, all_jump_positions)
previous_positions = takewhile(before_current_pos, all_jump_positions)
reverse = direction == 'previous'
jump_positions = list(previous_positions if reverse else next_positions)
if reverse:
jump_positions = list(reversed(jump_positions))
if not jump_positions:
if wrap:
point = all_jump_positions[-1] if reverse else all_jump_positions[0]
flash(
view,
'Jumped to {} problem'.format('last' if reverse else 'first'))
else:
flash(
view,
'No more problems {}'.format('above' if reverse else 'below'))
return
elif len(jump_positions) <= count:
# If we cannot jump wide enough, do not wrap, but jump as wide as
# possible to reduce disorientation.
point = jump_positions[-1]
else:
point = jump_positions[count - 1]
move_to(view, point)
class _sublime_linter_goto_line(sublime_plugin.TextCommand):
def run(self, edit, point):
self.view.sel().clear()
self.view.sel().add(point)
self.view.show(point)
def move_to(view, point):
window = view.window()
if view == window.active_view():
# If the region we're moving to is already visible, then we don't want
# the view to suddenly scroll. If the region is not visible, then we
# want the surrounding area of the region to be visible.
# We need to a use a custom goto line command for several reasons:
# * ST's goto line command doesn't accept a col argument.
# * SL requires that on_selection_modified events MUST be triggered for
# each move.
# See https://github.com/SublimeLinter/SublimeLinter/pull/867.
view.run_command('_sublime_linter_goto_line', {'point': point})
else:
filename = view.file_name() or "<untitled {}>".format(view.buffer_id())
line, col = view.rowcol(point)
target = "{}:{}:{}".format(filename, line + 1, col + 1)
window.open_file(target, sublime.ENCODED_POSITION)
def flash(view, msg):
window = view.window() or sublime.active_window()
window.status_message(msg)
| import sublime
import sublime_plugin
from itertools import dropwhile, takewhile
"""
Implement typical Goto Next Previous Error Commands.
"""
class SublimeLinterGotoError(sublime_plugin.WindowCommand):
def run(self, direction='next', count=1, wrap=False):
goto(self.window.active_view(), direction, count, wrap)
STORAGE_KEY = 'SL.{vid}.region_keys'
def get_region_keys(view):
setting_key = STORAGE_KEY.format(vid=view.id())
return set(view.settings().get(setting_key) or [])
def get_highlighted_regions(view):
return [
region
for key in get_region_keys(view)
if '.Highlights.' in key
for region in view.get_regions(key)
]
def goto(view, direction, count, wrap):
cursor = view.sel()[0].begin()
regions = get_highlighted_regions(view)
if not regions:
flash(view, 'No problems')
return
# Filter regions under the cursor, bc we don't want to jump to them.
# Also filter duplicate start positions.
all_jump_positions = sorted({
region.a
for region in regions
if not region.contains(cursor)})
# Edge case: Since we filtered, it is possible we get here with nothing
# left. That is the case if we sit on the last remaining error, where we
# don't have anything to jump to and even `wrap` becomes a no-op.
if len(all_jump_positions) == 0:
flash(view, 'No more problems')
return
def before_current_pos(pos):
return pos < cursor
next_positions = dropwhile(before_current_pos, all_jump_positions)
previous_positions = takewhile(before_current_pos, all_jump_positions)
reverse = direction == 'previous'
jump_positions = list(previous_positions if reverse else next_positions)
if reverse:
jump_positions = list(reversed(jump_positions))
if not jump_positions:
if wrap:
point = all_jump_positions[-1] if reverse else all_jump_positions[0]
flash(
view,
'Jumped to {} problem'.format('last' if reverse else 'first'))
else:
flash(
view,
'No more problems {}'.format('above' if reverse else 'below'))
return
elif len(jump_positions) <= count:
# If we cannot jump wide enough, do not wrap, but jump as wide as
# possible to reduce disorientation.
point = jump_positions[-1]
else:
point = jump_positions[count - 1]
move_to(view, point)
class _sublime_linter_goto_line(sublime_plugin.TextCommand):
def run(self, edit, point):
self.view.sel().clear()
self.view.sel().add(point)
self.view.show(point)
def move_to(view, point):
window = view.window()
if view == window.active_view():
# If the region we're moving to is already visible, then we don't want
# the view to suddenly scroll. If the region is not visible, then we
# want the surrounding area of the region to be visible.
# We need to a use a custom goto line command for several reasons:
# * ST's goto line command doesn't accept a col argument.
# * SL requires that on_selection_modified events MUST be triggered for
# each move.
# See https://github.com/SublimeLinter/SublimeLinter/pull/867.
view.run_command('_sublime_linter_goto_line', {'point': point})
else:
filename = view.file_name() or "<untitled {}>".format(view.buffer_id())
line, col = view.rowcol(point)
target = "{}:{}:{}".format(filename, line + 1, col + 1)
window.open_file(target, sublime.ENCODED_POSITION)
def flash(view, msg):
window = view.window() or sublime.active_window()
window.status_message(msg)
| Python | 0 |
1d31282a9781e8eef4aafc0549c01056d4fc03d0 | Bump version. | armet/_version.py | armet/_version.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division
__version_info__ = (0, 4, 22)
__version__ = '.'.join(map(str, __version_info__))
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division
__version_info__ = (0, 4, 21)
__version__ = '.'.join(map(str, __version_info__))
| Python | 0 |
cec594e525fb889029b85b1f92f89170ca330332 | Remove unnecessary "is not supported" verbiage. | zerver/webhooks/trello/view/__init__.py | zerver/webhooks/trello/view/__init__.py | # Webhooks for external integrations.
from typing import Any, Mapping, Optional, Tuple
import orjson
from django.http import HttpRequest, HttpResponse
from zerver.decorator import api_key_only_webhook_view, return_success_on_head_request
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import UnexpectedWebhookEventType, check_send_webhook_message
from zerver.models import UserProfile
from .board_actions import SUPPORTED_BOARD_ACTIONS, process_board_action
from .card_actions import IGNORED_CARD_ACTIONS, SUPPORTED_CARD_ACTIONS, process_card_action
@api_key_only_webhook_view('Trello')
@return_success_on_head_request
@has_request_variables
def api_trello_webhook(request: HttpRequest,
user_profile: UserProfile,
payload: Mapping[str, Any]=REQ(argument_type='body')) -> HttpResponse:
payload = orjson.loads(request.body)
action_type = payload['action'].get('type')
message = get_subject_and_body(payload, action_type)
if message is None:
return json_success()
else:
subject, body = message
check_send_webhook_message(request, user_profile, subject, body)
return json_success()
def get_subject_and_body(payload: Mapping[str, Any], action_type: str) -> Optional[Tuple[str, str]]:
if action_type in SUPPORTED_CARD_ACTIONS:
return process_card_action(payload, action_type)
if action_type in IGNORED_CARD_ACTIONS:
return None
if action_type in SUPPORTED_BOARD_ACTIONS:
return process_board_action(payload, action_type)
raise UnexpectedWebhookEventType("Trello", action_type)
| # Webhooks for external integrations.
from typing import Any, Mapping, Optional, Tuple
import orjson
from django.http import HttpRequest, HttpResponse
from zerver.decorator import api_key_only_webhook_view, return_success_on_head_request
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import UnexpectedWebhookEventType, check_send_webhook_message
from zerver.models import UserProfile
from .board_actions import SUPPORTED_BOARD_ACTIONS, process_board_action
from .card_actions import IGNORED_CARD_ACTIONS, SUPPORTED_CARD_ACTIONS, process_card_action
@api_key_only_webhook_view('Trello')
@return_success_on_head_request
@has_request_variables
def api_trello_webhook(request: HttpRequest,
user_profile: UserProfile,
payload: Mapping[str, Any]=REQ(argument_type='body')) -> HttpResponse:
payload = orjson.loads(request.body)
action_type = payload['action'].get('type')
message = get_subject_and_body(payload, action_type)
if message is None:
return json_success()
else:
subject, body = message
check_send_webhook_message(request, user_profile, subject, body)
return json_success()
def get_subject_and_body(payload: Mapping[str, Any], action_type: str) -> Optional[Tuple[str, str]]:
if action_type in SUPPORTED_CARD_ACTIONS:
return process_card_action(payload, action_type)
if action_type in IGNORED_CARD_ACTIONS:
return None
if action_type in SUPPORTED_BOARD_ACTIONS:
return process_board_action(payload, action_type)
raise UnexpectedWebhookEventType("Trello", f'{action_type} is not supported')
| Python | 0 |
04605ee82108695989e8f10b2287d43f6df448f8 | Update noisy_linear.py | chainerrl/links/noisy_linear.py | chainerrl/links/noisy_linear.py | import chainer
import chainer.functions as F
from chainer.initializers import Constant
import chainer.links as L
import numpy
from chainerrl.initializers import VarianceScalingConstant
class FactorizedNoisyLinear(chainer.Chain):
"""Linear layer in Factorized Noisy Network
Args:
mu_link (L.Linear): Linear link that computes mean of output.
sigma_scale (float): The hyperparameter sigma_0 in the original paper.
Scaling factor of the initial weights of noise-scaling parameters.
"""
def __init__(self, mu_link, sigma_scale=0.4):
super(FactorizedNoisyLinear, self).__init__()
self.out_size = mu_link.out_size
self.nobias = not ('/b' in [name for name, _ in mu_link.namedparams()])
W_data = mu_link.W.data
in_size = None if W_data is None else W_data.shape[1]
with self.init_scope():
self.mu = mu_link
self.mu.W.initializer = Uniform(1 / numpy.sqrt(in_size))
if not self.nobias:
self.mu.b.initializer = Uniform(1 / numpy.sqrt(in_size))
self.mu.W.initialize((self.out_size, in_size))
self.mu.b.initialize((self.out_size))
self.sigma = L.Linear(
in_size=in_size, out_size=self.out_size, nobias=self.nobias,
initialW=VarianceScalingConstant(sigma_scale),
initial_bias=Constant(sigma_scale / numpy.sqrt(self.out_size)))
device_id = self.mu._device_id
if device_id is not None:
self.to_gpu(device_id)
def _eps(self, shape, dtype):
xp = self.xp
r = xp.random.standard_normal(shape).astype(dtype)
# apply the function f
return xp.copysign(xp.sqrt(xp.abs(r)), r)
def __call__(self, x):
if self.mu.W.data is None:
self.mu.W.initialize((self.out_size, numpy.prod(x.shape[1:])))
if self.sigma.W.data is None:
self.sigma.W.initialize((self.out_size, numpy.prod(x.shape[1:])))
# use info of sigma.W to avoid strange error messages
dtype = self.sigma.W.dtype
out_size, in_size = self.sigma.W.shape
eps_x = self._eps(in_size, dtype)
eps_y = self._eps(out_size, dtype)
W = self.mu.W + self.sigma.W * self.xp.outer(eps_y, eps_x)
if self.nobias:
return F.linear(x, W)
else:
b = self.mu.b + self.sigma.b * eps_y
return F.linear(x, W, b)
| import chainer
import chainer.functions as F
from chainer.initializers import Constant
import chainer.links as L
import numpy
from chainerrl.initializers import VarianceScalingConstant
class FactorizedNoisyLinear(chainer.Chain):
"""Linear layer in Factorized Noisy Network
Args:
mu_link (L.Linear): Linear link that computes mean of output.
sigma_scale (float): The hyperparameter sigma_0 in the original paper.
Scaling factor of the initial weights of noise-scaling parameters.
"""
def __init__(self, mu_link, sigma_scale=0.4):
super(FactorizedNoisyLinear, self).__init__()
self.out_size = mu_link.out_size
self.nobias = not ('/b' in [name for name, _ in mu_link.namedparams()])
W_data = mu_link.W.data
in_size = None if W_data is None else W_data.shape[1]
with self.init_scope():
self.mu = mu_link
self.sigma = L.Linear(
in_size=in_size, out_size=self.out_size, nobias=self.nobias,
initialW=VarianceScalingConstant(sigma_scale),
initial_bias=Constant(sigma_scale))
device_id = self.mu._device_id
if device_id is not None:
self.to_gpu(device_id)
def _eps(self, shape, dtype):
xp = self.xp
r = xp.random.standard_normal(shape).astype(dtype)
# apply the function f
return xp.copysign(xp.sqrt(xp.abs(r)), r)
def __call__(self, x):
if self.mu.W.data is None:
self.mu.W.initialize((self.out_size, numpy.prod(x.shape[1:])))
if self.sigma.W.data is None:
self.sigma.W.initialize((self.out_size, numpy.prod(x.shape[1:])))
# use info of sigma.W to avoid strange error messages
dtype = self.sigma.W.dtype
out_size, in_size = self.sigma.W.shape
eps_x = self._eps(in_size, dtype)
eps_y = self._eps(out_size, dtype)
W = self.mu.W + self.sigma.W * self.xp.outer(eps_y, eps_x)
if self.nobias:
return F.linear(x, W)
else:
b = self.mu.b + self.sigma.b * eps_y
return F.linear(x, W, b)
| Python | 0 |
67c40fff7813b91b874c5fada042bfc0c6990d52 | Bump version | typepy/__version__.py | typepy/__version__.py | # encoding: utf-8
from datetime import datetime
__author__ = "Tsuyoshi Hombashi"
__copyright__ = "Copyright 2017-{}, {}".format(datetime.now().year, __author__)
__license__ = "MIT License"
__version__ = "0.3.2"
__maintainer__ = __author__
__email__ = "tsuyoshi.hombashi@gmail.com"
| # encoding: utf-8
from datetime import datetime
__author__ = "Tsuyoshi Hombashi"
__copyright__ = "Copyright 2017-{}, {}".format(datetime.now().year, __author__)
__license__ = "MIT License"
__version__ = "0.3.1"
__maintainer__ = __author__
__email__ = "tsuyoshi.hombashi@gmail.com"
| Python | 0 |
7f774d08ecf9d64a732a8471dd6f36b9d0e2826a | Update entity_main.py | EntityExtractor/src/entity_main.py | EntityExtractor/src/entity_main.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created by Lalitha Madhuri Putchala on Dec 10 2017
"""
import spacy
import docx2txt
import re
from docx import Document
from utils import get_sentence_tokens, tag_text, highlight_text
class Entity:
def __init__(self):
self.raw_data = docx2txt.process('Contract_Input.docx')
self.doc = Document('Contract_Input.docx')
def highlight_address_fields(self):
# extract street address/zipcodes/ proper format address and improper format address using python regex
street_address_exp = re.compile(
u'\d{1,4} [\w\s]{1,20}(?:street|st|avenue|ave|road|rd|highway|hwy|square|sq|trail|trl|drive|dr|court|ct|park|parkway|pkwy|circle|cir|boulevard|blvd)\W?(?=\D|$)',
re.IGNORECASE)
street_addresses = re.findall(street_address_exp, self.raw_data)
zip_code_exp = re.compile(r'\b\d{5}(?:[-\s]\d{4})?\b')
zip_codes = re.findall(zip_code_exp, self.raw_data)
proper_address_exp = "[0-9]{1,5} .+, .+, [A-Z]{2} [0-9]{5}"
proper_addresses = re.findall(proper_address_exp, self.raw_data)
# logic to handle the improper format address instead of using regex functions
sentence_tokens = get_sentence_tokens(self.raw_data)
for i in range(len(sentence_tokens)):
if sentence_tokens[i][0] == 'Address:':
improper_format = sentence_tokens[i + 1][0]
address_details = list()
address_details.extend(street_addresses)
address_details.extend(zip_codes)
address_details.extend(proper_addresses)
address_details.append(improper_format)
# highlight address fields
for each in address_details:
highlight_text(self.doc, each.strip())
def highlight_contact_details(self):
contact_details = list()
# Get emails and phone numbers
emails = re.findall(r'[\w\.-]+@[\w\.-]+', self.raw_data)
phonenumbers = re.findall(
r'\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}', self.raw_data)
contact_details.extend(emails)
contact_details.extend(phonenumbers)
for contact in contact_details:
highlight_text(self.doc, contact)
def highlight_dates(self):
# Get dates
match = re.search(r'(\d+/\d+/\d+)', self.raw_data)
highlight_text(self.doc, match.group(1))
def tag_person_entities(self):
# use pre-trained spacy models to get the 'PERSON' entities
model = spacy.load('en_core_web_sm')
mydata = model(self.raw_data)
person_labels = list()
for each in mydata.ents:
if each.label_ == 'PERSON':
person_labels.append(each.text)
unique_person_labels = set(person_labels)
for label in unique_person_labels:
tag_text(self.doc, label)
print (person_labels)
return len(person_labels)
def save_document(self):
self.doc.save('Contract_Output.docx')
| #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created by Lalitha Madhuri Putchala on Dec 10 2017
"""
import unittest
from entity_main import Entity
from docx import Document
import docx2txt
class TestEntity(unittest.TestCase):
'''The below function verifies the basic sanity functionality of the program
by validating the word count in the document before and after the highlighting
of the text'''
def test_sanity(self):
et = Entity()
et.highlight_address_fields()
et.highlight_contact_details()
et.highlight_dates()
person_count = et.tag_person_entities()
et.save_document()
# load the new document with highlighted text
new_raw_data = docx2txt.process('Contract_Output.docx')
new_cnt = 0
word_tokens = new_raw_data.split(' ')
for each_token in word_tokens:
if '[PERSON]' in each_token:
new_cnt +=1
self.assertEqual(person_count, new_cnt)
if __name__ == '__main__':
unittest.main()
| Python | 0.000002 |
fa9e5956adadd20d546129b07bf4b71772cd5b05 | make small optimization to vector multiply/divide | pyschool/static/external/brython/Lib/site-packages/glow/vector.py | pyschool/static/external/brython/Lib/site-packages/glow/vector.py | from javascript import JSConstructor, console
class vec:
def __init__(self, x=0, y=0, z=0):
self._vec=JSConstructor(glowscript.vec)(x,y,z)
self.add=self.__add__
self.sub=self.__sub__
self.multiply=self.__mul__
self.divide=self.__truediv__=self.__div__
#vec should be a glowscript vec, not an instance of this class
def _set_vec(self, vec):
self._vec=vec
@property
def x(self):
return self._vec.x
@x.setter
def x(self, value):
self._vec.x=value
@property
def y(self):
return self._vec.y
@y.setter
def y(self, value):
self._vec.y=value
@property
def z(self):
return self._vec.z
@z.setter
def z(self, value):
self._vec.z=value
def __add__(self, other):
if isinstance(other, vec):
_v=vec()
_v._set_vec(self._vec.add(other._vec))
return _v
raise ImplementationError("addition of vec and %s not implemented yet" % type(other))
def __sub__(self, other):
if isinstance(other, vec):
_v=vec()
_v._set_vec(self._vec.sub(other._vec))
return _v
raise ImplementationError("subtraction of vec and %s not is implemented yet" % type(other))
def __mul__(self, other):
if isinstance(other, (int, float)):
_v=vec()
_v._set_vec(self._vec.multiply(other))
return _v
raise ImplementationError("multiplication of vec and %s is not implemented yet" % type(other))
def __div__(self, other):
if isinstance(other, (int, float)):
_v=vec()
_v._set_vec(self._vec.divide(other))
return _v
raise ImplementationError("division of vec and %s is not implemented yet" % type(other))
def __eq__(self, other):
return self._vec.equals(other._vec)
def __repr__(self):
return self._vec.toString()
def __str__(self):
return self._vec.toString()
def comp(self, other):
return self._vec.comp(other._vec)
def cross(self, other):
return self._vec.cross(other._vec)
def diff_angle(self, other):
return self._vec.diff_angle(other._vec)
def dot(self):
return self._vec.dot()
def mag(self):
return self._vec.mag()
def mag2(self):
return self._vec.mag2()
def norm(self):
_v=vec()
_v._set_vec(self._vec.norm())
return _v
def proj(self, other):
_v=vec()
_v._set_vec(self._vec.proj(other._vec))
return _v
def random(self):
_v = vec()
_v._set_vec(self._vec.random())
return _v
def rotate(self, **kwargs):
_v = vec()
_v._set_vec(self._vec.rotate(kwargs))
return _v
def to_glowscript(self):
return self._vec
| from javascript import JSConstructor, console
class vec:
def __init__(self, x=0, y=0, z=0):
self._vec=JSConstructor(glowscript.vec)(x,y,z)
self.add=self.__add__
self.sub=self.__sub__
self.multiply=self.__mul__
self.divide=self.__truediv__=self.__div__
#vec should be a glowscript vec, not an instance of this class
def _set_vec(self, vec):
self._vec=vec
@property
def x(self):
return self._vec.x
@x.setter
def x(self, value):
self._vec.x=value
@property
def y(self):
return self._vec.y
@y.setter
def y(self, value):
self._vec.y=value
@property
def z(self):
return self._vec.z
@z.setter
def z(self, value):
self._vec.z=value
def __add__(self, other):
if isinstance(other, vec):
_v=vec()
_v._set_vec(self._vec.add(other._vec))
return _v
raise ImplementationError("addition of vec and %s not implemented yet" % type(other))
def __sub__(self, other):
if isinstance(other, vec):
_v=vec()
_v._set_vec(self._vec.sub(other._vec))
return _v
raise ImplementationError("subtraction of vec and %s not is implemented yet" % type(other))
def __mul__(self, other):
if isinstance(other, int) or isinstance(other, float):
_v=vec()
_v._set_vec(self._vec.multiply(other))
return _v
raise ImplementationError("multiplication of vec and %s is not implemented yet" % type(other))
def __div__(self, other):
if isinstance(other, int) or isinstance(other, float):
_v=vec()
_v._set_vec(self._vec.divide(other))
return _v
raise ImplementationError("division of vec and %s is not implemented yet" % type(other))
def __eq__(self, other):
return self._vec.equals(other._vec)
def __repr__(self):
return self._vec.toString()
def __str__(self):
return self._vec.toString()
def comp(self, other):
return self._vec.comp(other._vec)
def cross(self, other):
return self._vec.cross(other._vec)
def diff_angle(self, other):
return self._vec.diff_angle(other._vec)
def dot(self):
return self._vec.dot()
def mag(self):
return self._vec.mag()
def mag2(self):
return self._vec.mag2()
def norm(self):
_v=vec()
_v._set_vec(self._vec.norm())
return _v
def proj(self, other):
_v=vec()
_v._set_vec(self._vec.proj(other._vec))
return _v
def random(self):
_v = vec()
_v._set_vec(self._vec.random())
return _v
def rotate(self, **kwargs):
_v = vec()
_v._set_vec(self._vec.rotate(kwargs))
return _v
def to_glowscript(self):
return self._vec
| Python | 0.000001 |
835da41ffd1433c36bdc585a3154434c60bdbb8f | Fix lint | biggraphite/drivers/_utils.py | biggraphite/drivers/_utils.py | #!/usr/bin/env python
# Copyright 2016 Criteo
#
# 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.
"""Functions currently used by the Cassandra driver but not specific to it."""
from __future__ import absolute_import
from __future__ import print_function
import threading
try:
from opencensus.trace import execution_context
except ImportError:
execution_context = None
from biggraphite import accessor as bg_accessor
class Error(bg_accessor.Error):
"""Base class for all exceptions from this module."""
class CountDown(object):
"""Decrements a count, calls a callback when it reaches 0.
This is used to wait for queries to complete without storing & sorting their results.
"""
__slots__ = ("_canceled", "count", "_lock", "_on_zero")
def __init__(self, count, on_zero):
"""Record parameters.
Args:
count: The integer that will be decremented, must be > 0
on_zero: called once count reaches zero, see decrement
"""
assert count > 0
self.count = count
self._canceled = False
self._lock = threading.Lock()
self._on_zero = on_zero
def cancel(self, reason):
"""Call the callback now with reason as argument."""
with self._lock:
if self._canceled:
return
self._canceled = True
self._on_zero(reason)
def decrement(self):
"""Call the callback if count reached zero, with None as argument."""
with self._lock:
self.count -= 1
if self._canceled:
return
elif not self.count:
self._on_zero(None)
def on_result(self, unused_result):
"""Call decrement(), suitable for Cassandra's execute_async."""
self.decrement()
def on_failure(self, exc):
"""Call cancel(), suitable for Cassandra's execute_async."""
self.cancel(Error(exc))
def list_from_str(value):
"""Convert a comma separated string into a list.
Args:
value: str or list or set.
Returns:
list a list of values.
"""
if type(value) is str and value:
value = [s.strip() for s in value.split(",")]
elif type(value) in (list, set) and value:
value = list(value)
elif value is None:
value = []
elif not value:
value = []
else:
raise Error("Unkown type for '%s'" % (value))
return value
def bool_from_str(value):
"""Convert a user-specified string to a bool."""
if value == "True":
return value
elif value == "False":
return value
elif type(value) is bool:
return value
return str(value)
def trace_accessor_func(func):
"""Decorator for tracing of functions."""
if not execution_context:
return func
def tracer(self, *args, **kwargs):
if not hasattr(self, 'module_name'):
self.module_name = func.__module__.split('.')[-1]
tracer = execution_context.get_opencensus_tracer()
with tracer.span(name=self.module_name + '.' + func.__name__):
return func(self, *args, **kwargs)
return tracer
| #!/usr/bin/env python
# Copyright 2016 Criteo
#
# 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.
"""Functions currently used by the Cassandra driver but not specific to it."""
from __future__ import absolute_import
from __future__ import print_function
import threading
try:
from opencensus.trace import execution_context
except ImportError:
execution_context = None
from biggraphite import accessor as bg_accessor
class Error(bg_accessor.Error):
"""Base class for all exceptions from this module."""
class CountDown(object):
"""Decrements a count, calls a callback when it reaches 0.
This is used to wait for queries to complete without storing & sorting their results.
"""
__slots__ = ("_canceled", "count", "_lock", "_on_zero")
def __init__(self, count, on_zero):
"""Record parameters.
Args:
count: The integer that will be decremented, must be > 0
on_zero: called once count reaches zero, see decrement
"""
assert count > 0
self.count = count
self._canceled = False
self._lock = threading.Lock()
self._on_zero = on_zero
def cancel(self, reason):
"""Call the callback now with reason as argument."""
with self._lock:
if self._canceled:
return
self._canceled = True
self._on_zero(reason)
def decrement(self):
"""Call the callback if count reached zero, with None as argument."""
with self._lock:
self.count -= 1
if self._canceled:
return
elif not self.count:
self._on_zero(None)
def on_result(self, unused_result):
"""Call decrement(), suitable for Cassandra's execute_async."""
self.decrement()
def on_failure(self, exc):
"""Call cancel(), suitable for Cassandra's execute_async."""
self.cancel(Error(exc))
def list_from_str(value):
"""Convert a comma separated string into a list.
Args:
value: str or list or set.
Returns:
list a list of values.
"""
if type(value) is str and value:
value = [s.strip() for s in value.split(",")]
elif type(value) in (list, set) and value:
value = list(value)
elif value is None:
value = []
elif not value:
value = []
else:
raise Error("Unkown type for '%s'" % (value))
return value
def bool_from_str(value):
"""Convert a user-specified string to a bool."""
if value == "True":
return value
elif value == "False":
return value
elif type(value) is bool:
return value
return str(value)
def trace_accessor_func(func):
if not execution_context:
return func
def tracer(self, *args, **kwargs):
if not hasattr(self, 'module_name'):
self.module_name = func.__module__.split('.')[-1]
tracer = execution_context.get_opencensus_tracer()
with tracer.span(name=self.module_name + '.' + func.__name__) as span:
return func(self, *args, **kwargs)
return tracer
| Python | 0.000032 |
4b14f12fa8bb6dca7ad91f187e7765bef27c0d65 | Add some options | classes/admin.py | classes/admin.py | from django.contrib import admin
from classes.models import Attendee
from classes.models import Attendance
from classes.models import Session
from classes.models import WalkinClass
class AttendanceInline(admin.TabularInline):
model = Attendance
extra = 1
verbose_name = 'Attendee'
verbose_name_plural = 'Attendees'
fields = ('attendee', 'start_date_time', "stop_date_time", 'notes')
search_fields = 'name', 'phone'
class SessionInline(admin.TabularInline):
model = Session
extra = 1
fields = ('start_date_time', 'stop_date_time', 'teacher')
class AttendeeAdmin(admin.ModelAdmin):
pass
class SessionAdmin(admin.ModelAdmin):
inlines = [
AttendanceInline,
]
fields = ('walk_in_class','teacher', 'start_date_time', "stop_date_time", )
list_display= ('walk_in_class', 'start_date_time',)
date_hierarchy = 'start_date_time'
list_filter = ['walk_in_class', 'start_date_time', 'teacher']
ordering = ['-start_date_time']
class WalkinClassAdmin(admin.ModelAdmin):
inlines = [
SessionInline,
]
admin.site.register(Attendee, AttendeeAdmin)
admin.site.register(Session, SessionAdmin)
admin.site.register(WalkinClass, WalkinClassAdmin)
| from django.contrib import admin
from classes.models import Attendee
from classes.models import Attendance
from classes.models import Session
from classes.models import WalkinClass
class AttendanceInline(admin.TabularInline):
model = Attendance
extra = 1
verbose_name = 'Attendee'
verbose_name_plural = 'Attendees'
fields = ('attendee', 'start_date_time', "stop_date_time", 'notes')
class SessionInline(admin.TabularInline):
model = Session
extra = 1
fields = ('start_date_time', 'stop_date_time', 'teacher')
class AttendeeAdmin(admin.ModelAdmin):
pass
class SessionAdmin(admin.ModelAdmin):
inlines = [
AttendanceInline,
]
fields = ('walk_in_class','teacher', 'start_date_time', "stop_date_time", )
list_display= ('walk_in_class', 'start_date_time',)
class WalkinClassAdmin(admin.ModelAdmin):
inlines = [
SessionInline,
]
admin.site.register(Attendee, AttendeeAdmin)
admin.site.register(Session, SessionAdmin)
admin.site.register(WalkinClass, WalkinClassAdmin)
| Python | 0.000535 |
7bdf0a3121d539e0a98ffa68a964bfd022fe43a5 | Make the stitcher executable | atram_stitcher.py | atram_stitcher.py | #!/usr/bin/env python3
"""
Start the atram exon stitcher.
This wrapper module parses the input arguments and passes them to the module
that does the actual stitching (core_stitcher.py).
"""
from os.path import join
from datetime import date
import argparse
import textwrap
import lib.db as db
import lib.log as log
import lib.util as util
from lib.core_stitcher import Sticher
def parse_command_line():
"""Process command-line arguments."""
description = """
This program will find and stitch together exons from targeted
assemblies using amino acid targets and DNA assemblies.
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent(description))
parser.add_argument('--version', action='version',
version='%(prog)s {}'.format(db.ATRAM_VERSION))
parser.add_argument(
'-T', '--taxa', metavar='TAXA', required=True,
help="""A text file of all of your taxon names.""")
parser.add_argument(
'-r', '--reference-genes', '--refs', metavar='FASTA', required=True,
help="""Reference amino acid sequences in a FASTA file.""")
parser.add_argument(
'-a', '--assemblies-dir', metavar='PATH', required=True,
help="""The path to the target assemblies directory.""")
parser.add_argument(
'-O', '--overlap', type=int, default=10,
help="""Contigs must overlap by this many codons before it is
considered a real overlap.""")
parser.add_argument(
'-t', '--temp-dir', metavar='DIR',
help="""Place temporary files in this directory. All files will be
deleted after aTRAM completes. The directory must exist.""")
parser.add_argument(
'--keep-temp-dir', action='store_true',
help="""This flag will keep the temporary files in the --temp-dir
around for debugging.""")
parser.add_argument(
'-l', '--log-file',
help="""Log file (full path). The default is
"atram_stitcher_<date>.log".""")
parser.add_argument(
'-i', '--iterations', type=int, default=2, metavar='N',
help="""The number of times to run the main stitcher loop. The
minimum is "1" and the default is "2".""")
parser.add_argument(
'-o', '--output-prefix',
help="""This is the prefix of all of the output files. So you can
identify different stitcher output file sets. You may include a
directory as part of the prefix. The stitcher will add suffixes to
differentiate output files.""")
args = parser.parse_args()
util.temp_dir_exists(args.temp_dir)
if not args.output_prefix:
args.output_prefix = join(
'.', 'atram_stitcher_' + date.today().isoformat())
if not args.log_file:
args.log_file = args.output_prefix + '.log'
if args.iterations < 1:
log.fatal('The iterations must be >= 1.')
return args
if __name__ == '__main__':
ARGS = parse_command_line()
Sticher(ARGS).stitch()
| #!/usr/bin/env python3
"""
Start the atram exon stitcher.
This wrapper module parses the input arguments and passes them to the module
that does the actual stitching (core_stitcher.py).
"""
from os.path import join
from datetime import date
import argparse
import textwrap
import lib.db as db
import lib.log as log
import lib.util as util
from lib.core_stitcher import Sticher
def parse_command_line():
"""Process command-line arguments."""
description = """
This program will find and stitch together exons from targeted
assemblies using amino acid targets and DNA assemblies.
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent(description))
parser.add_argument('--version', action='version',
version='%(prog)s {}'.format(db.ATRAM_VERSION))
parser.add_argument(
'-T', '--taxa', metavar='TAXA', required=True,
help="""A text file of all of your taxon names.""")
parser.add_argument(
'-r', '--reference-genes', '--refs', metavar='FASTA', required=True,
help="""Reference amino acid sequences in a FASTA file.""")
parser.add_argument(
'-a', '--assemblies-dir', metavar='PATH', required=True,
help="""The path to the target assemblies directory.""")
parser.add_argument(
'-O', '--overlap', type=int, default=10,
help="""Contigs must overlap by this many codons before it is
considered a real overlap.""")
parser.add_argument(
'-t', '--temp-dir', metavar='DIR',
help="""Place temporary files in this directory. All files will be
deleted after aTRAM completes. The directory must exist.""")
parser.add_argument(
'--keep-temp-dir', action='store_true',
help="""This flag will keep the temporary files in the --temp-dir
around for debugging.""")
parser.add_argument(
'-l', '--log-file',
help="""Log file (full path). The default is
"atram_stitcher_<date>.log".""")
parser.add_argument(
'-i', '--iterations', type=int, default=2, metavar='N',
help="""The number of times to run the main stitcher loop. The
minimum is "1" and the default is "2".""")
parser.add_argument(
'-o', '--output-prefix',
help="""This is the prefix of all of the output files. So you can
identify different stitcher output file sets. You may include a
directory as part of the prefix. The stitcher will add suffixes to
differentiate output files.""")
args = parser.parse_args()
util.temp_dir_exists(args.temp_dir)
if not args.output_prefix:
args.output_prefix = join(
'.', 'atram_stitcher_' + date.today().isoformat())
if not args.log_file:
args.log_file = args.output_prefix + '.log'
if args.iterations < 1:
log.fatal('The iterations must be >= 1.')
return args
if __name__ == '__main__':
ARGS = parse_command_line()
Sticher(ARGS).stitch()
| Python | 0.998561 |
aa681b4a36ce36c53933f3834eec9c721d6029cf | Update docker images utils | polyaxon/docker_images/image_info.py | polyaxon/docker_images/image_info.py | import logging
from typing import Any, Tuple
import conf
from constants.images_tags import LATEST_IMAGE_TAG
_logger = logging.getLogger('polyaxon.dockerizer.images')
def get_experiment_image_info(experiment: 'Experiment') -> Tuple[str, str]:
"""Return the image name and image tag for an experiment"""
project_name = experiment.project.name
repo_name = project_name
image_name = '{}/{}'.format(conf.get('REGISTRY_HOST'), repo_name)
image_tag = experiment.code_reference.commit
return image_name, image_tag
def get_job_image_info(project: 'Project', job: Any) -> Tuple[str, str]:
"""Return the image name and image tag for a job"""
project_name = project.name
repo_name = project_name
image_name = '{}/{}'.format(conf.get('REGISTRY_HOST'), repo_name)
try:
last_commit = project.repo.last_commit
except ValueError:
raise ValueError('Repo was not found for project `{}`.'.format(project))
return image_name, last_commit[0]
def get_notebook_image_info(project: 'Project', job: Any) -> Tuple[str, str]:
"""Return the image name and image tag for a job"""
image_name, _ = get_job_image_info(project, job)
return image_name, LATEST_IMAGE_TAG
def get_project_image_name(project_name: str, project_id: int) -> str:
return '{}/{}_{}'.format(conf.get('REGISTRY_HOST'),
project_name.lower(),
project_id)
def get_project_image_info(project_name: str, project_id: int, image_tag: str) -> Tuple[str, str]:
return get_project_image_name(project_name=project_name, project_id=project_id), image_tag
def get_project_tagged_image(project_name: str, project_id: int, image_tag: str) -> str:
image_name, image_tag = get_project_image_info(project_name=project_name,
project_id=project_id,
image_tag=image_tag)
return '{}:{}'.format(image_name, image_tag)
def get_image_name(build_job: 'BuildJob') -> str:
return get_project_image_name(project_name=build_job.project.name,
project_id=build_job.project.id)
def get_image_info(build_job: 'BuildJob') -> Tuple[str, str]:
return get_project_image_info(project_name=build_job.project.name,
project_id=build_job.project.id,
image_tag=build_job.uuid.hex)
def get_tagged_image(build_job: 'BuildJob') -> str:
return get_project_tagged_image(project_name=build_job.project.name,
project_id=build_job.project.id,
image_tag=build_job.uuid.hex)
| import logging
from typing import Any, Tuple
import conf
from constants.images_tags import LATEST_IMAGE_TAG
_logger = logging.getLogger('polyaxon.dockerizer.images')
def get_experiment_image_info(experiment: 'Experiment') -> Tuple[str, str]:
"""Return the image name and image tag for an experiment"""
project_name = experiment.project.name
repo_name = project_name
image_name = '{}/{}'.format(conf.get('REGISTRY_HOST'), repo_name)
image_tag = experiment.code_reference.commit
return image_name, image_tag
def get_job_image_info(project: 'Project', job: Any)-> Tuple[str, str]:
"""Return the image name and image tag for a job"""
project_name = project.name
repo_name = project_name
image_name = '{}/{}'.format(conf.get('REGISTRY_HOST'), repo_name)
try:
last_commit = project.repo.last_commit
except ValueError:
raise ValueError('Repo was not found for project `{}`.'.format(project))
return image_name, last_commit[0]
def get_notebook_image_info(project: 'Project', job: Any) -> Tuple[str, str]:
"""Return the image name and image tag for a job"""
image_name, _ = get_job_image_info(project, job)
return image_name, LATEST_IMAGE_TAG
def get_image_name(build_job: 'BuildJob') -> str:
return '{}/{}_{}'.format(conf.get('REGISTRY_HOST'),
build_job.project.name.lower(),
build_job.project.id)
def get_image_info(build_job: 'BuildJob') -> Tuple[str, str]:
return get_image_name(build_job=build_job), build_job.uuid.hex
def get_tagged_image(build_job: 'BuildJob') -> str:
image_name, image_tag = get_image_info(build_job)
return '{}:{}'.format(image_name, image_tag)
| Python | 0.000001 |
d69bd1c72c1e01ba392eda54820ca5db4774b744 | Use 'open' with 'with' | polycircles/test/test_earthquakes.py | polycircles/test/test_earthquakes.py | import os, csv
from nose.tools import assert_equal
from polycircles import polycircles
import simplekml
import unittest
class TestLastPointInPolygonEqualsTheFirstOne(unittest.TestCase):
"""
Courtesy Carlos H. Grohmann (https://github.com/CarlosGrohmann) who
reported Issue #1 (https://github.com/adamatan/polycircles/issues/1).
In KML, the first point of the polygon should be equal to the last point
of the polygon in order to properly create a closed polygon, without
a missing vertex.
Therefore, a Polycircle called with number_of_vertices=N
will have N+1 vertices, where vertices[0] == vertices[N].
BTW, This is cool - this project is used to map earthquakes!
"""
def setUp(self):
csvfile = 'polycircles/test/sismos_continente2.csv'
output_dir = 'kmls'
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(csvfile) as f:
datafile = csv.reader(f, delimiter=',')
quakelist = list(datafile)
kml = simplekml.Kml()
alpha = 100
self.polycircles = []
self.number_of_vertices = 36
for quake in quakelist[1:]:
lng = float(quake[0]) # X
lat = float(quake[1]) # Y
yyyy = quake[2] # Ano
magw = quake[25] # mag_03
polycircle = polycircles.Polycircle(
latitude=lat,
longitude=lng,
radius=40000,
number_of_vertices=self.number_of_vertices)
self.polycircles.append(polycircle)
pol = kml.newpolygon(name=yyyy, outerboundaryis=polycircle.to_kml())
if float(magw) < 3.0:
pol.style.polystyle.color = simplekml.Color.changealphaint(alpha, simplekml.Color.lightyellow)
pol.style.linestyle.color = simplekml.Color.lightyellow
elif 3.0 < float(magw) < 3.5:
pol.style.polystyle.color = simplekml.Color.changealphaint(alpha, simplekml.Color.yellow)
pol.style.linestyle.color = simplekml.Color.yellow
elif 3.5 < float(magw) < 4.0:
pol.style.polystyle.color = simplekml.Color.changealphaint(alpha, simplekml.Color.orangered)
pol.style.linestyle.color = simplekml.Color.orangered
else:
pol.style.polystyle.color = simplekml.Color.changealphaint(alpha, simplekml.Color.red)
pol.style.linestyle.color = simplekml.Color.red
kml.save(os.path.join(output_dir, 'sismos.kml'))
def test_number_of_vertices(self):
"""The number of vertices in the Polycircle should equal (number_of_vertices+1).
This test verifies that all the points representations (wkt, kml, lat-lon, lon-lat)
have the same number of points, equal to number_of_vertices+1."""
for polycircle in self.polycircles:
lat_lons = polycircle.to_lat_lon()
lon_lats = polycircle.to_lon_lat()
points = [p for p in polycircle]
wkt = polycircle.to_wkt().split(',')
kml = polycircle.to_kml()
assert_equal(len(lat_lons), self.number_of_vertices + 1)
assert_equal(len(lon_lats), self.number_of_vertices + 1)
assert_equal(len(points), self.number_of_vertices + 1)
assert_equal(len(wkt), self.number_of_vertices + 1)
assert_equal(len(kml), self.number_of_vertices + 1)
| import os, csv
from nose.tools import assert_equal
from polycircles import polycircles
import simplekml
import unittest
class TestLastPointInPolygonEqualsTheFirstOne(unittest.TestCase):
"""
Courtesy Carlos H. Grohmann (https://github.com/CarlosGrohmann) who
reported Issue #1 (https://github.com/adamatan/polycircles/issues/1).
In KML, the first point of the polygon should be equal to the last point
of the polygon in order to properly create a closed polygon, without
a missing vertex.
Therefore, a Polycircle called with number_of_vertices=N
will have N+1 vertices, where vertices[0] == vertices[N].
BTW, This is cool - this project is used to map earthquakes!
"""
def setUp(self):
csvfile = 'polycircles/test/sismos_continente2.csv'
output_dir = 'kmls'
if not os.path.exists(output_dir):
os.makedirs(output_dir)
datafile = csv.reader(open(csvfile, 'rU'), delimiter=',')
quakelist = list(datafile)
kml = simplekml.Kml()
alpha = 100
self.polycircles = []
self.number_of_vertices = 36
for quake in quakelist[1:]:
lng = float(quake[0]) # X
lat = float(quake[1]) # Y
yyyy = quake[2] # Ano
magw = quake[25] # mag_03
polycircle = polycircles.Polycircle(
latitude=lat,
longitude=lng,
radius=40000,
number_of_vertices=self.number_of_vertices)
self.polycircles.append(polycircle)
pol = kml.newpolygon(name=yyyy, outerboundaryis=polycircle.to_kml())
if float(magw) < 3.0:
pol.style.polystyle.color = simplekml.Color.changealphaint(alpha, simplekml.Color.lightyellow)
pol.style.linestyle.color = simplekml.Color.lightyellow
elif 3.0 < float(magw) < 3.5:
pol.style.polystyle.color = simplekml.Color.changealphaint(alpha, simplekml.Color.yellow)
pol.style.linestyle.color = simplekml.Color.yellow
elif 3.5 < float(magw) < 4.0:
pol.style.polystyle.color = simplekml.Color.changealphaint(alpha, simplekml.Color.orangered)
pol.style.linestyle.color = simplekml.Color.orangered
else:
pol.style.polystyle.color = simplekml.Color.changealphaint(alpha, simplekml.Color.red)
pol.style.linestyle.color = simplekml.Color.red
kml.save(os.path.join(output_dir, 'sismos.kml'))
def test_number_of_vertices(self):
"""The number of vertices in the Polycircle should equal (number_of_vertices+1).
This test verifies that all the points representations (wkt, kml, lat-lon, lon-lat)
have the same number of points, equal to number_of_vertices+1."""
for polycircle in self.polycircles:
lat_lons = polycircle.to_lat_lon()
lon_lats = polycircle.to_lon_lat()
points = [p for p in polycircle]
wkt = polycircle.to_wkt().split(',')
kml = polycircle.to_kml()
assert_equal(len(lat_lons), self.number_of_vertices + 1)
assert_equal(len(lon_lats), self.number_of_vertices + 1)
assert_equal(len(points), self.number_of_vertices + 1)
assert_equal(len(wkt), self.number_of_vertices + 1)
assert_equal(len(kml), self.number_of_vertices + 1)
| Python | 0.998616 |
bd4a6e4444b73eacc75657985ffbfd90538a08f0 | fix code style | flexget/ui/__init__.py | flexget/ui/__init__.py | from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import logging
import os
import fnmatch
from flask import send_from_directory, Flask
from flexget.webserver import register_app, register_home
from flask_compress import Compress
log = logging.getLogger('webui')
manager = None
debug = False
app_base = None
ui_base = os.path.dirname(os.path.realpath(__file__))
ui_src = os.path.join(ui_base, 'src')
ui_dist = os.path.join(ui_base, 'app')
bower_components = os.path.join(ui_base, 'bower_components')
webui_app = Flask(__name__)
Compress(webui_app)
webui_app.url_path = '/ui'
@webui_app.route('/<path:path>')
def serve_app(path):
if debug:
if path.startswith('bower_components'):
return send_from_directory(bower_components, path.lstrip('bower_components').lstrip('/'))
if os.path.exists(os.path.join(ui_src, path)):
return send_from_directory(ui_src, path)
return send_from_directory(app_base, path)
@webui_app.route('/')
def root():
if not app_base:
return send_from_directory(ui_base, 'load.failure.html')
return send_from_directory(app_base, 'app.html')
def _find(path, f):
matches = []
for root_dir, dir_names, file_names in os.walk(path):
for filename in fnmatch.filter(file_names, f):
matches.append(os.path.join(root_dir, filename))
return matches
def _strip_trailing_sep(path):
return path.rstrip('\\/')
def register_web_ui(mgr):
global manager, app_base, debug
manager = mgr
if 'debug' in manager.args:
debug = True
if debug:
app_base = os.path.join(ui_base, '.tmp', 'serve')
if not os.path.exists(app_base):
log.warning('Unable to start web ui in debug mode. To enable debug mode please run the debug build, '
'see http://flexget.com/wiki/Web-UI for instructions')
log.warning('Attempting to serve web ui from complied directory')
app_base = None
if not app_base:
app_base = ui_dist
if not os.path.exists(app_base):
log.fatal('Failed to start web ui,'
' this can happen if you are running from GitHub version and forgot to run the web ui build, '
'see http://flexget.com/wiki/Web-UI for instructions')
app_base = None
register_app(webui_app.url_path, webui_app)
register_home('%s/' % webui_app.url_path)
| from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import logging
import os
import fnmatch
from flask import send_from_directory, Flask
from flexget.webserver import register_app, register_home
from flask_compress import Compress
log = logging.getLogger('webui')
manager = None
debug = False
app_base = None
ui_base = os.path.dirname(os.path.realpath(__file__))
ui_src = os.path.join(ui_base, 'src')
ui_dist = os.path.join(ui_base, 'app')
bower_components = os.path.join(ui_base, 'bower_components')
webui_app = Flask(__name__)
Compress(webui_app)
webui_app.url_path = '/ui'
@webui_app.route('/<path:path>')
def serve_app(path):
if debug:
if path.startswith('bower_components'):
return send_from_directory(bower_components, path.lstrip('bower_components').lstrip('/'))
if os.path.exists(os.path.join(ui_src, path)):
return send_from_directory(ui_src, path)
return send_from_directory(app_base, path)
@webui_app.route('/')
def root():
if not app_base:
return send_from_directory(ui_base, 'load.failure.html')
return send_from_directory(app_base, 'app.html')
def _find(path, f):
matches = []
for root, dir_names, file_names in os.walk(path):
for filename in fnmatch.filter(file_names, f):
matches.append(os.path.join(root, filename))
return matches
def _strip_trailing_sep(path):
return path.rstrip('\\/')
def register_web_ui(mgr):
global manager, app_base, debug
manager = mgr
if 'debug' in manager.args:
debug = True
if debug:
app_base = os.path.join(ui_base, '.tmp', 'serve')
if not os.path.exists(app_base):
log.warning('Unable to start web ui in debug mode. To enable debug mode please run the debug build, '
'see http://flexget.com/wiki/Web-UI for instructions')
log.warning('Attempting to serve web ui from complied directory')
app_base = None
if not app_base:
app_base = ui_dist
if not os.path.exists(app_base):
log.fatal('Failed to start web ui,'
' this can happen if you are running from GitHub version and forgot to run the web ui build, '
'see http://flexget.com/wiki/Web-UI for instructions')
app_base = None
register_app(webui_app.url_path, webui_app)
register_home('%s/' % webui_app.url_path)
| Python | 0.000022 |
7307a4b19b09f4408f569c580955f5c7d2af5f73 | Update version number | auth0/__init__.py | auth0/__init__.py | __version__ = '2.0.0b4'
| __version__ = '2.0.0b3'
| Python | 0.000002 |
6a1c3e8c7adecc98af10161d41d95034919eeacd | Allow user specified tsconfig.json | sphinx_js/generators.py | sphinx_js/generators.py | from codecs import getwriter
from errno import ENOENT
import subprocess
import os
from os.path import abspath
from tempfile import TemporaryFile, NamedTemporaryFile
from json import load
from sphinx.errors import SphinxError
from sphinx.util.logging import getLogger
from six import string_types
from .typedoc import parse_typedoc
logger = getLogger(__name__)
class Command(object):
def __init__(self, program):
self.program = program+".cmd" if os.name == 'nt' else program
self.args = []
def add(self, *args):
self.args.extend(args)
def make(self):
command = [self.program]
command.extend(self.args)
logger.info('running: ' + ' '.join(command))
return command
class Generator(object):
def __init__(self, app):
self.app = app
source_paths = [app.config.js_source_path] if isinstance(app.config.js_source_path, string_types) else app.config.js_source_path
# Uses cwd, which Sphinx seems to set to the dir containing conf.py:
self.abs_source_paths = [abspath(path) for path in source_paths]
class JSDocGenerator(Generator):
def run(self):
jsdoc_command = Command('jsdoc')
jsdoc_command.add(*self.abs_source_paths)
jsdoc_command.add('-X')
if self.app.config.jsdoc_config_path:
jsdoc_command.add('-c', self.app.config.jsdoc_config_path)
# Use a temporary file to handle large output volume. JSDoc defaults to
# utf8-encoded output.
with getwriter('utf-8')(TemporaryFile(mode='w+')) as temp:
try:
p = subprocess.Popen(jsdoc_command.make(), stdout=temp)
except OSError as exc:
if exc.errno == ENOENT:
raise SphinxError('%s was not found. Install it using "npm install -g jsdoc".' % jsdoc_command_name)
else:
raise
p.wait()
# Once output is finished, move back to beginning of file and load it:
temp.seek(0)
try:
return load(temp)
except ValueError:
raise SphinxError('jsdoc found no JS files in the directories %s. Make sure js_source_path is set correctly in conf.py. It is also possible (though unlikely) that jsdoc emitted invalid JSON.' % self.abs_source_paths)
class TypedocGenerator(Generator):
def run(self):
with getwriter('utf-8')(NamedTemporaryFile(mode='w+')) as temp:
jsdoc_command = Command('typedoc')
jsdoc_command.add('--json', temp.name)
jsdoc_command.add(*self.abs_source_paths)
if self.app.config.jsdoc_config_path:
jsdoc_command.add('--tsconfig', self.app.config.jsdoc_config_path)
subprocess.call(jsdoc_command.make())
try:
return parse_typedoc(temp)
except ValueError:
raise SphinxError('typedoc found no TS files in the directories %s. Make sure js_source_path is set correctly in conf.py. It is also possible (though unlikely) that typedoc emitted invalid JSON.' % self.abs_source_paths)
def generate_doclets(app):
if app.config.js_language == 'javascript':
return JSDocGenerator(app).run()
elif app.config.js_language == 'typescript':
return TypedocGenerator(app).run()
else:
raise SphinxError('unknown JS language: ' + app.config.js_language)
| from codecs import getwriter
from errno import ENOENT
import subprocess
import os
from os.path import abspath
from tempfile import TemporaryFile, NamedTemporaryFile
from json import load
from sphinx.errors import SphinxError
from sphinx.util.logging import getLogger
from six import string_types
from .typedoc import parse_typedoc
logger = getLogger(__name__)
class Command(object):
def __init__(self, program):
self.program = program+".cmd" if os.name == 'nt' else program
self.args = []
def add(self, *args):
self.args.extend(args)
def make(self):
command = [self.program]
command.extend(self.args)
logger.info('running: ' + ' '.join(command))
return command
class Generator(object):
def __init__(self, app):
self.app = app
source_paths = [app.config.js_source_path] if isinstance(app.config.js_source_path, string_types) else app.config.js_source_path
# Uses cwd, which Sphinx seems to set to the dir containing conf.py:
self.abs_source_paths = [abspath(path) for path in source_paths]
class JSDocGenerator(Generator):
def run(self):
jsdoc_command = Command('jsdoc')
jsdoc_command.add(*self.abs_source_paths)
jsdoc_command.add('-X')
if self.app.config.jsdoc_config_path:
jsdoc_command.add('-c', self.app.config.jsdoc_config_path)
# Use a temporary file to handle large output volume. JSDoc defaults to
# utf8-encoded output.
with getwriter('utf-8')(TemporaryFile(mode='w+')) as temp:
try:
p = subprocess.Popen(jsdoc_command.make(), stdout=temp)
except OSError as exc:
if exc.errno == ENOENT:
raise SphinxError('%s was not found. Install it using "npm install -g jsdoc".' % jsdoc_command_name)
else:
raise
p.wait()
# Once output is finished, move back to beginning of file and load it:
temp.seek(0)
try:
return load(temp)
except ValueError:
raise SphinxError('jsdoc found no JS files in the directories %s. Make sure js_source_path is set correctly in conf.py. It is also possible (though unlikely) that jsdoc emitted invalid JSON.' % self.abs_source_paths)
class TypedocGenerator(Generator):
def run(self):
with getwriter('utf-8')(NamedTemporaryFile(mode='w+')) as temp:
jsdoc_command = Command('typedoc')
jsdoc_command.add('--json', temp.name)
jsdoc_command.add(*self.abs_source_paths)
<<<<<<< eeacb9237af86b8b6e6dfd960f4696ab43e91aec
if self.app.config.jsdoc_config_path:
jsdoc_command.add('--tsconfig', self.app.config.jsdoc_config_path)
=======
>>>>>>> Refactor jsdoc.py
subprocess.call(jsdoc_command.make())
try:
return parse_typedoc(temp)
except ValueError:
raise SphinxError('typedoc found no TS files in the directories %s. Make sure js_source_path is set correctly in conf.py. It is also possible (though unlikely) that typedoc emitted invalid JSON.' % self.abs_source_paths)
def generate_doclets(app):
if app.config.js_language == 'javascript':
return JSDocGenerator(app).run()
elif app.config.js_language == 'typescript':
return TypedocGenerator(app).run()
else:
raise SphinxError('unknown JS language: ' + app.config.js_language)
| Python | 0 |
f1a54346ac0a0241ee5d8011ba443fc7ef5a74f1 | discard happens after interrupt | pyardrone/utils/object_executor.py | pyardrone/utils/object_executor.py | import threading
import queue
import time
class Interrupt:
def __init__(self, obj_exe, wait, discard):
self.obj_exe = obj_exe
self.wait = wait
self.discard = discard
def __enter__(self):
self.obj_exe.pause(wait=self.wait)
def __exit__(self, exc_type, exc_value, exc_tb):
if exc_type is None:
if self.discard:
q = self.obj_exe._queue
with self.obj_exe._queue_lock:
with q.mutex:
q.queue.clear()
q.all_tasks_done.notify_all()
q.unfinished_tasks = 0
self.obj_exe.resume()
class ObjectExecutor:
def __init__(self, target, interval, default):
self._target = target
self.default = default
self.interval = interval
self._queue = queue.Queue()
self._queue_lock = threading.Lock()
self._thread = threading.Thread(target=self._job)
self._stop_event = threading.Event()
self._working_event = threading.Event()
def start(self):
self._stop_event.clear()
self._working_event.set()
self._thread.start()
def stop(self, wait=False):
if wait:
self.join()
self._stop_event.set()
def pause(self, wait=False):
if wait:
self.join()
self._working_event.clear()
def resume(self):
self._working_event.set()
def interrupt(self, *, wait=False, discard=True):
return Interrupt(self, wait=wait, discard=discard)
def join(self):
self._queue.join()
def put(self, obj, with_event=True):
if with_event:
event = threading.Event()
else:
event = None
self._queue.put((obj, event))
def _process_object(self):
with self._queue_lock:
try:
obj, event = self._queue.get_nowait()
call_task_done = True
except queue.Empty:
obj, event = self.default, None
call_task_done = False
self._target(obj)
if event is not None:
event.set()
if call_task_done:
self._queue.task_done()
def _job(self):
while not self._stop_event.is_set():
self._working_event.wait()
self._process_object()
time.sleep(self.interval)
| import threading
import queue
import time
class Interrupt:
def __init__(self, obj_exe, wait, discard):
self.obj_exe = obj_exe
self.wait = wait
self.discard = discard
def __enter__(self):
self.obj_exe.pause(wait=self.wait)
if self.discard:
q = self.obj_exe._queue
with self.obj_exe._queue_lock:
with q.mutex:
q.queue.clear()
q.all_tasks_done.notify_all()
q.unfinished_tasks = 0
def __exit__(self, exc_type, exc_value, exc_tb):
if exc_type is None:
self.obj_exe.resume()
class ObjectExecutor:
def __init__(self, target, interval, default):
self._target = target
self.default = default
self.interval = interval
self._queue = queue.Queue()
self._queue_lock = threading.Lock()
self._thread = threading.Thread(target=self._job)
self._stop_event = threading.Event()
self._working_event = threading.Event()
def start(self):
self._stop_event.clear()
self._working_event.set()
self._thread.start()
def stop(self, wait=False):
if wait:
self.join()
self._stop_event.set()
def pause(self, wait=False):
if wait:
self.join()
self._working_event.clear()
def resume(self):
self._working_event.set()
def interrupt(self, *, wait=False, discard=True):
return Interrupt(self, wait=wait, discard=discard)
def join(self):
self._queue.join()
def put(self, obj, with_event=True):
if with_event:
event = threading.Event()
else:
event = None
self._queue.put((obj, event))
def _process_object(self):
with self._queue_lock:
try:
obj, event = self._queue.get_nowait()
call_task_done = True
except queue.Empty:
obj, event = self.default, None
call_task_done = False
self._target(obj)
if event is not None:
event.set()
if call_task_done:
self._queue.task_done()
def _job(self):
while not self._stop_event.is_set():
self._working_event.wait()
self._process_object()
time.sleep(self.interval)
| Python | 0.000112 |
443d56fdd2e588c11c2a1e3a685912b712e37d44 | Make sure all fields are grabbed. | split/casanfar_split.py | split/casanfar_split.py | import os
import numpy as np
import sys
SDM_name = str(sys.argv[4])
print "Inputted MS: "+SDM_name
# SDM_name = '14B-088.sb30023144.eb30070731.57002.919034293984'
# Set up some useful variables (these will be altered later on)
msfile = SDM_name + '.ms'
hisplitms = SDM_name + '.hi.ms'
splitms = SDM_name + '.hi.src.split.ms'
pathname = os.environ.get('CASAPATH').split()[0]
pipepath = '/home/ekoch/pipe_scripts/'
source = 'M33*'
# VOS stuff
vos_dir = '../vos/'
vos_proc = './'
# %&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%%&%&%&%&%&%&%%&%
# Find the 21cm spw and check if the obs
# is single pointing or mosaic
# %&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%%&%&%&%&%&%&%%&%
print "Find HI spw..."
# But first find the spw corresponding to it
tb.open(vos_dir+msfile+'/SPECTRAL_WINDOW')
freqs = tb.getcol('REF_FREQUENCY')
nchans = tb.getcol('NUM_CHAN')
tb.close()
spws = range(0, len(freqs))
# Select the 21cm
sel = np.where((freqs > 1.40*10**9) & (freqs < 1.43*10**9))
hispw = str(spws[sel[0][0]])
freq = freqs[sel[0][0]]
nchan = nchans[sel[0][0]]
print "Selected spw "+str(hispw)
print "with frequency "+str(freq)
print "and "+str(nchan)+" channels"
print "Starting split the HI line"
# Mosaic or single pointing?
tb.open(vos_dir+msfile+'/FIELD')
names = tb.getcol('NAME')
tb.close()
moscount = 0
for name in names:
chsrc = name.find(source)
if chsrc != -1:
moscount = moscount+1
if moscount > 1:
imagermode = "mosaic"
else:
imagermode = "csclean"
# %&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%
# Split the corrected source data from the rest
# %&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%
print "Starting source split..."
#os.system('md5sum $(find '+vos_dir+hisplitms+') > '+vos_proc+hisplitms+'.md5')
# os.system('rm -rf '+vos_proc+splitms)
default('split')
vis = vos_dir+msfile
outputvis = vos_proc+hisplitms
field = source
spw = hispw
datacolumn = 'corrected'
keepflags = False
print vis
print outputvis
print field
print spw
split()
print "Created splitted-source .ms "+hisplitms
| import os
import numpy as np
import sys
SDM_name = str(sys.argv[4])
print "Inputted MS: "+SDM_name
# SDM_name = '14B-088.sb30023144.eb30070731.57002.919034293984'
# Set up some useful variables (these will be altered later on)
msfile = SDM_name + '.ms'
hisplitms = SDM_name + '.hi.ms'
splitms = SDM_name + '.hi.src.split.ms'
pathname = os.environ.get('CASAPATH').split()[0]
pipepath = '/home/ekoch/pipe_scripts/'
source = 'M33'
# VOS stuff
vos_dir = '../vos/'
vos_proc = './'
# %&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%%&%&%&%&%&%&%%&%
# Find the 21cm spw and check if the obs
# is single pointing or mosaic
# %&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%%&%&%&%&%&%&%%&%
print "Find HI spw..."
# But first find the spw corresponding to it
tb.open(vos_dir+msfile+'/SPECTRAL_WINDOW')
freqs = tb.getcol('REF_FREQUENCY')
nchans = tb.getcol('NUM_CHAN')
tb.close()
spws = range(0, len(freqs))
# Select the 21cm
sel = np.where((freqs > 1.40*10**9) & (freqs < 1.43*10**9))
hispw = str(spws[sel[0][0]])
freq = freqs[sel[0][0]]
nchan = nchans[sel[0][0]]
print "Selected spw "+str(hispw)
print "with frequency "+str(freq)
print "and "+str(nchan)+" channels"
print "Starting split the HI line"
# Mosaic or single pointing?
tb.open(vos_dir+msfile+'/FIELD')
names = tb.getcol('NAME')
tb.close()
moscount = 0
for name in names:
chsrc = name.find(source)
if chsrc != -1:
moscount = moscount+1
if moscount > 1:
imagermode = "mosaic"
else:
imagermode = "csclean"
# %&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%
# Split the corrected source data from the rest
# %&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%
print "Starting source split..."
#os.system('md5sum $(find '+vos_dir+hisplitms+') > '+vos_proc+hisplitms+'.md5')
# os.system('rm -rf '+vos_proc+splitms)
default('split')
vis = vos_dir+msfile
outputvis = vos_proc+hisplitms
field = source
spw = hispw
datacolumn = 'corrected'
keepflags = False
print vis
print outputvis
print field
print spw
split()
print "Created splitted-source .ms "+hisplitms
| Python | 0 |
eeee8fb498eb3a52baff7b9b2684c8a713e20216 | remove non-essential calls from inner-loop methods | pydoop/mapreduce/binary_streams.py | pydoop/mapreduce/binary_streams.py | # BEGIN_COPYRIGHT
#
# Copyright 2009-2017 CRS4.
#
# 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.
#
# END_COPYRIGHT
from .streams import (
StreamWriter, StreamReader, DownStreamAdapter, UpStreamAdapter,
)
from pydoop.utils.serialize import CommandReader, CommandWriter, RULES
from pydoop.utils.py3compat import unicode
import logging
logging.basicConfig()
LOGGER = logging.getLogger('binary_streams')
LOGGER.setLevel(logging.CRITICAL)
class BinaryWriter(StreamWriter):
def __init__(self, stream):
super(BinaryWriter, self).__init__(CommandWriter(stream))
self.logger = LOGGER.getChild('BinaryWriter')
self.logger.debug('initialize on stream: %s', stream)
# we need to be sure that stream will not be gc
self.original_stream = stream
def send(self, cmd, *args):
typecodes = RULES[cmd] if cmd != self.SET_JOB_CONF else 's' * len(args)
args = self.__to_bytes(args, typecodes)
if cmd == self.SET_JOB_CONF:
args = (args,)
self.stream.write((cmd, args))
def __to_bytes(self, args, typecodes):
out_args = []
for a, t in zip(args, typecodes):
if t == "s" and not isinstance(a, (bytes, bytearray)):
if not isinstance(a, unicode):
a = unicode(a)
a = a.encode('utf-8')
out_args.append(a)
return tuple(out_args)
class BinaryReader(StreamReader):
def __init__(self, stream):
super(BinaryReader, self).__init__(CommandReader(stream))
self.logger = LOGGER.getChild('BinaryReader')
self.logger.debug('initialize on stream: %s', stream)
# we need to be sure that stream will not be gc
self.original_stream = stream
def __iter__(self):
self.logger.debug('requested iterator: %s', self)
return self.stream.__iter__()
def next(self):
return next(self.stream)
def __next__(self):
return self.next()
class BinaryDownStreamAdapter(BinaryReader, DownStreamAdapter):
def __init__(self, stream):
super(BinaryDownStreamAdapter, self).__init__(stream)
self.logger = LOGGER.getChild('BinaryDownStreamAdapter')
self.logger.debug('initialize on stream: %s', stream)
class BinaryUpStreamAdapter(BinaryWriter, UpStreamAdapter):
def __init__(self, stream):
super(BinaryUpStreamAdapter, self).__init__(stream)
self.logger = LOGGER.getChild('BinaryUpStreamAdapter')
self.logger.debug('initialize on stream: %s', stream)
class BinaryUpStreamDecoder(BinaryDownStreamAdapter):
def __init__(self, stream):
super(BinaryUpStreamDecoder, self).__init__(stream)
self.logger = LOGGER.getChild('BinaryUpStreamDecoder')
| # BEGIN_COPYRIGHT
#
# Copyright 2009-2017 CRS4.
#
# 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.
#
# END_COPYRIGHT
from .streams import (
StreamWriter, StreamReader, DownStreamAdapter, UpStreamAdapter,
)
from pydoop.utils.serialize import CommandReader, CommandWriter, RULES
from pydoop.utils.py3compat import unicode
import logging
logging.basicConfig()
LOGGER = logging.getLogger('binary_streams')
LOGGER.setLevel(logging.CRITICAL)
class BinaryWriter(StreamWriter):
def __init__(self, stream):
super(BinaryWriter, self).__init__(CommandWriter(stream))
self.logger = LOGGER.getChild('BinaryWriter')
self.logger.debug('initialize on stream: %s', stream)
# we need to be sure that stream will not be gc
self.original_stream = stream
def send(self, cmd, *args):
self.logger.debug('request to write %r, %r', cmd, args)
typecodes = RULES[cmd] if cmd != self.SET_JOB_CONF else 's' * len(args)
args = self.__to_bytes(args, typecodes)
if cmd == self.SET_JOB_CONF:
args = (args,)
self.logger.debug('writing (%r, %r)', cmd, args)
self.stream.write((cmd, args))
def __to_bytes(self, args, typecodes):
assert len(args) == len(typecodes)
out_args = []
for a, t in zip(args, typecodes):
if t == "s" and not isinstance(a, (bytes, bytearray)):
if not isinstance(a, unicode):
a = unicode(a)
a = a.encode('utf-8')
out_args.append(a)
return tuple(out_args)
class BinaryReader(StreamReader):
def __init__(self, stream):
super(BinaryReader, self).__init__(CommandReader(stream))
self.logger = LOGGER.getChild('BinaryReader')
self.logger.debug('initialize on stream: %s', stream)
# we need to be sure that stream will not be gc
self.original_stream = stream
def __iter__(self):
self.logger.debug('requested iterator: %s', self)
return self.stream.__iter__()
def next(self):
return next(self.stream)
def __next__(self):
return self.next()
class BinaryDownStreamAdapter(BinaryReader, DownStreamAdapter):
def __init__(self, stream):
super(BinaryDownStreamAdapter, self).__init__(stream)
self.logger = LOGGER.getChild('BinaryDownStreamAdapter')
self.logger.debug('initialize on stream: %s', stream)
class BinaryUpStreamAdapter(BinaryWriter, UpStreamAdapter):
def __init__(self, stream):
super(BinaryUpStreamAdapter, self).__init__(stream)
self.logger = LOGGER.getChild('BinaryUpStreamAdapter')
self.logger.debug('initialize on stream: %s', stream)
class BinaryUpStreamDecoder(BinaryDownStreamAdapter):
def __init__(self, stream):
super(BinaryUpStreamDecoder, self).__init__(stream)
self.logger = LOGGER.getChild('BinaryUpStreamDecoder')
| Python | 0.000009 |
ed320c5fac9bdd53b568946847981d38b0e0037b | Handle requests exceptions in actual healthcheck | src/django_healthchecks/checker.py | src/django_healthchecks/checker.py | import base64
import functools
import inspect
from importlib import import_module
import requests
from django.conf import settings
from django.utils.encoding import force_text
try:
from django.utils.module_loading import import_string
except ImportError:
def import_string(value):
module_name, func_name = value.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, func_name)
class PermissionDenied(Exception):
pass
def create_report(request=None):
"""Run all checks and return a tuple containing results and boolean to
indicate to indicate if all things are healthy.
"""
report = {}
has_error = False
for service, check_func in _get_check_functions(request=request):
report[service] = check_func() or False
if not report[service]:
has_error = True
return report, not has_error
def create_service_result(service, request=None):
functions = list(_get_check_functions(name=service, request=request))
if not functions:
return
check_func = functions[0][1]
result = check_func() or False
return result
def _get_check_functions(name=None, request=None):
checks = _get_registered_health_checks()
if not checks or (name and name not in checks):
raise StopIteration()
checks = _filter_checks_on_permission(request, checks)
if not checks or (name and name not in checks):
raise PermissionDenied()
for service, func_string in checks.items():
if name and name != service:
continue
if func_string.startswith(('https://', 'http://')):
check_func = _http_healthcheck_func(func_string)
elif callable(func_string):
check_func = func_string
else:
check_func = import_string(func_string)
spec = inspect.getargspec(check_func)
if spec.args == ['request']:
check_func = functools.partial(check_func, request)
yield service, check_func
def _get_registered_health_checks():
return getattr(settings, 'HEALTH_CHECKS', {})
def _http_healthcheck_func(url):
def handle_remote_request():
try:
response = requests.get(url, timeout=_get_http_healthcheck_timeout())
except requests.exceptions.RequestException:
return False
if response.ok:
return response.json()
return False
return handle_remote_request
def _get_http_healthcheck_timeout():
return getattr(settings, 'HEALTH_CHECKS_HTTP_TIMEOUT', 0.5)
def _filter_checks_on_permission(request, checks):
permissions = getattr(settings, 'HEALTH_CHECKS_BASIC_AUTH', {})
if not permissions:
return checks
allowed = {}
for name in checks.keys():
required_credentials = permissions.get(name, permissions.get('*'))
if required_credentials:
credentials = _get_basic_auth(request)
if not credentials or credentials not in required_credentials:
continue
allowed[name] = checks[name]
return allowed
def _get_basic_auth(request):
auth = request.META.get('HTTP_AUTHORIZATION')
if not auth:
return
auth = auth.split()
if len(auth) == 2 and force_text(auth[0]).lower() == u'basic':
credentials = base64.b64decode(auth[1]).decode('latin-1')
return tuple(credentials.split(':'))
| import base64
import functools
import inspect
from importlib import import_module
from django.conf import settings
from django.utils.encoding import force_text
import requests
try:
from django.utils.module_loading import import_string
except ImportError:
def import_string(value):
module_name, func_name = value.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, func_name)
class PermissionDenied(Exception):
pass
def create_report(request=None):
"""Run all checks and return a tuple containing results and boolean to
indicate to indicate if all things are healthy.
"""
report = {}
has_error = False
for service, check_func in _get_check_functions(request=request):
try:
report[service] = check_func()
except:
report[service] = False
if not report[service]:
has_error = True
return report, not has_error
def create_service_result(service, request=None):
functions = list(_get_check_functions(name=service, request=request))
if not functions:
return
check_func = functions[0][1]
try:
result = check_func()
except:
result = False
return result
def _get_check_functions(name=None, request=None):
checks = _get_registered_health_checks()
if not checks or (name and name not in checks):
raise StopIteration()
checks = _filter_checks_on_permission(request, checks)
if not checks or (name and name not in checks):
raise PermissionDenied()
for service, func_string in checks.items():
if name and name != service:
continue
if func_string.startswith(('https://', 'http://')):
check_func = _http_healthcheck_func(func_string)
elif callable(func_string):
check_func = func_string
else:
check_func = import_string(func_string)
spec = inspect.getargspec(check_func)
if spec.args == ['request']:
check_func = functools.partial(check_func, request)
yield service, check_func
def _get_registered_health_checks():
return getattr(settings, 'HEALTH_CHECKS', {})
def _http_healthcheck_func(url):
return lambda: requests.get(url,
timeout=_get_http_healthcheck_timeout()).json()
def _get_http_healthcheck_timeout():
return getattr(settings, 'HEALTH_CHECKS_HTTP_TIMEOUT', 0.5)
def _filter_checks_on_permission(request, checks):
permissions = getattr(settings, 'HEALTH_CHECKS_BASIC_AUTH', {})
if not permissions:
return checks
allowed = {}
for name in checks.keys():
required_credentials = permissions.get(name, permissions.get('*'))
if required_credentials:
credentials = _get_basic_auth(request)
if not credentials or credentials not in required_credentials:
continue
allowed[name] = checks[name]
return allowed
def _get_basic_auth(request):
auth = request.META.get('HTTP_AUTHORIZATION')
if not auth:
return
auth = auth.split()
if len(auth) == 2 and force_text(auth[0]).lower() == u'basic':
credentials = base64.b64decode(auth[1]).decode('latin-1')
return tuple(credentials.split(':'))
| Python | 0 |
4e0d90fc157760606ae8503762f10bdef30bff8c | Remove trailing slashes | bluebottle/impact/urls/api.py | bluebottle/impact/urls/api.py | from django.conf.urls import url
from bluebottle.impact.views import (
ImpactTypeList,
ImpactGoalList,
ImpactGoalDetail
)
urlpatterns = [
url(r'^types$', ImpactTypeList.as_view(), name='impact-type-list'),
url(r'^goals$', ImpactGoalList.as_view(), name='impact-goal-list'),
url(
r'^goals/(?P<pk>\d+)$',
ImpactGoalDetail.as_view(),
name='impact-goal-details'
)
]
| from django.conf.urls import url
from bluebottle.impact.views import (
ImpactTypeList,
ImpactGoalList,
ImpactGoalDetail
)
urlpatterns = [
url(r'^types/$', ImpactTypeList.as_view(), name='impact-type-list'),
url(r'^goals/$', ImpactGoalList.as_view(), name='impact-goal-list'),
url(
r'^goals/(?P<pk>\d+)/$',
ImpactGoalDetail.as_view(),
name='impact-goal-details'
)
]
| Python | 0.000346 |
0dd21b0f13aa7bf4cc3061dca216c65cf73975e5 | Make registration reports filterable and harmonize URL | kcdc3/apps/classes/urls.py | kcdc3/apps/classes/urls.py | from django.conf.urls import patterns, include, url
from models import Event, Registration
from views import EventListView, EventDetailView, ResponseTemplateView, EventArchiveView, SessionView, RegistrationListView, TeacherAdminListView, FilteredTeacherAdminListView
urlpatterns = patterns('kcdc3.apps.classes.views',
url(r'^$', EventListView.as_view()),
url(r'^staff/teachers/$', TeacherAdminListView.as_view()),
url(r'^staff/teachers/session/(?P<slug>[A-Za-z0-9_-]+)/$', FilteredTeacherAdminListView.as_view()),
url(r'^staff/registrations/session/(?P<slug>[A-Za-z0-9_-]+)/$', RegistrationListView.as_view()),
url(r'^(?P<slug>[0-9_-]+)/$', EventArchiveView.as_view()),
url(r'^(?P<slug>[0-9_-]+)/background/$', SessionView.as_view()),
url(r'^response/(?P<slug>[A-Za-z0-9_-]+)$', ResponseTemplateView.as_view()),
url(r'^(?P<slug>[A-Za-z0-9_-]+)/$', EventDetailView.as_view(model=Event,)),
url(r'^(?P<slug>[A-Za-z0-9_-]+)/register$', 'register'),
url(r'^(?P<slug>[A-Za-z0-9_-]+)/cancel$', 'cancel'),
url(r'^(?P<slug>[A-Za-z0-9_-]+)/facilitator$', 'facilitator'),
)
| from django.conf.urls import patterns, include, url
from models import Event, Registration
from views import EventListView, EventDetailView, ResponseTemplateView, EventArchiveView, SessionView, RegistrationListView, TeacherAdminListView, FilteredTeacherAdminListView
urlpatterns = patterns('kcdc3.apps.classes.views',
url(r'^$', EventListView.as_view()),
url(r'^staff/teachers/$', TeacherAdminListView.as_view()),
url(r'^staff/teachers/session/(?P<slug>[A-Za-z0-9_-]+)$', FilteredTeacherAdminListView.as_view()),
url(r'^dashboard/registrations/(?P<slug>[A-Za-z0-9_-]+)$', RegistrationListView.as_view()),
url(r'^(?P<slug>[0-9_-]+)/$', EventArchiveView.as_view()),
url(r'^(?P<slug>[0-9_-]+)/background/$', SessionView.as_view()),
url(r'^response/(?P<slug>[A-Za-z0-9_-]+)$', ResponseTemplateView.as_view()),
url(r'^(?P<slug>[A-Za-z0-9_-]+)/$', EventDetailView.as_view(model=Event,)),
url(r'^(?P<slug>[A-Za-z0-9_-]+)/register$', 'register'),
url(r'^(?P<slug>[A-Za-z0-9_-]+)/cancel$', 'cancel'),
url(r'^(?P<slug>[A-Za-z0-9_-]+)/facilitator$', 'facilitator'),
)
| Python | 0 |
80afbf3b5be1716553b93ee6ba57404d40e43a94 | Remove multiple workers | gunicorn_conf.py | gunicorn_conf.py | accesslog = '-'
access_log_format = '%({Host}i)s %(h)s %(l)s "%({X-Remote-User-Id}o)s: %({X-Remote-User-Name}o)s" %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s'
| accesslog = '-'
access_log_format = '%({Host}i)s %(h)s %(l)s "%({X-Remote-User-Id}o)s: %({X-Remote-User-Name}o)s" %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s'
workers = 3
| Python | 0.003335 |
67346a13eb40d605da498b0bdba25ca661f08dd1 | Remove unused imports | geotrek/feedback/templatetags/feedback_tags.py | geotrek/feedback/templatetags/feedback_tags.py | import json
from geotrek.feedback.models import PredefinedEmail, ReportStatus
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def suricate_management_enabled():
return settings.SURICATE_MANAGEMENT_ENABLED
@register.simple_tag
def suricate_workflow_enabled():
return settings.SURICATE_WORKFLOW_ENABLED
@register.simple_tag
def enable_report_colors_per_status():
return settings.ENABLE_REPORT_COLORS_PER_STATUS
@register.simple_tag
def status_ids_and_colors():
status_ids_and_colors = {
status.pk: {
"id": str(status.identifier),
"color": str(status.color)
}
for status in ReportStatus.objects.all()
}
return json.dumps(status_ids_and_colors)
@register.simple_tag
def predefined_emails():
predefined_emails = {
email.pk: {
"label": str(email.label),
"text": str(email.text)
}
for email in PredefinedEmail.objects.all()
}
return json.dumps(predefined_emails)
@register.simple_tag
def resolved_intervention_info(report):
if report:
username = "'?'"
intervention = report.report_interventions().first()
authors = intervention.authors
if authors:
user = authors.last() # oldest author is the one that created the intervention
if user.profile and user.profile.extended_username:
username = user.profile.extended_username
else:
username = user.username
resolved_intervention_info = {
"date": report.interventions.first().date.strftime("%d/%m/%Y") if report.interventions else None,
"username": username
}
return json.dumps(resolved_intervention_info)
return json.dumps({})
| import json
from geotrek.feedback.models import PredefinedEmail, ReportStatus
from mapentity.models import LogEntry
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def suricate_management_enabled():
return settings.SURICATE_MANAGEMENT_ENABLED
@register.simple_tag
def suricate_workflow_enabled():
return settings.SURICATE_WORKFLOW_ENABLED
@register.simple_tag
def enable_report_colors_per_status():
return settings.ENABLE_REPORT_COLORS_PER_STATUS
@register.simple_tag
def status_ids_and_colors():
status_ids_and_colors = {
status.pk: {
"id": str(status.identifier),
"color": str(status.color)
}
for status in ReportStatus.objects.all()
}
return json.dumps(status_ids_and_colors)
@register.simple_tag
def predefined_emails():
predefined_emails = {
email.pk: {
"label": str(email.label),
"text": str(email.text)
}
for email in PredefinedEmail.objects.all()
}
return json.dumps(predefined_emails)
@register.simple_tag
def resolved_intervention_info(report):
if report:
username = "'?'"
intervention = report.report_interventions().first()
authors = intervention.authors
if authors:
user = authors.last() # oldest author is the one that created the intervention
if user.profile and user.profile.extended_username:
username = user.profile.extended_username
else:
username = user.username
resolved_intervention_info = {
"date": report.interventions.first().date.strftime("%d/%m/%Y") if report.interventions else None,
"username": username
}
return json.dumps(resolved_intervention_info)
return json.dumps({})
| Python | 0.000001 |
f4b7426103d2b484501a3bfdff3ebe976216b882 | Make a nice description of the module. (../port-add-product_multi_company_7.0-bis-jge/ rev 213.5.7) | product_price_history/__openerp__.py | product_price_history/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright 2013 Camptocamp SA
# Author: Joel Grand-Guillaume
#
# 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/>
#
##############################################################################
{
"name" : "Product Price History",
"version" : "1.2",
"author" : "Camptocamp",
"category" : "Generic Modules/Inventory Control",
"depends" : [ "product","purchase"],
"description": """
Product Price History
=====================
This module allow you to :
* Record various prices of a same product for different companies. This way, every company can have his own cost (average or standard) and sale price.
* Historize the prices in a way that you'll then be able to retrieve the cost (or sale) price at a given date.
Note that to benefit those values in stock report (or any other view that is based on SQL),
you'll have to adapt it to include this new historized table. Especially true for stock
valuation.
This module also contain demo data and various tests to ensure it work well. It show
how to configure OpenERP properly when you have various company, each of them having
their product setup in average price and using different currency. The goal is to share
the products between all company, keeping the right price for each of them.
Technically, this module updates the definition of field standard_price, list_price
of the product and will make them stored in an external table. We override the read,
write and create methods to achieve that and don't used ir.property for performance
and historization purpose.
You may want to also use the module analytic_multicurrency from bzr branch lp:account-analytic
in order to have a proper computation in analytic line as well (standard_price will be converted
in company currency with this module when computing cost of analytic line).
""",
'demo': [
'demo/product_price_history_purchase_demo.yml',
],
'data': [
'product_price_history_view.xml',
'wizard/historic_prices_view.xml',
'security/ir.model.access.csv',
'security/product_price_history_security.xml',
],
'test': [
'test/price_controlling_multicompany.yml',
'test/avg_price_computation_mutlicompanies_multicurrencies.yml',
'test/price_historization.yml',
],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright 2013 Camptocamp SA
# Author: Joel Grand-Guillaume
#
# 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/>
#
##############################################################################
{
"name" : "Product Price History",
"version" : "1.2",
"author" : "Camptocamp",
"category" : "Generic Modules/Inventory Control",
"depends" : [ "product","purchase"],
"description": """
Product Price History
This module allow you to :
* record various prices of a same product for different companies. This way, every company
can have his own cost (average or standard) and sale price.
* historize the prices in a way that you'll then be able to retrieve the cost (or sale) price
at a given date.
Note that to benefit those values in stock report (or any other view that is based on SQL),
you'll have to adapt it to include this new historized table. Especially true for stock
valuation.
This module also contain demo data and various tests to ensure it work well. It show
how to configure OpenERP properly when you have various company, each of them having
their product setup in average price and using different currency. The goal is to share
the products between all company, keeping the right price for each of them.
Technically, this module updates the definition of field standard_price, list_price
of the product and will make them stored in an external table. We override the read,
write and create methods to achieve that and don't used ir.property for performance
and historization purpose.
You may want to also use the module analytic_multicurrency from bzr branch lp:account-analytic
in order to have a proper computation in analytic line as well (standard_price will be converted
in company currency with this module when computing cost of analytic line).
""",
'demo': [
'demo/product_price_history_purchase_demo.yml',
],
'data': [
'product_price_history_view.xml',
'wizard/historic_prices_view.xml',
'security/ir.model.access.csv',
'security/product_price_history_security.xml',
],
'test': [
'test/price_controlling_multicompany.yml',
'test/avg_price_computation_mutlicompanies_multicurrencies.yml',
'test/price_historization.yml',
],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| Python | 0.000001 |
eb712d30a6231b416e33d02a125daddf5322d51e | Add API docs for the Exscript.util.syslog module. | src/Exscript/util/syslog.py | src/Exscript/util/syslog.py | # Copyright (C) 2007-2010 Samuel Abels.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, as
# published by the Free Software Foundation.
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
Send messages to a syslog server.
"""
import imp
import socket
# This way of loading a module prevents Python from looking in the
# current directory. (We need to avoid it due to the syslog module
# name collision.)
syslog = imp.load_module('syslog', *imp.find_module('syslog'))
def netlog(message,
source = None,
host = 'localhost',
port = 514,
priority = syslog.LOG_DEBUG,
facility = syslog.LOG_USER):
"""
Python's built in syslog module does not support networking, so
this is the alternative.
The source argument specifies the message source that is
documented on the receiving server. It defaults to "scriptname[pid]",
where "scriptname" is sys.argv[0], and pid is the current process id.
The priority and facility arguments are equivalent to those of
Python's built in syslog module.
@type source: str
@param source: The source address.
@type host: str
@param host: The IP address or hostname of the receiving server.
@type port: str
@param port: The TCP port number of the receiving server.
@type priority: int
@param priority: The message priority.
@type facility: int
@param facility: The message facility.
"""
if not source:
source = '%s[%s]' + (sys.argv[0], os.getpid())
data = '<%d>%s: %s' % (priority + facility, source, message)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(data, (host, port))
sock.close()
| import imp, socket
# This way of loading a module prevents Python from looking in the
# current directory. (We need to avoid it due to the syslog module
# name collision.)
syslog = imp.load_module('syslog', *imp.find_module('syslog'))
def netlog(message,
source = None,
host = 'localhost',
port = 514,
priority = syslog.LOG_DEBUG,
facility = syslog.LOG_USER):
"""
Python's built in syslog module does not support networking, so
this is the alternative.
The source argument specifies the message source that is
documented on the receiving server. It defaults to "scriptname[pid]",
where "scriptname" is sys.argv[0], and pid is the current process id.
The priority and facility arguments are equivalent to those of
Python's built in syslog module.
@type source: str
@param source: The source address.
@type host: str
@param host: The IP address or hostname of the receiving server.
@type port: str
@param port: The TCP port number of the receiving server.
@type priority: int
@param priority: The message priority.
@type facility: int
@param facility: The message facility.
"""
if not source:
source = '%s[%s]' + (sys.argv[0], os.getpid())
data = '<%d>%s: %s' % (priority + facility, source, message)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(data, (host, port))
sock.close()
| Python | 0 |
e05243983cb9167303a19e85a3c88f74da8e2612 | Convert ipLocation function name to all lowercase | bot/slack/commands/ip_info.py | bot/slack/commands/ip_info.py | import netaddr
import os
from mozdef_util.geo_ip import GeoIP
def is_ip(ip):
try:
netaddr.IPNetwork(ip)
return True
except Exception:
return False
def ip_location(ip):
location = ""
try:
geoip_data_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../../data/GeoLite2-City.mmdb")
geoip = GeoIP(geoip_data_dir)
geoDict = geoip.lookup_ip(ip)
if geoDict is not None:
if 'error' in geoDict:
return geoDict['error']
location = geoDict['country_name']
if geoDict['country_code'] in ('US'):
if geoDict['metro_code']:
location = location + '/{0}'.format(geoDict['metro_code'])
except Exception:
location = ""
return location
class command():
def __init__(self):
self.command_name = '!ipinfo'
self.help_text = 'Perform a geoip lookup on an ip address'
def handle_command(self, parameters):
response = ""
for ip_token in parameters:
if is_ip(ip_token):
ip = netaddr.IPNetwork(ip_token)[0]
if (not ip.is_loopback() and not ip.is_private() and not ip.is_reserved()):
response += "{0} location: {1}\n".format(ip_token, ip_location(ip_token))
else:
response += "{0}: hrm...loopback? private ip?\n".format(ip_token)
else:
response = "{0} is not an IP address".format(ip_token)
return response
| import netaddr
import os
from mozdef_util.geo_ip import GeoIP
def is_ip(ip):
try:
netaddr.IPNetwork(ip)
return True
except Exception:
return False
def ipLocation(ip):
location = ""
try:
geoip_data_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../../data/GeoLite2-City.mmdb")
geoip = GeoIP(geoip_data_dir)
geoDict = geoip.lookup_ip(ip)
if geoDict is not None:
if 'error' in geoDict:
return geoDict['error']
location = geoDict['country_name']
if geoDict['country_code'] in ('US'):
if geoDict['metro_code']:
location = location + '/{0}'.format(geoDict['metro_code'])
except Exception:
location = ""
return location
class command():
def __init__(self):
self.command_name = '!ipinfo'
self.help_text = 'Perform a geoip lookup on an ip address'
def handle_command(self, parameters):
response = ""
for ip_token in parameters:
if is_ip(ip_token):
ip = netaddr.IPNetwork(ip_token)[0]
if (not ip.is_loopback() and not ip.is_private() and not ip.is_reserved()):
response += "{0} location: {1}\n".format(ip_token, ipLocation(ip_token))
else:
response += "{0}: hrm...loopback? private ip?\n".format(ip_token)
else:
response = "{0} is not an IP address".format(ip_token)
return response
| Python | 1 |
859d5cd5ac60785f64a87353ae8f9170f5e29100 | Make uri absolute, add get_release_data api | folivora/utils/pypi.py | folivora/utils/pypi.py | #-*- coding: utf-8 -*-
"""
folivora.utils.pypi
~~~~~~~~~~~~~~~~~~~
Utilities to access pypi compatible servers.
"""
import time
import xmlrpclib
def get_seconds(hours):
"""Get number of seconds since epoch from now minus `hours`"""
return int(time.time() - (60 * 60) * hours)
DEFAULT_SERVER = 'http://pypi.python.org/pypi/'
class CheeseShop(object):
def __init__(self, server=DEFAULT_SERVER):
self.xmlrpc = xmlrpclib.Server(server)
def get_package_versions(self, package_name):
"""Fetch list of available versions for a package.
:param package_name: Name of the package to query.
"""
return self.xmlrpc.package_releases(package_name)
def get_package_list(self):
"""Fetch the master list of package names."""
return self.xmlrpc.list_packages()
def search(self, spec, operator):
"""Query using search spec."""
return self.xmlrpc.search(spec, operator.lower())
def get_changelog(self, hours):
"""Query the changelog.
:param hours: Hours from now to specify the changelog size.
"""
return self.xmlrpc.changelog(get_seconds(hours))
def get_updated_releases(self, hours):
"""Query all updated releases within `hours`.
:param hours: Specify the number of hours to find updated releases.
"""
return self.xmlrpc.updated_releases(get_seconds(hours))
def get_release_urls(self, package_name, version):
"""Query for all available release urls of `package_name`.
:param package_name: Name of the package.
:param version: Version of the package.
"""
return self.xmlrpc.release_urls(package_name, version)
def get_release_data(self, package_name, version=None):
"""Query for specific release data.
:param package_name: Name of the package.
:param version: Version to query the data. If `None`, it's latest
version will be used.
"""
if version is None:
version = self.get_package_versions(package_name)[-1]
return self.xmlrpc.release_data(package_name, version)
| #-*- coding: utf-8 -*-
"""
folivora.utils.pypi
~~~~~~~~~~~~~~~~~~~
Utilities to access pypi compatible servers.
"""
import time
import xmlrpclib
def get_seconds(hours):
"""Get number of seconds since epoch from now minus `hours`"""
return int(time.time() - (60 * 60) * hours)
XML_RPC_SERVER = 'http://pypi.python.org/pypi'
class CheeseShop(object):
def __init__(self, server=XML_RPC_SERVER):
self.xmlrpc = xmlrpclib.Server(server)
def get_package_versions(self, package_name):
"""Fetch list of available versions for a package.
:param package_name: Name of the package to query.
"""
return self.xmlrpc.package_releases(package_name)
def get_package_list(self):
"""Fetch the master list of package names."""
return self.xmlrpc.list_packages()
def search(self, spec, operator):
"""Query using search spec."""
return self.xmlrpc.search(spec, operator.lower())
def get_changelog(self, hours):
"""Query the changelog.
:param hours: Hours from now to specify the changelog size.
"""
return self.xmlrpc.changelog(get_seconds(hours))
def get_updated_releases(self, hours):
"""Query all updated releases within `hours`.
:param hours: Specify the number of hours to find updated releases.
"""
return self.xmlrpc.updated_releases(get_seconds(hours))
def get_release_urls(self, package_name, version):
"""Query for all available release urls of `package_name`.
:param package_name: Name of the package.
:param version: Version of the package.
"""
return self.xmlrpc.release_urls(package_name, version)
| Python | 0 |
30b991e78158f8dee25a34565493b1ca582d51c5 | Simplify attribute check (menu items) | cmsplugin_zinnia/cms_toolbar.py | cmsplugin_zinnia/cms_toolbar.py | """Toolbar extensions for CMS"""
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_base import CMSToolbar
from cms.toolbar_pool import toolbar_pool
class ZinniaToolbar(CMSToolbar):
def populate(self):
user = self.request.user
zinnia_menu = self.toolbar.get_or_create_menu(
'zinnia-menu', _('Zinnia'))
url = reverse('admin:zinnia_entry_add')
zinnia_menu.add_sideframe_item(
_('New entry'), url=url,
disabled=not user.has_perm('zinnia.add_entry'))
url = reverse('admin:zinnia_category_add')
zinnia_menu.add_sideframe_item(
_('New category'), url=url,
disabled=not user.has_perm('zinnia.add_category'))
zinnia_menu.add_break()
url = reverse('admin:zinnia_entry_changelist')
zinnia_menu.add_sideframe_item(
_('Entries list'), url=url,
disabled=not user.has_perm('zinnia.change_entry'))
url = reverse('admin:zinnia_category_changelist')
zinnia_menu.add_sideframe_item(
_('Categories list'), url=url,
disabled=not user.has_perm('zinnia.change_category'))
url = reverse('admin:tagging_tag_changelist')
zinnia_menu.add_sideframe_item(
_('Tags list'), url=url,
disabled=not user.has_perm('tagging.change_tag'))
# remove complete menu if all items are disabled
for item in zinnia_menu.get_items():
if not getattr(item, 'disabled', True):
return
self.toolbar.remove_item(zinnia_menu)
toolbar_pool.register(ZinniaToolbar)
| """Toolbar extensions for CMS"""
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_base import CMSToolbar
from cms.toolbar_pool import toolbar_pool
class ZinniaToolbar(CMSToolbar):
def populate(self):
user = self.request.user
zinnia_menu = self.toolbar.get_or_create_menu(
'zinnia-menu', _('Zinnia'))
url = reverse('admin:zinnia_entry_add')
zinnia_menu.add_sideframe_item(
_('New entry'), url=url,
disabled=not user.has_perm('zinnia.add_entry'))
url = reverse('admin:zinnia_category_add')
zinnia_menu.add_sideframe_item(
_('New category'), url=url,
disabled=not user.has_perm('zinnia.add_category'))
zinnia_menu.add_break()
url = reverse('admin:zinnia_entry_changelist')
zinnia_menu.add_sideframe_item(
_('Entries list'), url=url,
disabled=not user.has_perm('zinnia.change_entry'))
url = reverse('admin:zinnia_category_changelist')
zinnia_menu.add_sideframe_item(
_('Categories list'), url=url,
disabled=not user.has_perm('zinnia.change_category'))
url = reverse('admin:tagging_tag_changelist')
zinnia_menu.add_sideframe_item(
_('Tags list'), url=url,
disabled=not user.has_perm('tagging.change_tag'))
# remove complete menu if all items are disabled
for item in zinnia_menu.get_items():
if hasattr(item, 'disabled') and not item.disabled:
return
self.toolbar.remove_item(zinnia_menu)
toolbar_pool.register(ZinniaToolbar)
| Python | 0 |
b3f926e013e81bb88e6634d453b31c5c30aac997 | Add constant to distance scoring functions | cocoscore/ml/distance_scores.py | cocoscore/ml/distance_scores.py | from math import exp
def _distance_scorer(data_df, score_function):
distance_column = 'distance'
if distance_column not in data_df.columns:
raise ValueError(f'The given data_df does not have a {distance_column} column.')
distances = data_df.loc[:, distance_column]
return distances.apply(score_function)
def reciprocal_distance(data_df, *_):
"""
Computes reciprocal distance scores for a given DataFrame of co-mentions.
The reciprocal distance score is defined as 1/x where x is the the distance of the closest matches of an
entity pair of interest.
:param data_df: pandas DataFrame, the data set loaded using
tools.data_tools.load_data_frame(..., match_distance=True)
:returns a pandas Series of distance scores
"""
return polynomial_decay_distance(data_df, 1, 0)
def constant_distance(data_df, *_):
"""
Returns a constant distance score of 1 for a given DataFrame of co-mentions.
:param data_df: pandas DataFrame, the data set loaded using
tools.data_tools.load_data_frame(..., match_distance=True)
:returns a pandas Series of distance scores
"""
return _distance_scorer(data_df, score_function=lambda x: 1.0)
def exponential_decay_distance(data_df, k, c):
"""
Computes exponentially decaying distance scores for a given DataFrame of co-mentions.
The exponentially decaying distance score is defined as exp(-k*x) + c where
x is the the distance of the closest matches of an
entity pair of interest and k is a positive constant.
:param data_df: pandas DataFrame, the data set loaded using
tools.data_tools.load_data_frame(..., match_distance=True)
:param k: float, a positive constant
:param c: float, a positive constant
:returns a pandas Series of distance scores
"""
return _distance_scorer(data_df, lambda x: exp(-k * x) + c)
def polynomial_decay_distance(data_df, k, c):
"""
Computes polynomially decaying distance scores for a given DataFrame of co-mentions.
The polynomially decaying distance score is defined as x^(-k) + c where
x is the the distance of the closest matches of an
entity pair of interest and k is a positive constant.
:param data_df: pandas DataFrame, the data set loaded using
tools.data_tools.load_data_frame(..., match_distance=True)
:param k: float, a positive constant
:param c: float, a positive constant
:returns a pandas Series of distance scores
"""
return _distance_scorer(data_df, lambda x: x ** (-k) + c)
| from math import exp
def _distance_scorer(data_df, score_function):
distance_column = 'distance'
if distance_column not in data_df.columns:
raise ValueError(f'The given data_df does not have a {distance_column} column.')
distances = data_df.loc[:, distance_column]
return distances.apply(score_function)
def reciprocal_distance(data_df, *_):
"""
Computes reciprocal distance scores for a given DataFrame of co-mentions.
The reciprocal distance score is defined as 1/x where x is the the distance of the closest matches of an
entity pair of interest.
:param data_df: pandas DataFrame, the data set loaded using
tools.data_tools.load_data_frame(..., match_distance=True)
:returns a pandas Series of distance scores
"""
return polynomial_decay_distance(data_df, 1)
def constant_distance(data_df, *_):
"""
Returns a constant distance score of 1 for a given DataFrame of co-mentions.
:param data_df: pandas DataFrame, the data set loaded using
tools.data_tools.load_data_frame(..., match_distance=True)
:returns a pandas Series of distance scores
"""
return _distance_scorer(data_df, score_function=lambda x: 1.0)
def exponential_decay_distance(data_df, k):
"""
Computes exponentially decaying distance scores for a given DataFrame of co-mentions.
The exponentially decaying distance score is defined as exp(-k*x) where
x is the the distance of the closest matches of an
entity pair of interest and k is a positive constant.
:param data_df: pandas DataFrame, the data set loaded using
tools.data_tools.load_data_frame(..., match_distance=True)
:param k: float, a positive constant
:returns a pandas Series of distance scores
"""
return _distance_scorer(data_df, lambda x: exp(-k * x))
def polynomial_decay_distance(data_df, k):
"""
Computes polynomially decaying distance scores for a given DataFrame of co-mentions.
The polynomially decaying distance score is defined as x^(-k) where
x is the the distance of the closest matches of an
entity pair of interest and k is a positive constant.
:param data_df: pandas DataFrame, the data set loaded using
tools.data_tools.load_data_frame(..., match_distance=True)
:param k: float, a positive constant
:returns a pandas Series of distance scores
"""
return _distance_scorer(data_df, lambda x: x ** (-k))
| Python | 0.000348 |
a23a9c4e5cd06ff6239a24e55ca7c4c598d02b27 | Fix broken Glance cleanup context | rally/benchmark/context/cleaner.py | rally/benchmark/context/cleaner.py | # Copyright 2014: Mirantis 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.
import functools
import sys
from rally.benchmark.context import base
from rally.benchmark import utils
from rally.openstack.common.gettextutils import _
from rally.openstack.common import log as logging
from rally import osclients
from rally import utils as rutils
LOG = logging.getLogger(__name__)
class ResourceCleaner(base.Context):
"""Context class for resource cleanup (both admin and non-admin)."""
__ctx_name__ = "cleanup"
__ctx_order__ = 200
__ctx_hidden__ = True
CONFIG_SCHEMA = {
"type": "array",
"$schema": rutils.JSON_SCHEMA,
"items": {
"type": "string",
"enum": ["nova", "glance", "cinder"]
},
"uniqueItems": True
}
def __init__(self, context):
super(ResourceCleaner, self).__init__(context)
self.admin = []
self.users = []
@rutils.log_task_wrapper(LOG.info, _("Cleanup users resources."))
def _cleanup_users_resources(self):
for user in self.users:
clients = osclients.Clients(user)
cleanup_methods = {
"nova": functools.partial(utils.delete_nova_resources,
clients.nova()),
"glance": functools.partial(utils.delete_glance_resources,
clients.glance(),
clients.keystone().tenant_id),
"cinder": functools.partial(utils.delete_cinder_resources,
clients.cinder())
}
for service in self.config:
try:
cleanup_methods[service]()
except Exception as e:
LOG.debug(_("Not all resources were cleaned."),
exc_info=sys.exc_info())
LOG.warning(_('Unable to fully cleanup the cloud: %s') %
(e.message))
@rutils.log_task_wrapper(LOG.info, _("Cleanup admin resources."))
def _cleanup_admin_resources(self):
try:
admin = osclients.Clients(self.admin)
utils.delete_keystone_resources(admin.keystone())
except Exception as e:
LOG.debug(_("Not all resources were cleaned."),
exc_info=sys.exc_info())
LOG.warning(_('Unable to fully cleanup keystone service: %s') %
(e.message))
@rutils.log_task_wrapper(LOG.info, _("Enter context: `cleanup`"))
def setup(self):
if "admin" in self.context and self.context["admin"]:
self.admin = self.context["admin"]["endpoint"]
if "users" in self.context and self.context["users"]:
self.users = [u["endpoint"] for u in self.context["users"]]
@rutils.log_task_wrapper(LOG.info, _("Exit context: `cleanup`"))
def cleanup(self):
if self.users and self.config:
self._cleanup_users_resources()
if self.admin:
self._cleanup_admin_resources()
def cleanup(services):
"""Decorates scenario methods requiring a cleanup of resources.
If a scenario method is not decorated by @cleanup all the resources
(nova, glance and cinder) will be cleaned.
:param services: list of services which will be cleaned.
"""
def wrap(func):
func.cleanup_services = services
return func
return wrap
| # Copyright 2014: Mirantis 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.
import functools
import sys
from rally.benchmark.context import base
from rally.benchmark import utils
from rally.openstack.common.gettextutils import _
from rally.openstack.common import log as logging
from rally import osclients
from rally import utils as rutils
LOG = logging.getLogger(__name__)
class ResourceCleaner(base.Context):
"""Context class for resource cleanup (both admin and non-admin)."""
__ctx_name__ = "cleanup"
__ctx_order__ = 200
__ctx_hidden__ = True
CONFIG_SCHEMA = {
"type": "array",
"$schema": rutils.JSON_SCHEMA,
"items": {
"type": "string",
"enum": ["nova", "glance", "cinder"]
},
"uniqueItems": True
}
def __init__(self, context):
super(ResourceCleaner, self).__init__(context)
self.admin = []
self.users = []
@rutils.log_task_wrapper(LOG.info, _("Cleanup users resources."))
def _cleanup_users_resources(self):
for user in self.users:
clients = osclients.Clients(user)
cleanup_methods = {
"nova": functools.partial(utils.delete_nova_resources,
clients.nova()),
"glance": functools.partial(utils.delete_glance_resources,
clients.glance(),
clients.keystone()),
"cinder": functools.partial(utils.delete_cinder_resources,
clients.cinder())
}
for service in self.config:
try:
cleanup_methods[service]()
except Exception as e:
LOG.debug(_("Not all resources were cleaned."),
exc_info=sys.exc_info())
LOG.warning(_('Unable to fully cleanup the cloud: %s') %
(e.message))
@rutils.log_task_wrapper(LOG.info, _("Cleanup admin resources."))
def _cleanup_admin_resources(self):
try:
admin = osclients.Clients(self.admin)
utils.delete_keystone_resources(admin.keystone())
except Exception as e:
LOG.debug(_("Not all resources were cleaned."),
exc_info=sys.exc_info())
LOG.warning(_('Unable to fully cleanup keystone service: %s') %
(e.message))
@rutils.log_task_wrapper(LOG.info, _("Enter context: `cleanup`"))
def setup(self):
if "admin" in self.context and self.context["admin"]:
self.admin = self.context["admin"]["endpoint"]
if "users" in self.context and self.context["users"]:
self.users = [u["endpoint"] for u in self.context["users"]]
@rutils.log_task_wrapper(LOG.info, _("Exit context: `cleanup`"))
def cleanup(self):
if self.users and self.config:
self._cleanup_users_resources()
if self.admin:
self._cleanup_admin_resources()
def cleanup(services):
"""Decorates scenario methods requiring a cleanup of resources.
If a scenario method is not decorated by @cleanup all the resources
(nova, glance and cinder) will be cleaned.
:param services: list of services which will be cleaned.
"""
def wrap(func):
func.cleanup_services = services
return func
return wrap
| Python | 0.000064 |
a668300c2e038b40b2ea6bbc51cb47598f4a5688 | Use AwesomeVersion for account link service check (#55449) | homeassistant/components/cloud/account_link.py | homeassistant/components/cloud/account_link.py | """Account linking via the cloud."""
import asyncio
import logging
from typing import Any
import aiohttp
from awesomeversion import AwesomeVersion
from hass_nabucasa import account_link
from homeassistant.const import __version__ as HA_VERSION
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_entry_oauth2_flow, event
from .const import DOMAIN
DATA_SERVICES = "cloud_account_link_services"
CACHE_TIMEOUT = 3600
_LOGGER = logging.getLogger(__name__)
CURRENT_VERSION = AwesomeVersion(HA_VERSION)
@callback
def async_setup(hass: HomeAssistant):
"""Set up cloud account link."""
config_entry_oauth2_flow.async_add_implementation_provider(
hass, DOMAIN, async_provide_implementation
)
async def async_provide_implementation(hass: HomeAssistant, domain: str):
"""Provide an implementation for a domain."""
services = await _get_services(hass)
for service in services:
if service["service"] == domain and CURRENT_VERSION >= service["min_version"]:
return CloudOAuth2Implementation(hass, domain)
return
async def _get_services(hass):
"""Get the available services."""
services = hass.data.get(DATA_SERVICES)
if services is not None:
return services
try:
services = await account_link.async_fetch_available_services(hass.data[DOMAIN])
except (aiohttp.ClientError, asyncio.TimeoutError):
return []
hass.data[DATA_SERVICES] = services
@callback
def clear_services(_now):
"""Clear services cache."""
hass.data.pop(DATA_SERVICES, None)
event.async_call_later(hass, CACHE_TIMEOUT, clear_services)
return services
class CloudOAuth2Implementation(config_entry_oauth2_flow.AbstractOAuth2Implementation):
"""Cloud implementation of the OAuth2 flow."""
def __init__(self, hass: HomeAssistant, service: str) -> None:
"""Initialize cloud OAuth2 implementation."""
self.hass = hass
self.service = service
@property
def name(self) -> str:
"""Name of the implementation."""
return "Home Assistant Cloud"
@property
def domain(self) -> str:
"""Domain that is providing the implementation."""
return DOMAIN
async def async_generate_authorize_url(self, flow_id: str) -> str:
"""Generate a url for the user to authorize."""
helper = account_link.AuthorizeAccountHelper(
self.hass.data[DOMAIN], self.service
)
authorize_url = await helper.async_get_authorize_url()
async def await_tokens():
"""Wait for tokens and pass them on when received."""
try:
tokens = await helper.async_get_tokens()
except asyncio.TimeoutError:
_LOGGER.info("Timeout fetching tokens for flow %s", flow_id)
except account_link.AccountLinkException as err:
_LOGGER.info(
"Failed to fetch tokens for flow %s: %s", flow_id, err.code
)
else:
await self.hass.config_entries.flow.async_configure(
flow_id=flow_id, user_input=tokens
)
self.hass.async_create_task(await_tokens())
return authorize_url
async def async_resolve_external_data(self, external_data: Any) -> dict:
"""Resolve external data to tokens."""
# We already passed in tokens
return external_data
async def _async_refresh_token(self, token: dict) -> dict:
"""Refresh a token."""
new_token = await account_link.async_fetch_access_token(
self.hass.data[DOMAIN], self.service, token["refresh_token"]
)
return {**token, **new_token}
| """Account linking via the cloud."""
import asyncio
import logging
from typing import Any
import aiohttp
from hass_nabucasa import account_link
from homeassistant.const import MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_entry_oauth2_flow, event
from .const import DOMAIN
DATA_SERVICES = "cloud_account_link_services"
CACHE_TIMEOUT = 3600
_LOGGER = logging.getLogger(__name__)
@callback
def async_setup(hass: HomeAssistant):
"""Set up cloud account link."""
config_entry_oauth2_flow.async_add_implementation_provider(
hass, DOMAIN, async_provide_implementation
)
async def async_provide_implementation(hass: HomeAssistant, domain: str):
"""Provide an implementation for a domain."""
services = await _get_services(hass)
for service in services:
if service["service"] == domain and _is_older(service["min_version"]):
return CloudOAuth2Implementation(hass, domain)
return
@callback
def _is_older(version: str) -> bool:
"""Test if a version is older than the current HA version."""
version_parts = version.split(".")
if len(version_parts) != 3:
return False
try:
version_parts = [int(val) for val in version_parts]
except ValueError:
return False
patch_number_str = ""
for char in PATCH_VERSION:
if char.isnumeric():
patch_number_str += char
else:
break
try:
patch_number = int(patch_number_str)
except ValueError:
patch_number = 0
cur_version_parts = [MAJOR_VERSION, MINOR_VERSION, patch_number]
return version_parts <= cur_version_parts
async def _get_services(hass):
"""Get the available services."""
services = hass.data.get(DATA_SERVICES)
if services is not None:
return services
try:
services = await account_link.async_fetch_available_services(hass.data[DOMAIN])
except (aiohttp.ClientError, asyncio.TimeoutError):
return []
hass.data[DATA_SERVICES] = services
@callback
def clear_services(_now):
"""Clear services cache."""
hass.data.pop(DATA_SERVICES, None)
event.async_call_later(hass, CACHE_TIMEOUT, clear_services)
return services
class CloudOAuth2Implementation(config_entry_oauth2_flow.AbstractOAuth2Implementation):
"""Cloud implementation of the OAuth2 flow."""
def __init__(self, hass: HomeAssistant, service: str) -> None:
"""Initialize cloud OAuth2 implementation."""
self.hass = hass
self.service = service
@property
def name(self) -> str:
"""Name of the implementation."""
return "Home Assistant Cloud"
@property
def domain(self) -> str:
"""Domain that is providing the implementation."""
return DOMAIN
async def async_generate_authorize_url(self, flow_id: str) -> str:
"""Generate a url for the user to authorize."""
helper = account_link.AuthorizeAccountHelper(
self.hass.data[DOMAIN], self.service
)
authorize_url = await helper.async_get_authorize_url()
async def await_tokens():
"""Wait for tokens and pass them on when received."""
try:
tokens = await helper.async_get_tokens()
except asyncio.TimeoutError:
_LOGGER.info("Timeout fetching tokens for flow %s", flow_id)
except account_link.AccountLinkException as err:
_LOGGER.info(
"Failed to fetch tokens for flow %s: %s", flow_id, err.code
)
else:
await self.hass.config_entries.flow.async_configure(
flow_id=flow_id, user_input=tokens
)
self.hass.async_create_task(await_tokens())
return authorize_url
async def async_resolve_external_data(self, external_data: Any) -> dict:
"""Resolve external data to tokens."""
# We already passed in tokens
return external_data
async def _async_refresh_token(self, token: dict) -> dict:
"""Refresh a token."""
new_token = await account_link.async_fetch_access_token(
self.hass.data[DOMAIN], self.service, token["refresh_token"]
)
return {**token, **new_token}
| Python | 0 |
33dd1a78a5bfdf0eca593816b15b34b86860c36f | install pip to bypass rally installation problem | lab/runners/RunnerRally.py | lab/runners/RunnerRally.py | from lab.runners import Runner
class RunnerRally(Runner):
def sample_config(self):
return {'cloud': 'cloud name', 'task-yaml': 'path to the valid task yaml file'}
def __init__(self, config):
from lab.WithConfig import read_config_from_file
super(RunnerRally, self).__init__(config=config)
self.cloud_name = config['cloud']
self.task_yaml_path = config['task-yaml']
self.task_body = read_config_from_file(yaml_path=self.task_yaml_path, is_as_string=True)
def execute(self, clouds, servers):
cloud = clouds[0]
server = servers[0]
open_rc_path = '{0}.openrc'.format(self.cloud_name)
results_path = 'rally-results.html'
task_path = 'rally-task.yaml'
venv_path = '~/venv_rally'
open_rc_body = cloud.create_open_rc()
server.create_user(new_username='rally')
server.put(string_to_put=open_rc_body, file_name=open_rc_path)
server.put(string_to_put=self.task_body, file_name=task_path)
repo_dir = server.clone_repo(repo_url='https://git.openstack.org/openstack/rally.git')
server.check_or_install_packages(package_names='libffi-devel gmp-devel postgresql-devel wget python-virtualenv')
server.run(command='sudo easy_install pip')
server.run(command='./install_rally.sh -y -d {0}'.format(venv_path), in_directory=repo_dir)
server.run(command='source {0} && {1}/bin/rally deployment create --fromenv --name {2}'.format(open_rc_path, venv_path, self.cloud_name))
server.run(command='{0}/bin/rally task start {1}'.format(venv_path, task_path))
server.run(command='{0}/bin/rally task report --out {1}'.format(venv_path, results_path))
server.get(remote_path=results_path, local_path=results_path)
self.get_artefacts(server=server)
| from lab.runners import Runner
class RunnerRally(Runner):
def sample_config(self):
return {'cloud': 'cloud name', 'task-yaml': 'path to the valid task yaml file'}
def __init__(self, config):
from lab.WithConfig import read_config_from_file
super(RunnerRally, self).__init__(config=config)
self.cloud_name = config['cloud']
self.task_yaml_path = config['task-yaml']
self.task_body = read_config_from_file(yaml_path=self.task_yaml_path, is_as_string=True)
def execute(self, clouds, servers):
cloud = clouds[0]
server = servers[0]
open_rc_path = '{0}.openrc'.format(self.cloud_name)
results_path = 'rally-results.html'
task_path = 'rally-task.yaml'
venv_path = '~/venv_rally'
open_rc_body = cloud.create_open_rc()
server.create_user(new_username='rally')
server.put(string_to_put=open_rc_body, file_name=open_rc_path)
server.put(string_to_put=self.task_body, file_name=task_path)
repo_dir = server.clone_repo(repo_url='https://git.openstack.org/openstack/rally.git')
server.check_or_install_packages(package_names='libffi-devel gmp-devel postgresql-devel wget python-virtualenv')
server.run(command='./install_rally.sh -y -d {0}'.format(venv_path), in_directory=repo_dir)
server.run(command='source {0} && {1}/bin/rally deployment create --fromenv --name {2}'.format(open_rc_path, venv_path, self.cloud_name))
server.run(command='{0}/bin/rally task start {1}'.format(venv_path, task_path))
server.run(command='{0}/bin/rally task report --out {1}'.format(venv_path, results_path))
server.get(remote_path=results_path, local_path=results_path)
self.get_artefacts(server=server)
| Python | 0 |
2c5d3387f23eaff6a689aad46b7b117f3a54bed1 | Fix wake_on_lan ping for Linux. (#6480) | homeassistant/components/switch/wake_on_lan.py | homeassistant/components/switch/wake_on_lan.py | """
Support for wake on lan.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.wake_on_lan/
"""
import logging
import platform
import subprocess as sp
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.script import Script
from homeassistant.const import (CONF_HOST, CONF_NAME)
REQUIREMENTS = ['wakeonlan==0.2.2']
_LOGGER = logging.getLogger(__name__)
CONF_MAC_ADDRESS = 'mac_address'
CONF_OFF_ACTION = 'turn_off'
DEFAULT_NAME = 'Wake on LAN'
DEFAULT_PING_TIMEOUT = 1
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_MAC_ADDRESS): cv.string,
vol.Optional(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_OFF_ACTION): cv.SCRIPT_SCHEMA,
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up a wake on lan switch."""
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
mac_address = config.get(CONF_MAC_ADDRESS)
off_action = config.get(CONF_OFF_ACTION)
add_devices([WOLSwitch(hass, name, host, mac_address, off_action)])
class WOLSwitch(SwitchDevice):
"""Representation of a wake on lan switch."""
def __init__(self, hass, name, host, mac_address, off_action):
"""Initialize the WOL switch."""
from wakeonlan import wol
self._hass = hass
self._name = name
self._host = host
self._mac_address = mac_address
self._off_script = Script(hass, off_action) if off_action else None
self._state = False
self._wol = wol
self.update()
@property
def should_poll(self):
"""Poll for status regularly."""
return True
@property
def is_on(self):
"""Return true if switch is on."""
return self._state
@property
def name(self):
"""The name of the switch."""
return self._name
def turn_on(self):
"""Turn the device on."""
self._wol.send_magic_packet(self._mac_address)
def turn_off(self):
"""Turn the device off if an off action is present."""
if self._off_script is not None:
self._off_script.run()
def update(self):
"""Check if device is on and update the state."""
if platform.system().lower() == 'windows':
ping_cmd = ['ping', '-n', '1', '-w',
str(DEFAULT_PING_TIMEOUT * 1000), self._host]
else:
ping_cmd = ['ping', '-c', '1', '-W',
str(DEFAULT_PING_TIMEOUT), self._host]
status = sp.call(ping_cmd, stdout=sp.DEVNULL)
self._state = not bool(status)
| """
Support for wake on lan.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.wake_on_lan/
"""
import logging
import platform
import subprocess as sp
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.script import Script
from homeassistant.const import (CONF_HOST, CONF_NAME)
REQUIREMENTS = ['wakeonlan==0.2.2']
_LOGGER = logging.getLogger(__name__)
CONF_MAC_ADDRESS = 'mac_address'
CONF_OFF_ACTION = 'turn_off'
DEFAULT_NAME = 'Wake on LAN'
DEFAULT_PING_TIMEOUT = 1
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_MAC_ADDRESS): cv.string,
vol.Optional(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_OFF_ACTION): cv.SCRIPT_SCHEMA,
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up a wake on lan switch."""
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
mac_address = config.get(CONF_MAC_ADDRESS)
off_action = config.get(CONF_OFF_ACTION)
add_devices([WOLSwitch(hass, name, host, mac_address, off_action)])
class WOLSwitch(SwitchDevice):
"""Representation of a wake on lan switch."""
def __init__(self, hass, name, host, mac_address, off_action):
"""Initialize the WOL switch."""
from wakeonlan import wol
self._hass = hass
self._name = name
self._host = host
self._mac_address = mac_address
self._off_script = Script(hass, off_action) if off_action else None
self._state = False
self._wol = wol
self.update()
@property
def should_poll(self):
"""Poll for status regularly."""
return True
@property
def is_on(self):
"""Return true if switch is on."""
return self._state
@property
def name(self):
"""The name of the switch."""
return self._name
def turn_on(self):
"""Turn the device on."""
self._wol.send_magic_packet(self._mac_address)
def turn_off(self):
"""Turn the device off if an off action is present."""
if self._off_script is not None:
self._off_script.run()
def update(self):
"""Check if device is on and update the state."""
if platform.system().lower() == 'windows':
ping_cmd = 'ping -n 1 -w {} {}'.format(
DEFAULT_PING_TIMEOUT * 1000, self._host)
else:
ping_cmd = 'ping -c 1 -W {} {}'.format(
DEFAULT_PING_TIMEOUT, self._host)
status = sp.call(ping_cmd, stdout=sp.DEVNULL)
self._state = not bool(status)
| Python | 0 |
c5fff613e5b860d3df51fa45189d379c3e1aeb68 | Support for namespace in graphite bridge #49 | prometheus_client/bridge/graphite.py | prometheus_client/bridge/graphite.py | #!/usr/bin/python
from __future__ import unicode_literals
import logging
import re
import socket
import time
import threading
from .. import core
# Roughly, have to keep to what works as a file name.
# We also remove periods, so labels can be distinguished.
_INVALID_GRAPHITE_CHARS = re.compile(r"[^a-zA-Z0-9_-]")
def _sanitize(s):
return _INVALID_GRAPHITE_CHARS.sub('_', s)
class _RegularPush(threading.Thread):
def __init__(self, pusher, interval, prefix):
super(_RegularPush, self).__init__()
self._pusher = pusher
self._interval = interval
self._prefix = prefix
def run(self):
wait_until = time.time()
while True:
while True:
now = time.time()
if now >= wait_until:
# May need to skip some pushes.
while wait_until < now:
wait_until += self._interval
break
# time.sleep can return early.
time.sleep(wait_until - now)
try:
self._pusher.push(prefix=self._prefix)
except IOError:
logging.exception("Push failed")
class GraphiteBridge(object):
def __init__(self, address, registry=core.REGISTRY, timeout_seconds=30, _time=time):
self._address = address
self._registry = registry
self._timeout = timeout_seconds
self._time = _time
def push(self, prefix=''):
now = int(self._time.time())
output = []
prefixstr = ''
if prefix:
prefixstr = prefix + '.'
for metric in self._registry.collect():
for name, labels, value in metric._samples:
if labels:
labelstr = '.' + '.'.join(
['{0}.{1}'.format(
_sanitize(k), _sanitize(v))
for k, v in sorted(labels.items())])
else:
labelstr = ''
output.append('{0}{1}{2} {3} {4}\n'.format(
prefixstr, _sanitize(name), labelstr, float(value), now))
conn = socket.create_connection(self._address, self._timeout)
conn.sendall(''.join(output).encode('ascii'))
conn.close()
def start(self, interval=60.0, prefix=''):
t = _RegularPush(self, interval, prefix)
t.daemon = True
t.start()
| #!/usr/bin/python
from __future__ import unicode_literals
import logging
import re
import socket
import time
import threading
from .. import core
# Roughly, have to keep to what works as a file name.
# We also remove periods, so labels can be distinguished.
_INVALID_GRAPHITE_CHARS = re.compile(r"[^a-zA-Z0-9_-]")
def _sanitize(s):
return _INVALID_GRAPHITE_CHARS.sub('_', s)
class _RegularPush(threading.Thread):
def __init__(self, pusher, interval):
super(_RegularPush, self).__init__()
self._pusher = pusher
self._interval = interval
def run(self):
wait_until = time.time()
while True:
while True:
now = time.time()
if now >= wait_until:
# May need to skip some pushes.
while wait_until < now:
wait_until += self._interval
break
# time.sleep can return early.
time.sleep(wait_until - now)
try:
self._pusher.push()
except IOError:
logging.exception("Push failed")
class GraphiteBridge(object):
def __init__(self, address, registry=core.REGISTRY, timeout_seconds=30, _time=time):
self._address = address
self._registry = registry
self._timeout = timeout_seconds
self._time = _time
def push(self, prefix=''):
now = int(self._time.time())
output = []
prefixstr = ''
if prefix:
prefixstr = prefix + '.'
for metric in self._registry.collect():
for name, labels, value in metric._samples:
if labels:
labelstr = '.' + '.'.join(
['{0}.{1}'.format(
_sanitize(k), _sanitize(v))
for k, v in sorted(labels.items())])
else:
labelstr = ''
output.append('{0}{1}{2} {3} {4}\n'.format(
prefixstr, _sanitize(name), labelstr, float(value), now))
conn = socket.create_connection(self._address, self._timeout)
conn.sendall(''.join(output).encode('ascii'))
conn.close()
def start(self, interval=60.0):
t = _RegularPush(self, interval)
t.daemon = True
t.start()
| Python | 0 |
a390d2551a5e39ad35888c4b326f50212b60cabf | add description of exception | eventbus/exception.py | eventbus/exception.py | __author__ = 'Xsank'
class EventTypeError(Exception):
'''Event type is invalid!'''
def __str__(self):
return self.__doc__
class UnregisterError(Exception):
'''No listener to unregister!'''
def __str__(self):
return self.__doc__ | __author__ = 'Xsank'
class EventTypeError(Exception):
'''Event type is invalid!'''
class UnregisterError(Exception):
'''No listener to unregister!''' | Python | 0.000002 |
0f1fdb93c8005a26fcea10f708252a9e5f358270 | add compare string in JRC | src/JRCFileParserService.py | src/JRCFileParserService.py | '''
Created on Jan 30, 2017
@author: Subhasis
'''
import csv
from MongoManager import MongoManager
class JRCFileParserService(object):
'''
This class takes care of reading the input file parsing the text line by line and pushing it into MongoDB.
'''
def __init__(self, file_path, db_config, schema, table, batch_size):
self.file_path = file_path
self.manager = MongoManager(schema, table, batch_size, db_config)
def process(self):
print "Reading File ", self.file_path
count_record = 0
entity_count = 0
similar_record = []
previous_record_id = '0'
with open(self.file_path, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
for row in reader:
if previous_record_id != row[0]:
self.manager.pushRecords(self.getInsertObject(similar_record))
entity_count += 1
similar_record = []
similar_record.append(row)
previous_record_id = row[0]
count_record += 1
self.manager.pushRecords(self.getInsertObject(similar_record))
print "Records Processed ", count_record
print "Entity Processed ", entity_count
return self.manager.flushBatch()
def getInsertObject(self, data_list):
d = {}
d['id'] = int(data_list[0][0])
d['type'] = 'UNKNOWN'
if data_list[0][1] == 'P':
d['type'] = 'PERSON'
if data_list[0][1] == 'O':
d['type'] = 'ORGANIZATION'
variations = []
compare_strings = []
for r in data_list:
v = {}
v['lang'] = r[2]
v['name'] = r[3]
variations.append(v)
compare_strings.append(r[3].lower())
d['variations'] = variations
d['compare_strings'] = compare_strings
return d
| '''
Created on Jan 30, 2017
@author: Subhasis
'''
import csv
from MongoManager import MongoManager
class JRCFileParserService(object):
'''
This class takes care of reading the input file parsing the text line by line and pushing it into MongoDB.
'''
def __init__(self, file_path, db_config, schema, table, batch_size):
self.file_path = file_path
self.manager = MongoManager(schema, table, batch_size, db_config)
def process(self):
print "Reading File ", self.file_path
count_record = 0
entity_count = 0
similar_record = []
previous_record_id = '0'
with open(self.file_path, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
for row in reader:
if previous_record_id != row[0]:
self.manager.pushRecords(self.getInsertObject(similar_record))
entity_count += 1
similar_record = []
similar_record.append(row)
previous_record_id = row[0]
count_record += 1
self.manager.pushRecords(self.getInsertObject(similar_record))
print "Records Processed ", count_record
print "Entity Processed ", entity_count
return self.manager.flushBatch()
def getInsertObject(self, data_list):
d = {}
d['id'] = int(data_list[0][0])
d['type'] = 'UNKNOWN'
if data_list[0][1] == 'P':
d['type'] = 'PERSON'
if data_list[0][1] == 'O':
d['type'] = 'ORGANIZATION'
variations = []
for r in data_list:
v = {}
v['lang'] = r[2]
v['name'] = r[3]
variations.append(v)
d['variations'] = variations
return d
| Python | 0.00002 |
0ff9ccacf20d2896353df906426db06ce8c24605 | Update ASIC count from 7 to 10 | scripts/avalon3-a3233-modular-test.py | scripts/avalon3-a3233-modular-test.py | #!/usr/bin/env python2.7
# This simple script was for test A3255 modular. there are 128 cores in one A3255 chip.
# If all cores are working the number should be 0.
# If some of them not working the number is the broken cores count.
from serial import Serial
from optparse import OptionParser
import binascii
import sys
parser = OptionParser()
parser.add_option("-s", "--serial", dest="serial_port", default="/dev/ttyUSB0", help="Serial port")
(options, args) = parser.parse_args()
ser = Serial(options.serial_port, 115200, 8, timeout=8)
cmd="415614010100000000000000000000000000000000000000000000000000000000000000000000"
#cmd="415614010100000000000000000000000000000000000000000000000000000000000000011021"
#cmd="415614010100000000000000000000000000000000000000000000000000000000000000022042"
while (1):
print ("Reading result ...")
ser.write(cmd.decode('hex'))
count = 0
while (1):
res_s = ser.read(39)
if not res_s:
print(str(count) + ": Something is wrong or modular id not correct")
else :
result = binascii.hexlify(res_s)
for i in range(0, 11):
number = '{:03}'.format(int(result[10 + i * 2:12 + i * 2], 16))
if (i == 0):
sys.stdout.write(number + ":\t")
else :
sys.stdout.write(number + "\t")
sys.stdout.flush()
print("")
count = count + 1
if (count == 5):
raw_input('Press enter to continue:')
break
| #!/usr/bin/env python2.7
# This simple script was for test A3255 modular. there are 128 cores in one A3255 chip.
# If all cores are working the number should be 0.
# If some of them not working the number is the broken cores count.
from serial import Serial
from optparse import OptionParser
import binascii
import sys
parser = OptionParser()
parser.add_option("-s", "--serial", dest="serial_port", default="/dev/ttyUSB0", help="Serial port")
(options, args) = parser.parse_args()
ser = Serial(options.serial_port, 115200, 8, timeout=8)
cmd="415614010100000000000000000000000000000000000000000000000000000000000000000000"
#cmd="415614010100000000000000000000000000000000000000000000000000000000000000011021"
#cmd="415614010100000000000000000000000000000000000000000000000000000000000000022042"
while (1):
print ("Reading result ...")
ser.write(cmd.decode('hex'))
count = 0
while (1):
res_s = ser.read(39)
if not res_s:
print(str(count) + ": Something is wrong or modular id not correct")
else :
result = binascii.hexlify(res_s)
for i in range(0, 8):
number = '{:03}'.format(int(result[10 + i * 2:12 + i * 2], 16))
if (i == 0):
sys.stdout.write(number + ":\t")
else :
sys.stdout.write(number + "\t")
sys.stdout.flush()
print("")
count = count + 1
if (count == 5):
raw_input('Press enter to continue:')
break
| Python | 0.000013 |
1b704c24eaeb412e0636e5a0111ce2ac990998fd | remove confirm_text option in example | example/app/tables.py | example/app/tables.py | #!/usr/bin/env python
# coding: utf-8
from table.columns import Column, LinkColumn, Link
from table.utils import A
from table import Table
from models import Person
class PersonTable(Table):
id = Column(field='id', header=u'序号', header_attrs={'width': '50%'})
name = Column(field='name', header=u'姓名', header_attrs={'width': '50%'})
class Meta:
model = Person
ext_button_link = "http://www.baidu.com"
class LinkColumnTable(Table):
id = Column(field='id', header=u'序号', header_attrs={'width': '33%'})
name = Column(field='name', header=u'姓名', header_attrs={'width': '33%'})
action = LinkColumn(header=u'操作', header_attrs={'width': '33%'}, links=[
Link(text=u'编辑', viewname='app.views.edit', args=('id',), confirm=u"确定吗?")])
class Meta:
model = Person
| #!/usr/bin/env python
# coding: utf-8
from table.columns import Column, LinkColumn, Link
from table.utils import A
from table import Table
from models import Person
class PersonTable(Table):
id = Column(field='id', header=u'序号', header_attrs={'width': '50%'})
name = Column(field='name', header=u'姓名', header_attrs={'width': '50%'})
class Meta:
model = Person
ext_button_link = "http://www.baidu.com"
class LinkColumnTable(Table):
id = Column(field='id', header=u'序号', header_attrs={'width': '33%'})
name = Column(field='name', header=u'姓名', header_attrs={'width': '33%'})
action = LinkColumn(header=u'操作', header_attrs={'width': '33%'}, links=[
Link(text=u'编辑', viewname='app.views.edit', args=('id',), confirm=True, confirm_text=u"确定吗?")])
class Meta:
model = Person
| Python | 0 |
1591faf725844ae76bdf0a4343837e1c3d2e16c0 | update weight clipping params | common/models/discriminators.py | common/models/discriminators.py | import numpy as np
import math
import chainer
import chainer.functions as F
import chainer.links as L
from chainer import cuda, optimizers, serializers, Variable
from chainer import function
from chainer.utils import type_check
from .ops import *
class DCGANDiscriminator(chainer.Chain):
def __init__(self, in_ch=3, base_size=128, down_layers=4, use_bn=True, noise_all_layers=False, conv_as_last=False, w_init=None):
layers = {}
self.down_layers = down_layers
self.conv_as_last = conv_as_last
if use_bn:
norm = 'bn'
else:
norm = None
act = F.leaky_relu
if w_init is None:
w_init = chainer.initializers.Normal(0.02)
layers['c_first'] = NNBlock(in_ch, base_size, nn='down_conv', norm=None, activation=act, noise=noise_all_layers, w_init=w_init)
base = base_size
for i in range(down_layers-1):
layers['c'+str(i)] = NNBlock(base, base*2, nn='down_conv', norm=norm, activation=act, noise=noise_all_layers, w_init=w_init)
base*=2
if conv_as_last:
layers['c_last'] = NNBlock(base, 1, nn='conv', norm=None, activation=None, w_init=w_init)
else:
layers['c_last'] = NNBlock(None, 1, nn='linear', norm=None, activation=None, w_init=w_init)
super(DCGANDiscriminator, self).__init__(**layers)
def __call__(self, x, test=False, retain_forward=False):
h = self.c_first(x, test=test, retain_forward=retain_forward)
for i in range(self.down_layers-1):
h = getattr(self, 'c'+str(i))(h, test=test, retain_forward=retain_forward)
if not self.conv_as_last:
_b, _ch, _w, _h = h.data.shape
self.last_shape=(_b, _ch, _w, _h)
h = F.reshape(h, (_b, _ch*_w*_h))
h = self.c_last(h, test=test, retain_forward=retain_forward)
return h
def clip(self, upper=0.01, lower=-0.01):
weight_clipping(self, upper=upper, lower=lower)
def differentiable_backward(self, g):
g = self.c_last.differentiable_backward(g)
if not self.conv_as_last:
_b, _ch, _w, _h = self.last_shape
g = F.reshape(g, (_b, _ch, _w, _h))
for i in reversed(range(self.down_layers-1)):
g = getattr(self, 'c'+str(i)).differentiable_backward(g)
g = self.c_first.differentiable_backward(g)
return g
| import numpy as np
import math
import chainer
import chainer.functions as F
import chainer.links as L
from chainer import cuda, optimizers, serializers, Variable
from chainer import function
from chainer.utils import type_check
from .ops import *
class DCGANDiscriminator(chainer.Chain):
def __init__(self, in_ch=3, base_size=128, down_layers=4, use_bn=True, noise_all_layers=False, conv_as_last=False, w_init=None):
layers = {}
self.down_layers = down_layers
self.conv_as_last = conv_as_last
if use_bn:
norm = 'bn'
else:
norm = None
act = F.leaky_relu
if w_init is None:
w_init = chainer.initializers.Normal(0.02)
layers['c_first'] = NNBlock(in_ch, base_size, nn='down_conv', norm=None, activation=act, noise=noise_all_layers, w_init=w_init)
base = base_size
for i in range(down_layers-1):
layers['c'+str(i)] = NNBlock(base, base*2, nn='down_conv', norm=norm, activation=act, noise=noise_all_layers, w_init=w_init)
base*=2
if conv_as_last:
layers['c_last'] = NNBlock(base, 1, nn='conv', norm=None, activation=None, w_init=w_init)
else:
layers['c_last'] = NNBlock(None, 1, nn='linear', norm=None, activation=None, w_init=w_init)
super(DCGANDiscriminator, self).__init__(**layers)
def __call__(self, x, test=False, retain_forward=False):
h = self.c_first(x, test=test, retain_forward=retain_forward)
for i in range(self.down_layers-1):
h = getattr(self, 'c'+str(i))(h, test=test, retain_forward=retain_forward)
if not self.conv_as_last:
_b, _ch, _w, _h = h.data.shape
self.last_shape=(_b, _ch, _w, _h)
h = F.reshape(h, (_b, _ch*_w*_h))
h = self.c_last(h, test=test, retain_forward=retain_forward)
return h
def clip(self, upper=0.1, lower=-0.1):
weight_clipping(self, upper=upper, lower=lower)
def differentiable_backward(self, g):
g = self.c_last.differentiable_backward(g)
if not self.conv_as_last:
_b, _ch, _w, _h = self.last_shape
g = F.reshape(g, (_b, _ch, _w, _h))
for i in reversed(range(self.down_layers-1)):
g = getattr(self, 'c'+str(i)).differentiable_backward(g)
g = self.c_first.differentiable_backward(g)
return g
| Python | 0 |
cb34162de51f36e2d6b846cfbb6e9d6fe8801e48 | implement send message | client/client.py | client/client.py | class OTC_Client(object):
def __init__(self):
raise NotImplementedError("TODO: write a client")
def send(message):
payload = {'message':message}
r = requets.post(self.server_address,data=payload)
raise NotImplementedError("TODO: write send method")
def recieve():
raise NotImplementedError("TODO: write recieve")
def decrypt(message, pad_index=current_index):
raise NotImplementedError("TODO: clients need to decrypt messages")
def encrypt(encrypt):
raise NotImplementedError("TODO: clients need to encrypt messages")
def connect(server_address):
self.server_address = server_address
raise NotImplementedError("TODO:clients need to be able to connect to server")
if __name__ == "__main__":
client = OTC_Client()
| class OTC_Client(object):
def __init__(self):
raise NotImplementedError("TODO: write a client")
def send(message):
raise NotImplementedError("TODO: write send method")
def recieve():
raise NotImplementedError("TODO: write recieve")
def decrypt(message, pad_index=current_index):
raise NotImplementedError("TODO: clients need to decrypt messages")
def encrypt(encrypt):
raise NotImplementedError("TODO: clients need to encrypt messages")
def connect():
raise NotImplementedError("TODO:clients need to be able to connect to server")
if __name__ == "__main__":
client = OTC_Client()
| Python | 0.000029 |
f1ed9cf573ec8aaa61e9aefb124b453a5a353db4 | fix pointe-claire | ca_qc_pointe_claire/people.py | ca_qc_pointe_claire/people.py | from pupa.scrape import Scraper
from utils import lxmlize, CanadianLegislator as Legislator
import re
COUNCIL_PAGE = 'http://www.ville.pointe-claire.qc.ca/en/city-hall-administration/your-council/municipal-council.html'
class PointeClairePersonScraper(Scraper):
def get_people(self):
page = lxmlize(COUNCIL_PAGE)
mayor = page.xpath('.//div[@class="item-page clearfix"]//table[1]//p')[1]
name = mayor.xpath('.//strong/text()')[0]
p = Legislator(name=name, post_id='Pointe-Claire', role='Maire')
p.add_source(COUNCIL_PAGE)
phone = re.findall(r'[0-9]{3}[ -][0-9]{3}-[0-9]{4}', mayor.text_content())[0].replace(' ', '-')
p.add_contact('voice', phone, 'legislature')
yield p
rows = page.xpath('//tr')
for i, row in enumerate(rows):
if i % 2 == 0:
continue
councillors = row.xpath('./td')
for j, councillor in enumerate(councillors):
name = councillor.text_content()
# rows[i + 1].xpath('.//td//a[contains(@href, "maps")]/text()')[j] # district number
district = rows[i + 1].xpath('.//td/p[1]/text()')[j].replace(' / ', '/')
p = Legislator(name=name, post_id=district, role='Conseiller')
p.add_source(COUNCIL_PAGE)
p.image = councillor.xpath('.//img/@src')[0]
phone = re.findall(r'[0-9]{3}[ -][0-9]{3}-[0-9]{4}', rows[i + 1].xpath('.//td')[j].text_content())[0].replace(' ', '-')
p.add_contact('voice', phone, 'legislature')
yield p
| from pupa.scrape import Scraper
from utils import lxmlize, CanadianLegislator as Legislator
import re
COUNCIL_PAGE = 'http://www.ville.pointe-claire.qc.ca/en/city-hall-administration/your-council/municipal-council.html'
class PointeClairePersonScraper(Scraper):
def get_people(self):
page = lxmlize(COUNCIL_PAGE)
mayor = page.xpath('.//div[@class="item-page clearfix"]//table[1]//p')[1]
name = mayor.xpath('.//strong/text()')[0]
p = Legislator(name=name, post_id='Pointe-Claire', role='Maire')
p.add_source(COUNCIL_PAGE)
phone = re.findall(r'[0-9]{3} [0-9]{3}-[0-9]{4}', mayor.text_content())[0].replace(' ', '-')
p.add_contact('voice', phone, 'legislature')
yield p
rows = page.xpath('//tr')
for i, row in enumerate(rows):
if i % 2 == 0:
continue
councillors = row.xpath('./td')
for j, councillor in enumerate(councillors):
name = councillor.text_content()
# rows[i + 1].xpath('.//td//a[contains(@href, "maps")]/text()')[j] # district number
district = rows[i + 1].xpath('.//td/p[1]/text()')[j].replace(' / ', '/')
p = Legislator(name=name, post_id=district, role='Conseiller')
p.add_source(COUNCIL_PAGE)
p.image = councillor.xpath('.//img/@src')[0]
phone = re.findall(r'[0-9]{3} [0-9]{3}-[0-9]{4}', rows[i + 1].xpath('.//td')[j].text_content())[0].replace(' ', '-')
p.add_contact('voice', phone, 'legislature')
yield p
| Python | 0.000092 |
9a3081c58818ad28e216e9a14fc573c4a392f55f | Add method for getting csv Hours Worked reports for Jobs Board and Payment Plan | invoice/management/commands/ticket_time_csv.py | invoice/management/commands/ticket_time_csv.py | # -*- encoding: utf-8 -*-
import csv
import os
from django.core.management.base import BaseCommand
from invoice.models import TimeRecord
class Command(BaseCommand):
help = "Export ticket time to a CSV file"
def _jobs_board_tickets(self):
return (
732,
746,
747,
748,
749,
750,
751,
752,
753,
754,
755,
756,
757,
758,
759,
906,
976,
)
def _payment_plan_tickets(self):
return (
644,
)
def handle(self, *args, **options):
"""Export ticket time to a CSV file.
Columns:
- ticket number
- user name
- billable - True or False
- date started
- minutes
"""
tickets = self._jobs_board_tickets()
# tickets = self._payment_plan_tickets()
tickets = list(tickets)
tickets.sort()
file_name = '{}_ticket_time.csv'.format(
'_'.join([str(i) for i in tickets])
)
if os.path.exists(file_name):
raise Exception(
"Export file, '{}', already exists. "
"Cannot export time.".format(file_name)
)
with open(file_name, 'w', newline='') as csv_file:
csv_writer = csv.writer(csv_file, dialect='excel-tab')
for tr in TimeRecord.objects.filter(ticket__pk__in=tickets):
csv_writer.writerow([
tr.ticket.pk,
tr.user.username,
tr.billable,
tr.has_invoice_line,
tr.date_started,
tr._timedelta_minutes(),
])
print("Exported time to {}".format(file_name))
| # -*- encoding: utf-8 -*-
import csv
import os
from django.core.management.base import BaseCommand
from invoice.models import TimeRecord
class Command(BaseCommand):
help = "Export ticket time to a CSV file"
def handle(self, *args, **options):
"""Export ticket time to a CSV file.
Columns:
- ticket number
- user name
- billable - True or False
- date started
- minutes
"""
tickets = (
732,
746,
747,
748,
749,
750,
751,
752,
753,
754,
755,
756,
757,
758,
759,
906
)
tickets = list(tickets)
tickets.sort()
file_name = '{}_ticket_time.csv'.format(
'_'.join([str(i) for i in tickets])
)
if os.path.exists(file_name):
raise Exception(
"Export file, '{}', already exists. "
"Cannot export time.".format(file_name)
)
with open(file_name, 'w', newline='') as csv_file:
csv_writer = csv.writer(csv_file, dialect='excel-tab')
for tr in TimeRecord.objects.filter(ticket__pk__in=tickets):
csv_writer.writerow([
tr.ticket.pk,
tr.user.username,
tr.billable,
tr.date_started,
tr._timedelta_minutes(),
])
print("Exported time to {}".format(file_name))
| Python | 0 |
a3db681a63a5908d38ca5fcac4bdd96f5e4fed7e | use typing.TYPE_CHECKING to avoid flake8 failure (#398) | launch/launch/event_handlers/on_execution_complete.py | launch/launch/event_handlers/on_execution_complete.py | # Copyright 2019 Open Source Robotics Foundation, 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.
import collections.abc
from typing import Callable
from typing import cast
from typing import List # noqa
from typing import Optional
from typing import Text
from typing import TYPE_CHECKING
from typing import Union
from ..event import Event
from ..event_handler import EventHandler
from ..events import ExecutionComplete
from ..launch_context import LaunchContext
from ..launch_description_entity import LaunchDescriptionEntity
from ..some_actions_type import SomeActionsType
if TYPE_CHECKING:
from .. import Action # noqa
class OnExecutionComplete(EventHandler):
"""
Convenience class for handling an action completion event.
It may be configured to only handle the completion of a specific action,
or to handle them all.
"""
def __init__(
self,
*,
target_action: Optional['Action'] = None,
on_completion: Union[SomeActionsType, Callable[[int], Optional[SomeActionsType]]],
**kwargs
) -> None:
"""Create an OnExecutionComplete event handler."""
from ..action import Action # noqa
if not isinstance(target_action, (Action, type(None))):
raise ValueError("OnExecutionComplete requires an 'Action' as the target")
super().__init__(
matcher=(
lambda event: (
isinstance(event, ExecutionComplete) and (
target_action is None or
event.action == target_action
)
)
),
entities=None,
**kwargs,
)
self.__target_action = target_action
# TODO(wjwwood) check that it is not only callable, but also a callable that matches
# the correct signature for a handler in this case
self.__on_completion = on_completion
self.__actions_on_completion = [] # type: List[LaunchDescriptionEntity]
if callable(on_completion):
# Then on_completion is a function or lambda, so we can just call it, but
# we don't put anything in self.__actions_on_completion because we cannot
# know what the function will return.
pass
else:
# Otherwise, setup self.__actions_on_completion
if isinstance(on_completion, collections.abc.Iterable):
for entity in on_completion:
if not isinstance(entity, LaunchDescriptionEntity):
raise ValueError(
"expected all items in 'on_completion' iterable to be of type "
"'LaunchDescriptionEntity' but got '{}'".format(type(entity)))
self.__actions_on_completion = list(on_completion)
else:
self.__actions_on_completion = [on_completion]
# Then return it from a lambda and use that as the self.__on_completion callback.
self.__on_completion = lambda event, context: self.__actions_on_completion
def handle(self, event: Event, context: LaunchContext) -> Optional[SomeActionsType]:
"""Handle the given event."""
return self.__on_completion(cast(ExecutionComplete, event), context)
@property
def handler_description(self) -> Text:
"""Return the string description of the handler."""
# TODO(jacobperron): revisit how to describe known actions that are passed in.
# It would be nice if the parent class could output their description
# via the 'entities' property.
if self.__actions_on_completion:
return '<actions>'
return '{}'.format(self.__on_completion)
@property
def matcher_description(self) -> Text:
"""Return the string description of the matcher."""
if self.__target_action is None:
return 'event == ExecutionComplete'
return 'event == ExecutionComplete and event.action == Action({})'.format(
hex(id(self.__target_action))
)
| # Copyright 2019 Open Source Robotics Foundation, 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.
import collections.abc
from typing import Callable
from typing import cast
from typing import List # noqa
from typing import Optional
from typing import Text
from typing import Union
from ..event import Event
from ..event_handler import EventHandler
from ..events import ExecutionComplete
from ..launch_context import LaunchContext
from ..launch_description_entity import LaunchDescriptionEntity
from ..some_actions_type import SomeActionsType
class OnExecutionComplete(EventHandler):
"""
Convenience class for handling an action completion event.
It may be configured to only handle the completion of a specific action,
or to handle them all.
"""
def __init__(
self,
*,
target_action: Optional['Action'] = None,
on_completion: Union[SomeActionsType, Callable[[int], Optional[SomeActionsType]]],
**kwargs
) -> None:
"""Create an OnExecutionComplete event handler."""
from ..action import Action # noqa
if not isinstance(target_action, (Action, type(None))):
raise ValueError("OnExecutionComplete requires an 'Action' as the target")
super().__init__(
matcher=(
lambda event: (
isinstance(event, ExecutionComplete) and (
target_action is None or
event.action == target_action
)
)
),
entities=None,
**kwargs,
)
self.__target_action = target_action
# TODO(wjwwood) check that it is not only callable, but also a callable that matches
# the correct signature for a handler in this case
self.__on_completion = on_completion
self.__actions_on_completion = [] # type: List[LaunchDescriptionEntity]
if callable(on_completion):
# Then on_completion is a function or lambda, so we can just call it, but
# we don't put anything in self.__actions_on_completion because we cannot
# know what the function will return.
pass
else:
# Otherwise, setup self.__actions_on_completion
if isinstance(on_completion, collections.abc.Iterable):
for entity in on_completion:
if not isinstance(entity, LaunchDescriptionEntity):
raise ValueError(
"expected all items in 'on_completion' iterable to be of type "
"'LaunchDescriptionEntity' but got '{}'".format(type(entity)))
self.__actions_on_completion = list(on_completion)
else:
self.__actions_on_completion = [on_completion]
# Then return it from a lambda and use that as the self.__on_completion callback.
self.__on_completion = lambda event, context: self.__actions_on_completion
def handle(self, event: Event, context: LaunchContext) -> Optional[SomeActionsType]:
"""Handle the given event."""
return self.__on_completion(cast(ExecutionComplete, event), context)
@property
def handler_description(self) -> Text:
"""Return the string description of the handler."""
# TODO(jacobperron): revisit how to describe known actions that are passed in.
# It would be nice if the parent class could output their description
# via the 'entities' property.
if self.__actions_on_completion:
return '<actions>'
return '{}'.format(self.__on_completion)
@property
def matcher_description(self) -> Text:
"""Return the string description of the matcher."""
if self.__target_action is None:
return 'event == ExecutionComplete'
return 'event == ExecutionComplete and event.action == Action({})'.format(
hex(id(self.__target_action))
)
| Python | 0 |
8fa0ca6a307f7b23545d297d17f8eb05f037978f | fix one e2e test problem (#459) | test/e2e/utils.py | test/e2e/utils.py | # Copyright 2019 kubeflow.org.
#
# 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 time
from kfserving import KFServingClient
KFServing = KFServingClient(config_file="~/.kube/config")
def wait_for_kfservice_ready(name, namespace='kfserving-ci-e2e-test', Timeout_seconds=600):
for _ in range(round(Timeout_seconds/10)):
time.sleep(10)
kfsvc_status = KFServing.get(name, namespace=namespace)
status = 'Unknown'
for condition in kfsvc_status['status'].get('conditions', {}):
if condition.get('type', '') == 'Ready':
status = condition.get('status', 'Unknown')
if status == 'True':
return
raise RuntimeError("Timeout to start the KFService.")
| # Copyright 2019 kubeflow.org.
#
# 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 time
from kfserving import KFServingClient
KFServing = KFServingClient(config_file="~/.kube/config")
def wait_for_kfservice_ready(name, namespace='kfserving-ci-e2e-test', Timeout_seconds=600):
for _ in range(round(Timeout_seconds/10)):
time.sleep(10)
kfsvc_status = KFServing.get(name, namespace=namespace)
for condition in kfsvc_status['status'].get('conditions', {}):
if condition.get('type', '') == 'Ready':
status = condition.get('status', 'Unknown')
if status == 'True':
return
raise RuntimeError("Timeout to start the KFService.")
| Python | 0.000001 |
0097a4022ec8ab57e76c86bd202dd7a5fad8a076 | Revert to original | cardiffshop/products/admin.py | cardiffshop/products/admin.py | from products.models import Product, Category, ProductImage
from django.conf import settings
from django.contrib import admin
from django.contrib.admin import SimpleListFilter
from suit.admin import SortableTabularInline
class CanBeSoldListFilter(SimpleListFilter):
title = "Can be sold"
parameter_name = "can_be_sold"
def lookups(self, request, model_admin):
return (
("1", "Yes"),
("0", "No")
)
def queryset(self, request, queryset):
value = self.value()
if value == "1":
return queryset.filter(stock_count__gt=0)
if value == "0":
return queryset.filter(stock_count=0)
class ProductImageInline(SortableTabularInline):
model = ProductImage
fields = ("image", "image_preview", "alt_text")
readonly_fields = ("image_preview",)
extra = 0
ordering = ("order",)
def image_preview(self, obj):
if obj.image:
return '<img src="%s" width="100">' % obj.image.url
else:
return '<img src="%s%s" width="100">' % (settings.STATIC_URL, "images/no-image.jpg")
image_preview.allow_tags = True
class ProductAdmin(admin.ModelAdmin):
list_display = ("name", "category", "stock_count", "can_be_sold")
list_filter = ("category", "date_created", CanBeSoldListFilter)
search_fields = ("name", "description", "sku_number", "barcode")
inlines = (ProductImageInline, )
readonly_fields = ("date_created", )
prepopulated_fields = {"slug": ("name",)}
radio_fields = {"campaign": admin.VERTICAL}
fieldsets = (
(None, {
"fields": ("category", "name", "slug", "description"),
"classes": ("suit-tab", "suit-tab-identity",),
}),
(None, {
"fields": (("price", "price_unit"), "campaign", "campaign_end_date", "damaged"),
"classes": ("suit-tab", "suit-tab-price",),
}),
(None, {
"fields": ("barcode", "sku_number", "stock_count", "is_visible", "date_created"),
"classes": ("suit-tab", "suit-tab-stock",),
}),
)
suit_form_tabs = (
('identity', 'Identity'),
('price', 'Price'),
('stock', 'Stock')
)
def can_be_sold(self, obj):
"""
Determines whether the product can be sold or not.
"""
if obj.stock_count > 0:
return True
else:
return False
can_be_sold.boolean = True
admin.site.register(Category)
admin.site.register(Product, ProductAdmin)
admin.site.register(ProductImage)
| from products.models import Product, Category, ProductImage
from django.conf import settings
from django.contrib import admin
from django.contrib.admin import SimpleListFilter
from suit.admin import SortableTabularInline
class CanBeSoldListFilter(SimpleListFilter):
title = "Can be sold"
parameter_name = "can_be_sold"
def lookups(self, request, model_admin):
return (
("1", "Yes"),
("0", "No")
)
def queryset(self, request, queryset):
value = self.value()
if value == "1":
return queryset.filter(stock_count__gt=0).filter(is_visible=True)
if value == "0":
return queryset.exclude(stock_count__gt=0).exclude(is_visible=True)
class ProductImageInline(SortableTabularInline):
model = ProductImage
fields = ("image", "image_preview", "alt_text")
readonly_fields = ("image_preview",)
extra = 0
ordering = ("order",)
def image_preview(self, obj):
if obj.image:
return '<img src="%s" width="100">' % obj.image.url
else:
return '<img src="%s%s" width="100">' % (settings.STATIC_URL, "images/no-image.jpg")
image_preview.allow_tags = True
class ProductAdmin(admin.ModelAdmin):
list_display = ("name", "category", "stock_count", "can_be_sold")
list_filter = ("category", "date_created", CanBeSoldListFilter)
search_fields = ("name", "description", "sku_number", "barcode")
inlines = (ProductImageInline, )
readonly_fields = ("date_created", )
prepopulated_fields = {"slug": ("name",)}
radio_fields = {"campaign": admin.VERTICAL}
fieldsets = (
(None, {
"fields": ("category", "name", "slug", "description"),
"classes": ("suit-tab", "suit-tab-identity",),
}),
(None, {
"fields": (("price", "price_unit"), "campaign", "campaign_end_date", "damaged"),
"classes": ("suit-tab", "suit-tab-price",),
}),
(None, {
"fields": ("barcode", "sku_number", "stock_count", "is_visible", "date_created"),
"classes": ("suit-tab", "suit-tab-stock",),
}),
)
suit_form_tabs = (
('identity', 'Identity'),
('price', 'Price'),
('stock', 'Stock')
)
def can_be_sold(self, obj):
"""
Determines whether the product can be sold or not.
"""
if obj.stock_count > 0 and obj.is_visible:
return True
else:
return False
can_be_sold.boolean = True
admin.site.register(Category)
admin.site.register(Product, ProductAdmin)
admin.site.register(ProductImage)
| Python | 0.999647 |
618c5bd2dee90565a97ab744f620ae8de4a74b91 | refactor plymouth importer to use get_srid() | polling_stations/apps/data_collection/management/commands/import_plymouth.py | polling_stations/apps/data_collection/management/commands/import_plymouth.py | """
Imports Plymouth
"""
from django.contrib.gis.geos import Point, GEOSGeometry
from data_collection.management.commands import BaseKamlImporter
from data_collection.google_geocoding_api_wrapper import (
GoogleGeocodingApiWrapper,
PostcodeNotFoundException
)
class Command(BaseKamlImporter):
"""
Imports the Polling Station data from Plymouth Council
"""
council_id = 'E06000026'
districts_name = 'Plymouth_Polling_Districts.kml'
stations_name = 'Plymouth Polling Stations.csv'
def district_record_to_dict(self, record):
# this kml has no altitude co-ordinates so the data is ok as it stands
geojson = record.geom.geojson
poly = self.clean_poly(GEOSGeometry(geojson, srid=self.get_srid('districts')))
# manually deal with dodgy/missing data
if record['DISTRICT'].value == '' and record['NOTES1'].value == 'EGGBUCKLAND' and record['AREA'].value == 689766:
id = 'HD'
elif record['DISTRICT'].value == '' and record['NOTES1'].value == 'EGGBUCKLAND' and record['AREA'].value == 594904:
id = 'HF'
elif record['DISTRICT'].value == '' and record['NOTES1'].value == '':
# Drake's Island ( https://en.wikipedia.org/wiki/Drake's_Island )
# seems to have a polling district but no associated station so can't work out the code.
# We'll just give it a name:
id = "Drake's Island"
else:
id = record['DISTRICT'].value
return {
'internal_council_id': id,
'name' : id,
'area' : poly
}
def station_record_to_dict(self, record):
location = Point(float(record.east), float(record.north), srid=self.get_srid())
address = "\n".join([record.addressl1, record.addressl2, record.addressl3])
if address[-1:] == '\n':
address = address[:-1]
# attempt to attach postcodes
gwrapper = GoogleGeocodingApiWrapper(address + ", Plymouth, UK")
try:
postcode = gwrapper.address_to_postcode()
except PostcodeNotFoundException:
postcode = ''
return {
'internal_council_id': record.statno,
'postcode': postcode,
'address': address,
'location': location
}
| """
Imports Plymouth
"""
from django.contrib.gis.geos import Point, GEOSGeometry
from data_collection.management.commands import BaseKamlImporter
from data_collection.google_geocoding_api_wrapper import (
GoogleGeocodingApiWrapper,
PostcodeNotFoundException
)
class Command(BaseKamlImporter):
"""
Imports the Polling Station data from Plymouth Council
"""
council_id = 'E06000026'
districts_name = 'Plymouth_Polling_Districts.kml'
stations_name = 'Plymouth Polling Stations.csv'
def district_record_to_dict(self, record):
# this kml has no altitude co-ordinates so the data is ok as it stands
geojson = record.geom.geojson
# The SRID for the KML is 4326 but the CSV is 2770 so we
# set it each time we create the polygon.
# We could probably do with a more elegant way of doing
# this longer term.
self._srid = self.srid
self.srid = 4326
poly = self.clean_poly(GEOSGeometry(geojson, srid=self.srid))
self.srid = self._srid
# manually deal with dodgy/missing data
if record['DISTRICT'].value == '' and record['NOTES1'].value == 'EGGBUCKLAND' and record['AREA'].value == 689766:
id = 'HD'
elif record['DISTRICT'].value == '' and record['NOTES1'].value == 'EGGBUCKLAND' and record['AREA'].value == 594904:
id = 'HF'
elif record['DISTRICT'].value == '' and record['NOTES1'].value == '':
# Drake's Island ( https://en.wikipedia.org/wiki/Drake's_Island )
# seems to have a polling district but no associated station so can't work out the code.
# We'll just give it a name:
id = "Drake's Island"
else:
id = record['DISTRICT'].value
return {
'internal_council_id': id,
'name' : id,
'area' : poly
}
def station_record_to_dict(self, record):
location = Point(float(record.east), float(record.north), srid=self.srid)
address = "\n".join([record.addressl1, record.addressl2, record.addressl3])
if address[-1:] == '\n':
address = address[:-1]
# attempt to attach postcodes
gwrapper = GoogleGeocodingApiWrapper(address + ", Plymouth, UK")
try:
postcode = gwrapper.address_to_postcode()
except PostcodeNotFoundException:
postcode = ''
return {
'internal_council_id': record.statno,
'postcode': postcode,
'address': address,
'location': location
}
| Python | 0 |
49be60d27b5d5ce40c20847f79a8dd09f580a830 | Update _var_dump.py | var_dump/_var_dump.py | var_dump/_var_dump.py | from __future__ import print_function
import sys
try:
from types import NoneType
except:
NoneType = type(None)
if sys.version_info > (3,):
long = int
unicode = str
__author__ = "Shamim Hasnath"
__copyright__ = "Copyright 2013, Shamim Hasnath"
__license__ = "BSD License"
__version__ = "1.0.1"
TAB_SIZE = 4
def display(o, space, num, key, typ, proret):
st = ""
l = []
if key:
if typ is dict:
st += " " * space + "['%s'] => "
else:
st += " " * space + "%s => "
l.append(key)
elif space > 0:
st += " " * space + "[%d] => "
l.append(num)
else: # at the very start
st += "#%d "
l.append(num)
if type(o) in (tuple, list, dict, int, str, float, long, bool, NoneType, unicode):
st += "%s(%s) "
l.append(type(o).__name__)
if type(o) in (int, float, long, bool, NoneType):
l.append(o)
else:
l.append(len(o))
if type(o) in (str, unicode):
st += '"%s"'
l.append(o)
elif isinstance(o, object):
st += "object(%s) (%d)"
l.append(o.__class__.__name__)
l.append(len(o.__dict__))
if proret:
print(st % tuple(l))
return st % tuple(l)
def dump(o, space, num, key, typ, proret):
r = '';
if type(o) in (str, int, float, long, bool, NoneType, unicode):
r += display(o, space, num, key, typ, proret)
elif isinstance(o, object):
r += display(o, space, num, key, typ, proret)
num = 0
if type(o) in (tuple, list, dict):
typ = type(o) # type of the container of str, int, long, float etc
elif isinstance(o, object):
o = o.__dict__
typ = object
for i in o:
space += TAB_SIZE
if type(o) is dict:
r += dump(o[i], space, num, i, typ, proret)
else:
r += dump(i, space, num, '', typ, proret)
num += 1
space -= TAB_SIZE
return r
def var_dump(*obs):
"""
shows structured information of a object, list, tuple etc
"""
i = 0
for x in obs:
dump(x, 0, i, '', object, True)
i += 1
def var_export(*obs):
"""
returns output as as string
"""
r = ''
i = 0
for x in obs:
r += dump(x, 0, i, '', object, False)
i += 1
return r
| from __future__ import print_function
import sys
try:
from types import NoneType
except:
NoneType = type(None)
if sys.version_info > (3,):
long = int
unicode = str
__author__ = "Shamim Hasnath"
__copyright__ = "Copyright 2013, Shamim Hasnath"
__license__ = "BSD License"
__version__ = "1.0.1"
TAB_SIZE = 4
def display(o, space, num, key, typ, display):
st = ""
l = []
if key:
if typ is dict:
st += " " * space + "['%s'] => "
else:
st += " " * space + "%s => "
l.append(key)
elif space > 0:
st += " " * space + "[%d] => "
l.append(num)
else: # at the very start
st += "#%d "
l.append(num)
if type(o) in (tuple, list, dict, int, str, float, long, bool, NoneType, unicode):
st += "%s(%s) "
l.append(type(o).__name__)
if type(o) in (int, float, long, bool, NoneType):
l.append(o)
else:
l.append(len(o))
if type(o) in (str, unicode):
st += '"%s"'
l.append(o)
elif isinstance(o, object):
st += "object(%s) (%d)"
l.append(o.__class__.__name__)
l.append(len(o.__dict__))
if display:
print(st % tuple(l))
else:
return st % tuple(l)
def dump(o, space, num, key, typ, proret):
if type(o) in (str, int, float, long, bool, NoneType, unicode):
display(o, space, num, key, typ, proret)
elif isinstance(o, object):
display(o, space, num, key, typ, proret)
num = 0
if type(o) in (tuple, list, dict):
typ = type(o) # type of the container of str, int, long, float etc
elif isinstance(o, object):
o = o.__dict__
typ = object
for i in o:
space += TAB_SIZE
if type(o) is dict:
dump(o[i], space, num, i, typ, proret)
else:
dump(i, space, num, '', typ, proret)
num += 1
space -= TAB_SIZE
def var_dump(*obs):
"""
shows structured information of a object, list, tuple etc
"""
i = 0
for x in obs:
dump(x, 0, i, '', object, True)
i += 1
def var_export(*obs):
"""
returns output as as string
"""
r = ''
i = 0
for x in obs:
r += dump(x, 0, i, '', object, False)
i += 1
return r
| Python | 0.000005 |
206696e82f3e5be4a64e60abdb59ca51d2b1461e | Add a test for rgb+mp to verify that it continues to work. | pysc2/tests/multi_player_env_test.py | pysc2/tests/multi_player_env_test.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test that the multiplayer environment works."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
from future.builtins import range # pylint: disable=redefined-builtin
from pysc2.agents import random_agent
from pysc2.env import run_loop
from pysc2.env import sc2_env
from pysc2.tests import utils
class TestMultiplayerEnv(utils.TestCase):
def test_multi_player_env_features(self):
steps = 100
step_mul = 16
players = 2
with sc2_env.SC2Env(
map_name="Simple64",
players=[sc2_env.Agent(sc2_env.Race.zerg),
sc2_env.Agent(sc2_env.Race.terran)],
feature_screen_size=84,
feature_minimap_size=64,
step_mul=step_mul,
game_steps_per_episode=steps * step_mul // 2) as env:
agents = [random_agent.RandomAgent() for _ in range(players)]
run_loop.run_loop(agents, env, steps)
def test_multi_player_env_rgb(self):
steps = 100
step_mul = 16
players = 2
with sc2_env.SC2Env(
map_name="Simple64",
players=[sc2_env.Agent(sc2_env.Race.zerg),
sc2_env.Agent(sc2_env.Race.terran)],
rgb_screen_size=84,
rgb_minimap_size=64,
step_mul=step_mul,
game_steps_per_episode=steps * step_mul // 2) as env:
agents = [random_agent.RandomAgent() for _ in range(players)]
run_loop.run_loop(agents, env, steps)
if __name__ == "__main__":
absltest.main()
| #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test that the multiplayer environment works."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
from future.builtins import range # pylint: disable=redefined-builtin
from pysc2.agents import random_agent
from pysc2.env import run_loop
from pysc2.env import sc2_env
from pysc2.tests import utils
class TestMultiplayerEnv(utils.TestCase):
def test_multi_player_env(self):
steps = 100
step_mul = 16
players = 2
with sc2_env.SC2Env(
map_name="Simple64",
players=[sc2_env.Agent(sc2_env.Race.zerg),
sc2_env.Agent(sc2_env.Race.terran)],
feature_screen_size=84,
feature_minimap_size=64,
step_mul=step_mul,
game_steps_per_episode=steps * step_mul // 2) as env:
agents = [random_agent.RandomAgent() for _ in range(players)]
run_loop.run_loop(agents, env, steps)
if __name__ == "__main__":
absltest.main()
| Python | 0 |
48e3dab4ce044554b0ff606dea340ff8b6e5d928 | Update __init__.py | edbo_connector/__init__.py | edbo_connector/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
edbo_connector
Author: Eldar Aliiev
Email: e.aliiev@vnmu.edu.ua
"""
from .client import EDBOWebApiClient
__name__ = 'python-edbo-connector'
__author__ = 'Eldar Aliiev'
__copyright__ = 'Copyright 2018, National Pirogov Memorial Medical University, Vinnytsya'
__credits__ = ['Eldar Aliiev']
__license__ = 'MIT'
__version__ = '1.0.4-13'
__maintainer__ = 'Eldar Aliiev'
__email__ = 'e.aliiev@vnmu.edu.ua'
__status__ = 'Production'
__all__ = ['EDBOWebApiClient']
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
edbo_connector
Author: Eldar Aliiev
Email: e.aliiev@vnmu.edu.ua
"""
from .client import EDBOWebApiClient
__name__ = 'python-edbo-connector'
__author__ = 'Eldar Aliiev'
__copyright__ = 'Copyright 2018, National Pirogov Memorial Medical University, Vinnytsya'
__credits__ = ['Eldar Aliiev']
__license__ = 'MIT'
__version__ = '1.0.4-12'
__maintainer__ = 'Eldar Aliiev'
__email__ = 'e.aliiev@vnmu.edu.ua'
__status__ = 'Production'
__all__ = ['EDBOWebApiClient']
| Python | 0.000072 |
949934ea7a34fcd71f65118b741a51a28e815e5d | update from trunk r9256 | pywikibot/families/wowwiki_family.py | pywikibot/families/wowwiki_family.py | # -*- coding: utf-8 -*-
__version__ = '$Id$'
from pywikibot import family
class Family(family.Family):
def __init__(self):
family.Family.__init__(self)
self.name = 'wowwiki'
self.langs = {
'cs': 'cs.wow.wikia.com',
'da': 'da.wowwiki.com',
'de': 'de.wow.wikia.com',
'el': 'el.wow.wikia.com',
'en': 'www.wowwiki.com',
'es': 'es.wow.wikia.com',
'fa': 'fa.wow.wikia.com',
'fi': 'fi.wow.wikia.com',
'fr': 'fr.wowwiki.com',
'he': 'he.wow.wikia.com',
'hr': 'hr.wow.wikia.com',
'hu': 'hu.wow.wikia.com',
'is': 'is.wow.wikia.com',
'it': 'it.wow.wikia.com',
'ja': 'ja.wow.wikia.com',
'ko': 'ko.wow.wikia.com',
'lt': 'lt.wow.wikia.com',
'lv': 'lv.wow.wikia.com',
'nl': 'nl.wow.wikia.com',
'no': 'no.wowwiki.com',
'pl': 'pl.wow.wikia.com',
'pt': 'pt.wow.wikia.com',
'pt-br': 'pt-br.wow.wikia.com',
'ro': 'ro.wow.wikia.com',
'ru': 'ru.wow.wikia.com',
'sk': 'sk.wow.wikia.com',
'sr': 'sr.wow.wikia.com',
'sv': 'sv.warcraft.wikia.com',
'tr': 'tr.wow.wikia.com',
'zh-tw': 'zh-tw.wow.wikia.com',
'zh': 'zh.wow.wikia.com'
}
self.content_id = "article"
self.disambiguationTemplates['en'] = ['disambig', 'disambig/quest',
'disambig/quest2',
'disambig/achievement2']
self.disambcatname['en'] = "Disambiguations"
# Wikia's default CategorySelect extension always puts categories last
self.categories_last = ['cs', 'da', 'de', 'el', 'en', 'es', 'fa', 'fi', 'fr', 'he', 'hr', 'hu', 'is', 'it', 'ja', 'ko', 'lt', 'lv', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru', 'sk', 'sr', 'sv', 'tr', 'zh-tw', 'zh']
def scriptpath(self, code):
return ''
def version(self, code):
return '1.16.4'
| # -*- coding: utf-8 -*-
__version__ = '$Id$'
from pywikibot import family
class Family(family.Family):
def __init__(self):
family.Family.__init__(self)
self.name = 'wowwiki'
self.langs = {
'cs': 'cs.wow.wikia.com',
'da': 'da.wowwiki.com',
'de': 'de.wow.wikia.com',
'el': 'el.wow.wikia.com',
'en': 'www.wowwiki.com',
'es': 'es.wow.wikia.com',
'fa': 'fa.wow.wikia.com',
'fi': 'fi.wow.wikia.com',
'fr': 'fr.wowwiki.com',
'he': 'he.wow.wikia.com',
'hr': 'hr.wow.wikia.com',
'hu': 'hu.wow.wikia.com',
'is': 'is.wow.wikia.com',
'it': 'it.wow.wikia.com',
'ja': 'ja.wow.wikia.com',
'ko': 'ko.wow.wikia.com',
'lt': 'lt.wow.wikia.com',
'lv': 'lv.wow.wikia.com',
'nl': 'nl.wow.wikia.com',
'no': 'no.wow.wikia.com',
'pl': 'pl.wow.wikia.com',
'pt': 'pt.wow.wikia.com',
'pt-br': 'pt-br.wow.wikia.com',
'ro': 'ro.wow.wikia.com',
'ru': 'ru.wow.wikia.com',
'sk': 'sk.wow.wikia.com',
'sr': 'sr.wow.wikia.com',
'sv': 'sv.warcraft.wikia.com',
'tr': 'tr.wow.wikia.com',
'zh-tw': 'zh-tw.wow.wikia.com',
'zh': 'zh.wow.wikia.com'
}
self.content_id = "article"
self.disambiguationTemplates['en'] = ['disambig', 'disambig/quest',
'disambig/quest2',
'disambig/achievement2']
self.disambcatname['en'] = "Disambiguations"
def scriptpath(self, code):
return ''
def version(self, code):
return '1.16.2'
| Python | 0 |
c95c222384c2c0d887d435017196c9af4137d1b2 | set numba parallel option | hpat/__init__.py | hpat/__init__.py | from __future__ import print_function, division, absolute_import
import numba
from numba import *
from .compiler import add_hpat_stages
set_user_pipeline_func(add_hpat_stages)
del add_hpat_stages
def jit(signature_or_function=None, **options):
# set nopython by default
if 'nopython' not in options:
options['nopython'] = True
options['parallel'] = True
return numba.jit(signature_or_function, **options)
| from __future__ import print_function, division, absolute_import
import numba
from numba import *
from .compiler import add_hpat_stages
set_user_pipeline_func(add_hpat_stages)
del add_hpat_stages
def jit(signature_or_function=None, **options):
# set nopython by default
if 'nopython' not in options:
options['nopython'] = True
return numba.jit(signature_or_function, **options)
| Python | 0.000002 |
80d3fe7d2c69fd960a5b585d60085f33e109e455 | solution found text incorrect | simbad/command_line/simbad_lattice.py | simbad/command_line/simbad_lattice.py | #!/usr/bin/env python
__author__ = "Felix Simkovic & Adam Simpkin"
__date__ = "06 Mar 2017"
__version__ = "0.1"
import argparse
import os
import platform
import sys
import time
import simbad.command_line
import simbad.util.exit_util
import simbad.util.simbad_util
import simbad.version
__version__ = simbad.version.__version__
def lattice_argparse():
"""Create the argparse options"""
p = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
simbad.command_line._argparse_core_options(p)
simbad.command_line._argparse_lattice_options(p)
simbad.command_line._argparse_mtz_options(p)
simbad.command_line._argparse_mr_options(p)
p.add_argument('mtz', help="The path to the input mtz file")
return p.parse_args()
def main():
"""Main function to run SIMBAD's lattice search"""
args = lattice_argparse()
if args.work_dir and os.path.isdir(args.work_dir):
raise ValueError("Named working directory exists, please rename or remove")
elif args.work_dir:
os.mkdir(args.work_dir)
args.work_dir = args.work_dir
elif args.run_dir and os.path.isdir(args.run_dir):
args.work_dir = simbad.command_line.make_workdir(args.run_dir, ccp4_jobid=args.ccp4_jobid)
elif args.run_dir:
os.mkdir(args.run_dir)
args.work_dir = simbad.command_line.make_workdir(args.run_dir, ccp4_jobid=args.ccp4_jobid)
else:
raise RuntimeError("Not entirely sure what has happened here but I should never get to here")
# Logger setup
debug_log = os.path.join(args.work_dir, 'debug.log')
logger = simbad.command_line.setup_logging(logfile=debug_log)
# Check the CCP4 installation
ccp4_root = simbad.command_line.setup_ccp4()
ccp4_version = simbad.util.simbad_util.ccp4_version()
# Print some fancy info
logger.info(simbad.command_line.header)
logger.info("SIMBAD version: %s", __version__)
logger.info("Running with CCP4 version: %s from directory: %s", ccp4_version, ccp4_root)
logger.info("Running on host: %s", platform.node())
logger.info("Running on platform: %s", platform.platform())
logger.info("Job started at: %s", time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime()))
logger.info("Invoked with command-line:\n%s\n", " ".join(map(str, sys.argv)))
logger.info("Running in directory: %s\n", args.work_dir)
# Take the start time
time_start = time.time()
# Perform the contaminante search
solution_found = simbad.command_line._simbad_lattice_search(args)
if solution_found:
logger.info("Lucky you! SIMBAD worked its charm and found a lattice match for you.")
else:
logger.info("No results found - lattice search was unsuccessful")
# Calculate and display the runtime in hours
days, hours, mins, secs = simbad.command_line.calculate_runtime(time_start, time.time())
logger.info("All processing completed in %d days, %d hours, %d minutes, %d and seconds", days, hours, mins, secs)
if __name__ == "__main__":
try:
main()
except Exception as e:
msg = "Error running main SIMBAD program: {0}".format(e.message)
simbad.util.exit_util.exit_error(msg, sys.exc_info()[2])
| #!/usr/bin/env python
__author__ = "Felix Simkovic & Adam Simpkin"
__date__ = "06 Mar 2017"
__version__ = "0.1"
import argparse
import os
import platform
import sys
import time
import simbad.command_line
import simbad.util.exit_util
import simbad.util.simbad_util
import simbad.version
__version__ = simbad.version.__version__
def lattice_argparse():
"""Create the argparse options"""
p = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
simbad.command_line._argparse_core_options(p)
simbad.command_line._argparse_lattice_options(p)
simbad.command_line._argparse_mtz_options(p)
simbad.command_line._argparse_mr_options(p)
p.add_argument('mtz', help="The path to the input mtz file")
return p.parse_args()
def main():
"""Main function to run SIMBAD's lattice search"""
args = lattice_argparse()
if args.work_dir and os.path.isdir(args.work_dir):
raise ValueError("Named working directory exists, please rename or remove")
elif args.work_dir:
os.mkdir(args.work_dir)
args.work_dir = args.work_dir
elif args.run_dir and os.path.isdir(args.run_dir):
args.work_dir = simbad.command_line.make_workdir(args.run_dir, ccp4_jobid=args.ccp4_jobid)
elif args.run_dir:
os.mkdir(args.run_dir)
args.work_dir = simbad.command_line.make_workdir(args.run_dir, ccp4_jobid=args.ccp4_jobid)
else:
raise RuntimeError("Not entirely sure what has happened here but I should never get to here")
# Logger setup
debug_log = os.path.join(args.work_dir, 'debug.log')
logger = simbad.command_line.setup_logging(logfile=debug_log)
# Check the CCP4 installation
ccp4_root = simbad.command_line.setup_ccp4()
ccp4_version = simbad.util.simbad_util.ccp4_version()
# Print some fancy info
logger.info(simbad.command_line.header)
logger.info("SIMBAD version: %s", __version__)
logger.info("Running with CCP4 version: %s from directory: %s", ccp4_version, ccp4_root)
logger.info("Running on host: %s", platform.node())
logger.info("Running on platform: %s", platform.platform())
logger.info("Job started at: %s", time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime()))
logger.info("Invoked with command-line:\n%s\n", " ".join(map(str, sys.argv)))
logger.info("Running in directory: %s\n", args.work_dir)
# Take the start time
time_start = time.time()
# Perform the contaminante search
solution_found = simbad.command_line._simbad_lattice_search(args)
if solution_found:
logger.info("Check you out, crystallizing contaminants! But don't worry, SIMBAD figured it out and found a solution.")
else:
logger.info("No results found - lattice search was unsuccessful")
# Calculate and display the runtime in hours
days, hours, mins, secs = simbad.command_line.calculate_runtime(time_start, time.time())
logger.info("All processing completed in %d days, %d hours, %d minutes, %d and seconds", days, hours, mins, secs)
if __name__ == "__main__":
try:
main()
except Exception as e:
msg = "Error running main SIMBAD program: {0}".format(e.message)
simbad.util.exit_util.exit_error(msg, sys.exc_info()[2])
| Python | 0.999998 |
77651861fc5a27d1d62293e3bc66d62ae193221d | add tolerance option to F.sqrt | tests/chainer_tests/functions_tests/math_tests/test_sqrt.py | tests/chainer_tests/functions_tests/math_tests/test_sqrt.py | import unittest
import numpy
import chainer.functions as F
from chainer import testing
# sqrt
def make_data(shape, dtype):
x = numpy.random.uniform(0.1, 5, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
ggx = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy, ggx
@testing.unary_math_function_unittest(
F.sqrt,
make_data=make_data,
backward_options={'atol': 1e-3, 'rtol': 1e-3},
)
class TestSqrt(unittest.TestCase):
pass
# rsqrt
def rsqrt(x):
return numpy.reciprocal(numpy.sqrt(x))
class TestRsqrt(unittest.TestCase):
def test_rsqrt(self):
x = numpy.random.uniform(0.1, 5, (3, 2)).astype(numpy.float32)
testing.assert_allclose(F.rsqrt(x).data, rsqrt(x))
testing.run_module(__name__, __file__)
| import unittest
import numpy
import chainer.functions as F
from chainer import testing
# sqrt
def make_data(shape, dtype):
x = numpy.random.uniform(0.1, 5, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
ggx = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy, ggx
@testing.unary_math_function_unittest(F.sqrt, make_data=make_data)
class TestSqrt(unittest.TestCase):
pass
# rsqrt
def rsqrt(x):
return numpy.reciprocal(numpy.sqrt(x))
class TestRsqrt(unittest.TestCase):
def test_rsqrt(self):
x = numpy.random.uniform(0.1, 5, (3, 2)).astype(numpy.float32)
testing.assert_allclose(F.rsqrt(x).data, rsqrt(x))
testing.run_module(__name__, __file__)
| Python | 0.000003 |
cc17390eada091da34fed92ee7e2090adc1fa87e | Fix for `plot_field` function failing on non-square grids #666 | examples/cfd/tools.py | examples/cfd/tools.py | from mpl_toolkits.mplot3d import Axes3D # noqa
import numpy as np
from matplotlib import pyplot, cm
def plot_field(field, xmax=2., ymax=2., zmax=None, view=None, linewidth=0):
"""Utility plotting routine for 2D data
:param field: Numpy array with field data to plot
:param xmax: (Optional) Length of the x-axis
:param ymax: (Optional) Length of the y-axis
:param view: (Optional) View point to intialise
"""
x_coord = np.linspace(0, xmax, field.shape[0])
y_coord = np.linspace(0, ymax, field.shape[1])
fig = pyplot.figure(figsize=(11, 7), dpi=100)
ax = fig.gca(projection='3d')
X, Y = np.meshgrid(x_coord, y_coord, indexing='ij')
ax.plot_surface(X, Y, field[:], cmap=cm.viridis, rstride=1, cstride=1,
linewidth=linewidth, antialiased=False)
# Enforce axis measures and set view if given
ax.set_xlim(0., xmax)
ax.set_ylim(0., ymax)
if zmax is not None:
ax.set_zlim(1., zmax)
if view is not None:
ax.view_init(*view)
# Label axis
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
pyplot.show()
def init_hat(field, dx, dy, value=2., bgvalue=1.):
"""Set "hat function" initial condition on an array:
u(.5<=x<=1 && .5<=y<=1 ) is 2
:param field: Numpy array with field data to plot
:param dx: Spacing in the x-dimension
:param dy: Spacing in the y-dimension
:param value: Value of the top part of the function, default=2.
:param bgvalue: Background value for the bottom of the function, default=1.
"""
field[:] = bgvalue
field[int(.5 / dx):int(1 / dx + 1), int(.5 / dy):int(1 / dy + 1)] = value
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
def fin_bump(x):
if x <= 0 or x >= 1:
return 0
else:
return 100*np.exp(-1./(x-np.power(x, 2.)))
def init_smooth(field, dx, dy):
nx, ny = field.shape
for ix in range(nx):
for iy in range(ny):
x = ix * dx
y = iy * dy
field[ix, iy] = fin_bump(x/1.5) * fin_bump(y/1.5) + 1.
| from mpl_toolkits.mplot3d import Axes3D # noqa
import numpy as np
from matplotlib import pyplot, cm
def plot_field(field, xmax=2., ymax=2., zmax=None, view=None, linewidth=0):
"""Utility plotting routine for 2D data
:param field: Numpy array with field data to plot
:param xmax: (Optional) Length of the x-axis
:param ymax: (Optional) Length of the y-axis
:param view: (Optional) View point to intialise
"""
x_coord = np.linspace(0, xmax, field.shape[0])
y_coord = np.linspace(0, ymax, field.shape[1])
fig = pyplot.figure(figsize=(11, 7), dpi=100)
ax = fig.gca(projection='3d')
X, Y = np.meshgrid(x_coord, y_coord)
ax.plot_surface(X, Y, field[:], cmap=cm.viridis, rstride=1, cstride=1,
linewidth=linewidth, antialiased=False)
# Enforce axis measures and set view if given
ax.set_xlim(0., xmax)
ax.set_ylim(0., ymax)
if zmax is not None:
ax.set_zlim(1., zmax)
if view is not None:
ax.view_init(*view)
# Label axis
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
pyplot.show()
def init_hat(field, dx, dy, value=2., bgvalue=1.):
"""Set "hat function" initial condition on an array:
u(.5<=x<=1 && .5<=y<=1 ) is 2
:param field: Numpy array with field data to plot
:param dx: Spacing in the x-dimension
:param dy: Spacing in the y-dimension
:param value: Value of the top part of the function, default=2.
:param bgvalue: Background value for the bottom of the function, default=1.
"""
field[:] = bgvalue
field[int(.5 / dx):int(1 / dx + 1), int(.5 / dy):int(1 / dy + 1)] = value
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
def fin_bump(x):
if x <= 0 or x >= 1:
return 0
else:
return 100*np.exp(-1./(x-np.power(x, 2.)))
def init_smooth(field, dx, dy):
nx, ny = field.shape
for ix in range(nx):
for iy in range(ny):
x = ix * dx
y = iy * dy
field[ix, iy] = fin_bump(x/1.5) * fin_bump(y/1.5) + 1.
| Python | 0 |
173317003a59afb639e6f4f5d5eca41a1f390979 | Revise q05 to successfully use partial derivatives of u and v for gradient descent of E (error). | hw05/hw05ex05.py | hw05/hw05ex05.py | # dE/du (u e^v - 2v e^(-u))^2 = 2 (u e^v - 2v e^(-u))(e^v + 2v e^(-u))
#from decimal import Decimal
from math import sqrt, exp, fabs #natural exponent, e**x. and absolute value
def calcEwrtu(u,v):
'''
Given u and v, the hypothesis and the target function,
return the partial deriv w.r.t. u for gradient descent of the error.
'''
return 2 * ( u*exp(v) - 2*v*exp(-u) ) * ( exp(v) + 2*v*exp(-u) )
def calcEwrtv(u,v):
'''
Given u and v, the hypothesis and the target function,
return the partial deriv w.r.t. v for gradient descent of the error.
'''
return 2 * ( u * exp(v) - 2*v*exp(-u) ) * ( u*exp(v) - 2*exp(-u))
def calcE(u,v):
return ( u*exp(v) - 2.*v*exp(-u) )**2
def q05():
i = 0
eta = 0.1 # u"\u03B7"
u = 1.
v = 1.
#E = float(10^(-14))
#E = 10^(-14)
#E = Decimal(0.0000000000001)
#E = 0.0000000000001
E_threshold = 10e-14
E = 99999.
while True:
if E < E_threshold:
print E, '<', E_threshold, ' in', i, 'iterations'
break
else:
dE_du = calcEwrtu(u,v)
dE_dv = calcEwrtv(u,v)
u = u - eta * dE_du
v = v - eta * dE_dv
E = calcE(u,v)
#print 'E:', E, 'u:', u, 'v:', v, 'iter:', i
i+=1
return u, v, E, i
print q05()
| # dE/du (u e^v - 2v e^(-u))^2 = 2 (u e^v - 2v e^(-u))(e^v + 2v e^(-u))
#from decimal import Decimal
from math import exp #natural exponent, e**x
def calcE(u,v):
return 2 * ( u*exp(v) - 2*v*exp(-u) ) * ( exp(v) + 2*v*exp(-u) )
i = 0
eta = 0.1 # u"\u03B7"
#E = float(10^(-14))
#E = 10^(-14)
#E = Decimal(0.0000000000001)
#E = 0.0000000000001
E_threshold = 10e-14
print calcE(1,1)
'''
while True:
if E < E_threshold:
print E, '<', E_threshold, ' in', i, 'iterations'
break
else:
''' | Python | 0 |
61609c6b1a93316c1b8a5e512ed310a38d6c772b | Add gss_mnist description | examples/gss_mnist.py | examples/gss_mnist.py | import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss
from torch.optim import SGD
from avalanche.benchmarks import Experience
from avalanche.benchmarks.classic import SplitMNIST
from avalanche.benchmarks.generators.benchmark_generators import \
data_incremental_benchmark
from avalanche.benchmarks.utils import AvalancheSubset
from avalanche.evaluation.metrics import accuracy_metrics, loss_metrics
from avalanche.logging import InteractiveLogger
from avalanche.training.plugins import EvaluationPlugin
from avalanche.training.strategies import GSS_greedy
"""
This example the strategy GSS_greedy on Split MNIST.
The final accuracy is around 82.6% (std 2.9)
as stated in the original paper: https://arxiv.org/abs/1903.08671
"""
class FlattenP(nn.Module):
'''A nn-module to flatten a multi-dimensional tensor to 2-dim tensor.'''
def forward(self, x):
batch_size = x.size(0) # first dimenstion should be batch-dimension.
return x.view(batch_size, -1)
def __repr__(self):
tmpstr = self.__class__.__name__ + '()'
return tmpstr
class MLP(nn.Module):
def __init__(self, sizes, bias=True):
super(MLP, self).__init__()
layers = []
for i in range(0, len(sizes) - 1):
if i < (len(sizes)-2):
layers.append(nn.Linear(sizes[i], sizes[i + 1]))
layers.append(nn.ReLU())
else:
layers.append(nn.Linear(sizes[i], sizes[i + 1], bias=bias))
self.net = nn.Sequential(FlattenP(), *layers)
def forward(self, x):
return self.net(x)
def shrinking_experience_size_split_strategy(
experience: Experience):
experience_size = 1000
exp_dataset = experience.dataset
exp_indices = list(range(len(exp_dataset)))
result_datasets = []
exp_indices = \
torch.as_tensor(exp_indices)[
torch.randperm(len(exp_indices))
].tolist()
result_datasets.append(AvalancheSubset(
exp_dataset, indices=exp_indices[0:experience_size]))
return result_datasets
def setup_mnist():
scenario = data_incremental_benchmark(SplitMNIST(
n_experiences=5, seed=1), experience_size=0, custom_split_strategy=shrinking_experience_size_split_strategy)
n_inputs = 784
nh = 100
nl = 2
n_outputs = 10
model = MLP([n_inputs] + [nh] * nl + [n_outputs])
return model, scenario
if __name__ == "__main__":
dev = "cuda:0"
device = torch.device(dev)
#_______________________________________Model and scenario
model, scenario = setup_mnist()
eval_plugin = EvaluationPlugin(
accuracy_metrics(epoch=True, experience=True, stream=True),
loss_metrics(stream=True), loggers=[InteractiveLogger()])
# _____________________________Strategy
optimizer = SGD(model.parameters(), lr=0.05)
strategy = GSS_greedy(model, optimizer, criterion=CrossEntropyLoss(), train_mb_size=10, mem_strength=10, input_size=[
1, 28, 28], train_epochs=3, eval_mb_size=10, mem_size=300, evaluator=eval_plugin)
# ___________________________________________train
for experience in scenario.train_stream:
print(">Experience ", experience.current_experience)
res = strategy.train(experience)
res = strategy.eval(scenario.test_stream)
| import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss
from torch.optim import SGD
from avalanche.benchmarks import Experience
from avalanche.benchmarks.classic import SplitMNIST
from avalanche.benchmarks.generators.benchmark_generators import \
data_incremental_benchmark
from avalanche.benchmarks.utils import AvalancheSubset
from avalanche.evaluation.metrics import accuracy_metrics, loss_metrics
from avalanche.logging import InteractiveLogger
from avalanche.training.plugins import EvaluationPlugin
from avalanche.training.strategies import GSS_greedy
class FlattenP(nn.Module):
'''A nn-module to flatten a multi-dimensional tensor to 2-dim tensor.'''
def forward(self, x):
batch_size = x.size(0) # first dimenstion should be batch-dimension.
return x.view(batch_size, -1)
def __repr__(self):
tmpstr = self.__class__.__name__ + '()'
return tmpstr
class MLP(nn.Module):
def __init__(self, sizes, bias=True):
super(MLP, self).__init__()
layers = []
for i in range(0, len(sizes) - 1):
if i < (len(sizes)-2):
layers.append(nn.Linear(sizes[i], sizes[i + 1]))
layers.append(nn.ReLU())
else:
layers.append(nn.Linear(sizes[i], sizes[i + 1], bias=bias))
self.net = nn.Sequential(FlattenP(), *layers)
def forward(self, x):
return self.net(x)
def shrinking_experience_size_split_strategy(
experience: Experience):
experience_size = 1000
exp_dataset = experience.dataset
exp_indices = list(range(len(exp_dataset)))
result_datasets = []
exp_indices = \
torch.as_tensor(exp_indices)[
torch.randperm(len(exp_indices))
].tolist()
result_datasets.append(AvalancheSubset(
exp_dataset, indices=exp_indices[0:experience_size]))
return result_datasets
def setup_mnist():
scenario = data_incremental_benchmark(SplitMNIST(
n_experiences=5, seed=1), experience_size=0, custom_split_strategy=shrinking_experience_size_split_strategy)
n_inputs = 784
nh = 100
nl = 2
n_outputs = 10
model = MLP([n_inputs] + [nh] * nl + [n_outputs])
return model, scenario
if __name__ == "__main__":
dev = "cuda:0"
device = torch.device(dev)
#_______________________________________Model and scenario
model, scenario = setup_mnist()
eval_plugin = EvaluationPlugin(
accuracy_metrics(epoch=True, experience=True, stream=True),
loss_metrics(stream=True), loggers=[InteractiveLogger()])
# _____________________________Strategy
optimizer = SGD(model.parameters(), lr=0.05)
strategy = GSS_greedy(model, optimizer, criterion=CrossEntropyLoss(), train_mb_size=10, mem_strength=10, input_size=[
1, 28, 28], train_epochs=3, eval_mb_size=10, mem_size=300, evaluator=eval_plugin)
# ___________________________________________train
for experience in scenario.train_stream:
print(">Experience ", experience.current_experience)
res = strategy.train(experience)
res = strategy.eval(scenario.test_stream)
| Python | 0.000003 |
c0eedfeca0e19a65e4484e63790319cf18433343 | change optimizer in example | examples/mnist_mlp.py | examples/mnist_mlp.py | '''Trains a simple deep NN on the MNIST dataset.
Gets to 98.40% test accuracy after 20 epochs
(there is *a lot* of margin for parameter tuning).
2 seconds per epoch on a K520 GPU.
'''
from __future__ import print_function
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD, Adam, RMSprop
from keras.utils import np_utils
batch_size = 128
nb_classes = 10
nb_epoch = 20
# the data, shuffled and split between train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.reshape(60000, 784)
X_test = X_test.reshape(10000, 784)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)
model = Sequential()
model.add(Dense(512, input_shape=(784,)))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(10))
model.add(Activation('softmax'))
model.summary()
model.compile(loss='categorical_crossentropy',
optimizer=RMSprop(),
metrics=['accuracy'])
history = model.fit(X_train, Y_train,
batch_size=batch_size, nb_epoch=nb_epoch,
verbose=1, validation_data=(X_test, Y_test))
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test score:', score[0])
print('Test accuracy:', score[1])
| '''Trains a simple deep NN on the MNIST dataset.
Gets to 98.40% test accuracy after 20 epochs
(there is *a lot* of margin for parameter tuning).
2 seconds per epoch on a K520 GPU.
'''
from __future__ import print_function
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD, Adam, RMSprop
from keras.utils import np_utils
batch_size = 128
nb_classes = 10
nb_epoch = 20
# the data, shuffled and split between train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.reshape(60000, 784)
X_test = X_test.reshape(10000, 784)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)
model = Sequential()
model.add(Dense(512, input_shape=(784,)))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(10))
model.add(Activation('softmax'))
model.summary()
model.compile(loss='categorical_crossentropy',
optimizer=Adam(),
metrics=['accuracy'])
history = model.fit(X_train, Y_train,
batch_size=batch_size, nb_epoch=nb_epoch,
verbose=1, validation_data=(X_test, Y_test))
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test score:', score[0])
print('Test accuracy:', score[1])
| Python | 0 |
a5be3784d0cfce42c0cdb6bc83b37a07dff7a164 | Implement accuracy on GPU | chainer/functions/accuracy.py | chainer/functions/accuracy.py | import numpy
from pycuda import gpuarray
from chainer import cuda, Function
class Accuracy(Function):
"""Compute accuracy within minibatch."""
def forward_cpu(self, inputs):
y, t = inputs
y = y.reshape(y.shape[0], y.size / y.shape[0]) # flatten
pred = y.argmax(axis=1)
return (pred == t).mean(dtype=numpy.float32),
def forward_gpu(self, inputs):
x, t = inputs
fragments = cuda.empty((x.shape[0],), dtype=numpy.int8)
cuda.elementwise(
'char* fragments, const float* x, const int* t, int c',
'''
x += i * c;
float maxval = x[0];
int argmax = 0;
for (int j = 1; j < c; ++j) {
if (maxval < x[j]) {
maxval = x[j];
argmax = j;
}
}
fragments[i] = argmax == t[i];
''', 'accuracy_fwd_map')(fragments, x, t, x.shape[1])
y = gpuarray.sum(fragments, dtype=numpy.float32)
y /= x.shape[0]
return y,
def accuracy(y, t):
return Accuracy()(y, t)
| import numpy
from chainer import cuda, Function
class Accuracy(Function):
"""Compute accuracy within minibatch."""
def forward_cpu(self, inputs):
y, t = inputs
y = y.reshape(y.shape[0], y.size / y.shape[0]) # flatten
pred = y.argmax(axis=1)
return (pred == t).mean(dtype=numpy.float32),
def forward_gpu(self, inputs):
# Fallback to CPU
# TODO(beam2d): Pure GPU version
accuracy, = self.forward_cpu((a.get() for a in inputs))
return cuda.to_gpu_async(numpy.array(accuracy)),
def accuracy(y, t):
return Accuracy()(y, t)
| Python | 0.000008 |
f3c5a477141e5f3845641111f775ea90398be633 | Add numpy.ndarray and cupy.ndarray as input type | chainer/functions/math/erf.py | chainer/functions/math/erf.py | import math
import warnings
import numpy
import chainer
from chainer import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
_erf_cpu = None
class Erf(function_node.FunctionNode):
@property
def label(self):
return 'erf'
def check_type_forward(self, in_types):
type_check.expect(in_types.size() == 1)
type_check.expect(in_types[0].dtype.kind == 'f')
def forward_cpu(self, x):
global _erf_cpu
if _erf_cpu is None:
try:
from scipy import special
_erf_cpu = special.erf
except ImportError:
warnings.warn(
"SciPy is not available. Forward computation of erf in CPU"
" can be slow without SciPy.")
_erf_cpu = numpy.vectorize(math.erf)
self.retain_inputs((0,))
return utils.force_array(_erf_cpu(x[0]), dtype=x[0].dtype),
def forward_gpu(self, x):
self.retain_inputs((0,))
return cuda.elementwise(
'T x', 'T y',
'y = erf(x)',
'elementwise_erf',
)(x[0]),
def backward(self, indexes, gy):
x = self.get_retained_inputs()[0]
return 2 / numpy.pi ** 0.5 * chainer.functions.exp(-x ** 2) * gy[0],
def erf(x):
"""Elementwise error function.
.. note::
Forward computation in CPU can be slow if
`SciPy <https://www.scipy.org/>`_ is not available.
Args:
x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
:class:`cupy.ndarray`): Input variable.
Returns:
~chainer.Variable: Output variable.
"""
return Erf().apply((x,))[0]
| import math
import warnings
import numpy
import chainer
from chainer import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
_erf_cpu = None
class Erf(function_node.FunctionNode):
@property
def label(self):
return 'erf'
def check_type_forward(self, in_types):
type_check.expect(in_types.size() == 1)
type_check.expect(in_types[0].dtype.kind == 'f')
def forward_cpu(self, x):
global _erf_cpu
if _erf_cpu is None:
try:
from scipy import special
_erf_cpu = special.erf
except ImportError:
warnings.warn(
"SciPy is not available. Forward computation of erf in CPU"
" can be slow without SciPy.")
_erf_cpu = numpy.vectorize(math.erf)
self.retain_inputs((0,))
return utils.force_array(_erf_cpu(x[0]), dtype=x[0].dtype),
def forward_gpu(self, x):
self.retain_inputs((0,))
return cuda.elementwise(
'T x', 'T y',
'y = erf(x)',
'elementwise_erf',
)(x[0]),
def backward(self, indexes, gy):
x = self.get_retained_inputs()[0]
return 2 / numpy.pi ** 0.5 * chainer.functions.exp(-x ** 2) * gy[0],
def erf(x):
"""Elementwise error function.
.. note::
Forward computation in CPU can be slow if
`SciPy <https://www.scipy.org/>`_ is not available.
Args:
x (~chainer.Variable): Input variable.
Returns:
~chainer.Variable: Output variable.
"""
return Erf().apply((x,))[0]
| Python | 0.000127 |
0eeacf39140ae204bcea59a497acb8e58d949f5a | Remove unused relation join | changes/utils/originfinder.py | changes/utils/originfinder.py | from __future__ import absolute_import
from collections import defaultdict
from sqlalchemy.orm import subqueryload_all
from changes.config import db
from changes.constants import Result, Status
from changes.models import Build, Job, TestGroup, Source
def first(key, iterable):
for x in iterable:
if key(x):
return x
return None
def find_failure_origins(build, test_failures):
"""
Attempt to find originating causes of failures.
Returns a mapping of {TestGroup.name_sha: Job}.
"""
project = build.project
if not test_failures:
return {}
# find any existing failures in the previous runs
# to do this we first need to find the last passing job
last_pass = Build.query.join(
Source, Source.id == Build.source_id,
).filter(
Build.project == project,
Build.date_created <= build.date_created,
Build.status == Status.finished,
Build.result == Result.passed,
Build.id != build.id,
Source.patch == None, # NOQA
).order_by(Build.date_created.desc()).first()
if last_pass is None:
return {}
# We have to query all runs between build and last_pass. Because we're
# paranoid about performance, we limit this to 100 results.
previous_runs = Build.query.join(
Source, Source.id == build.source_id,
).filter(
Build.project == project,
Build.date_created <= build.date_created,
Build.date_created >= last_pass.date_created,
Build.status == Status.finished,
Build.result.in_([Result.failed, Result.passed]),
Build.id != build.id,
Build.id != last_pass.id,
Source.patch == None, # NOQA
).order_by(Build.date_created.desc())[:100]
if not previous_runs:
return {}
# we now have a list of previous_runs so let's find all test failures in
# these runs
queryset = db.session.query(
TestGroup.name_sha, Job.build_id,
).join(
Job, Job.id == TestGroup.job_id,
).filter(
Job.build_id.in_(b.id for b in previous_runs),
Job.status == Status.finished,
Job.result == Result.failed,
TestGroup.result == Result.failed,
TestGroup.num_leaves == 0,
TestGroup.name_sha.in_(t.name_sha for t in test_failures),
).group_by(
TestGroup.name_sha, Job.build_id
)
previous_test_failures = defaultdict(set)
for name_sha, build_id in queryset:
previous_test_failures[build_id].add(name_sha)
failures_at_build = dict()
searching = set(t for t in test_failures)
last_checked_run = build
for p_build in previous_runs:
p_build_failures = previous_test_failures[p_build.id]
# we have to copy the set as it might change size during iteration
for f_test in list(searching):
if f_test.name_sha not in p_build_failures:
failures_at_build[f_test] = last_checked_run
searching.remove(f_test)
last_checked_run = p_build
for f_test in searching:
failures_at_build[f_test] = last_checked_run
return failures_at_build
| from __future__ import absolute_import
from collections import defaultdict
from sqlalchemy.orm import subqueryload_all
from changes.config import db
from changes.constants import Result, Status
from changes.models import Build, Job, TestGroup, Source
def first(key, iterable):
for x in iterable:
if key(x):
return x
return None
def find_failure_origins(build, test_failures):
"""
Attempt to find originating causes of failures.
Returns a mapping of {TestGroup.name_sha: Job}.
"""
project = build.project
if not test_failures:
return {}
# find any existing failures in the previous runs
# to do this we first need to find the last passing job
last_pass = Build.query.join(
Source, Source.id == Build.source_id,
).filter(
Build.project == project,
Build.date_created <= build.date_created,
Build.status == Status.finished,
Build.result == Result.passed,
Build.id != build.id,
Source.patch == None, # NOQA
).order_by(Build.date_created.desc()).first()
if last_pass is None:
return {}
# We have to query all runs between build and last_pass. Because we're
# paranoid about performance, we limit this to 100 results.
previous_runs = Build.query.join(
Source, Source.id == build.source_id,
).options(
subqueryload_all(Build.jobs),
).filter(
Build.project == project,
Build.date_created <= build.date_created,
Build.date_created >= last_pass.date_created,
Build.status == Status.finished,
Build.result.in_([Result.failed, Result.passed]),
Build.id != build.id,
Build.id != last_pass.id,
Source.patch == None, # NOQA
).order_by(Build.date_created.desc())[:100]
if not previous_runs:
return {}
# we now have a list of previous_runs so let's find all test failures in
# these runs
queryset = db.session.query(
TestGroup.name_sha, Job.build_id,
).join(
Job, Job.id == TestGroup.job_id,
).filter(
Job.build_id.in_(b.id for b in previous_runs),
Job.status == Status.finished,
Job.result == Result.failed,
TestGroup.result == Result.failed,
TestGroup.num_leaves == 0,
TestGroup.name_sha.in_(t.name_sha for t in test_failures),
).group_by(
TestGroup.name_sha, Job.build_id
)
previous_test_failures = defaultdict(set)
for name_sha, build_id in queryset:
previous_test_failures[build_id].add(name_sha)
failures_at_build = dict()
searching = set(t for t in test_failures)
last_checked_run = build
for p_build in previous_runs:
p_build_failures = previous_test_failures[p_build.id]
# we have to copy the set as it might change size during iteration
for f_test in list(searching):
if f_test.name_sha not in p_build_failures:
failures_at_build[f_test] = last_checked_run
searching.remove(f_test)
last_checked_run = p_build
for f_test in searching:
failures_at_build[f_test] = last_checked_run
return failures_at_build
| Python | 0.000001 |
569e21f9ad9f9668c7dcfcd4dba64806c9c07d7d | Support origination contexts in V2. | ambassador/ambassador/envoy/v2/v2cluster.py | ambassador/ambassador/envoy/v2/v2cluster.py | # Copyright 2018 Datawire. 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 urllib
from typing import List, TYPE_CHECKING
from ...ir.ircluster import IRCluster
from .v2tls import V2TLSContext
if TYPE_CHECKING:
from . import V2Config
class V2Cluster(dict):
def __init__(self, config: 'V2Config', cluster: IRCluster) -> None:
super().__init__()
fields = {
'name': cluster.name,
'type': cluster.type.upper(),
'lb_policy': cluster.lb_type.upper(),
'connect_timeout': "3s",
'load_assignment': {
'cluster_name': cluster.name,
'endpoints': [
{
'lb_endpoints': self.get_endpoints(cluster)
}
]
}
}
if cluster.get('grpc', False):
self["http2_protocol_options"] = {}
ctx = cluster.get('tls_context', None)
if ctx is not None:
# If this is a null TLS Context (_ambassador_enabled is True), then we at need to specify a
# minimal `tls_context` to enable HTTPS origination.
if ctx.get('_ambassador_enabled', False):
fields['tls_context'] = {
'common_tls_context': {}
}
else:
envoy_ctx = V2TLSContext(ctx=ctx, host_rewrite=cluster.get('host_rewrite', None))
if envoy_ctx:
fields['tls_context'] = envoy_ctx
self.update(fields)
def get_endpoints(self, cluster: IRCluster):
result = []
for u in cluster.urls:
p = urllib.parse.urlparse(u)
address = {
'address': p.hostname,
'port_value': int(p.port)
}
if p.scheme:
address['protocol'] = p.scheme.upper()
result.append({'endpoint': {'address': {'socket_address': address}}})
return result
@classmethod
def generate(self, config: 'V2Config') -> None:
config.clusters = []
for ircluster in sorted(config.ir.clusters.values(), key=lambda x: x.name):
cluster = config.save_element('cluster', ircluster, V2Cluster(config, ircluster))
config.clusters.append(cluster)
| # Copyright 2018 Datawire. 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 urllib
from typing import List, TYPE_CHECKING
from ...ir.ircluster import IRCluster
from .v2tls import V2TLSContext
if TYPE_CHECKING:
from . import V2Config
class V2Cluster(dict):
def __init__(self, config: 'V2Config', cluster: IRCluster) -> None:
super().__init__()
fields = {
'name': cluster.name,
'type': cluster.type.upper(),
'lb_policy': cluster.lb_type.upper(),
'connect_timeout': "3s",
'load_assignment': {
'cluster_name': cluster.name,
'endpoints': [
{
'lb_endpoints': self.get_endpoints(cluster)
}
]
}
}
if cluster.get('grpc', False):
self["http2_protocol_options"] = {}
ctx = cluster.get('tls_context', None)
if ctx is not None:
# If TLS Context is enabled, then we at least need to specify `tls_context` to enabled HTTPS origination
if ctx.get('enabled'):
fields['tls_context'] = {
'common_tls_context': {}
}
envoy_ctx = V2TLSContext(ctx=ctx, host_rewrite=cluster.get('host_rewrite', None))
if envoy_ctx:
fields['tls_context'] = envoy_ctx
self.update(fields)
def get_endpoints(self, cluster: IRCluster):
result = []
for u in cluster.urls:
p = urllib.parse.urlparse(u)
address = {
'address': p.hostname,
'port_value': int(p.port)
}
if p.scheme:
address['protocol'] = p.scheme.upper()
result.append({'endpoint': {'address': {'socket_address': address}}})
return result
@classmethod
def generate(self, config: 'V2Config') -> None:
config.clusters = []
for ircluster in sorted(config.ir.clusters.values(), key=lambda x: x.name):
cluster = config.save_element('cluster', ircluster, V2Cluster(config, ircluster))
config.clusters.append(cluster)
| Python | 0 |
95d6c63dfd527f3ffc19a713b2a2dfa2b97dfb1a | remove unnecessary lines | client/python/modeldb/tests/sklearn/testRandomSplitEvent.py | client/python/modeldb/tests/sklearn/testRandomSplitEvent.py | import unittest
import sys
from ModelDbSyncerTest import SyncerTest
import modeldb.tests.utils as utils
from modeldb.thrift.modeldb import ttypes as modeldb_types
from modeldb.sklearn_native.ModelDbSyncer import *
from modeldb.sklearn_native import SyncableRandomSplit
import pandas as pd
import random
class TestRandomSplitEvent(unittest.TestCase):
def setUp(self):
name = "random split test"
author = "srinidhi"
description = "70/30 split"
SyncerObj = SyncerTest(
NewOrExistingProject(name, author, description),
DefaultExperiment(),
NewExperimentRun("Abc"))
X = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
y = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=['output'])
X.tag("digits-dataset")
seed = 1
weights = [0.7, 0.3]
SyncerTest.instance.clearBuffer()
X_set, y_set = SyncableRandomSplit.randomSplit(X, [0.7, 0.3], seed, y)
events = SyncerTest.instance.sync()
self.randomSplitEvent = events[0]
def test_random_split_event(self):
utils.validate_random_split_event_struct(self.randomSplitEvent, self)
self.assertEquals(self.randomSplitEvent.weights, [0.7, 0.3])
self.assertEquals(self.randomSplitEvent.seed, 1)
def test_old_dataframe(self):
old_df = self.randomSplitEvent.oldDataFrame
expected_df = modeldb_types.DataFrame(
-1,
[
modeldb_types.DataFrameColumn('A', 'int64'),
modeldb_types.DataFrameColumn('B', 'int64'),
modeldb_types.DataFrameColumn('C', 'int64'),
modeldb_types.DataFrameColumn('D', 'int64'),
],
100,
'digits-dataset')
utils.is_equal_dataframe(old_df, expected_df, self)
def test_split_dataframes(self):
split_data_frames = self.randomSplitEvent.splitDataFrames
self.assertEquals(len(split_data_frames), 2)
dataframe1 = split_data_frames[0]
dataframe2 = split_data_frames[1]
utils.validate_dataframe_struct(dataframe1, self)
utils.validate_dataframe_struct(dataframe2, self)
# Check if dataframes are split according to weights (within some margin of error)
self.assertIn(dataframe1.numRows, range(60,80))
self.assertIn(dataframe2.numRows, range(20,40))
self.assertEquals(dataframe1.numRows + dataframe2.numRows, 100)
if __name__ == '__main__':
unittest.main()
| import unittest
import sys
from ModelDbSyncerTest import SyncerTest
import modeldb.tests.utils as utils
from modeldb.thrift.modeldb import ttypes as modeldb_types
from modeldb.sklearn_native.ModelDbSyncer import *
from modeldb.sklearn_native import SyncableRandomSplit
import pandas as pd
import random
FMIN = sys.float_info.min
FMAX = sys.float_info.max
class TestRandomSplitEvent(unittest.TestCase):
def setUp(self):
name = "random split test"
author = "srinidhi"
description = "70/30 split"
SyncerObj = SyncerTest(
NewOrExistingProject(name, author, description),
DefaultExperiment(),
NewExperimentRun("Abc"))
X = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
y = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=['output'])
X.tag("digits-dataset")
seed = 1
weights = [0.7, 0.3]
SyncerTest.instance.clearBuffer()
X_set, y_set = SyncableRandomSplit.randomSplit(X, [0.7, 0.3], seed, y)
events = SyncerTest.instance.sync()
self.randomSplitEvent = events[0]
def test_random_split_event(self):
utils.validate_random_split_event_struct(self.randomSplitEvent, self)
self.assertEquals(self.randomSplitEvent.weights, [0.7, 0.3])
self.assertEquals(self.randomSplitEvent.seed, 1)
def test_old_dataframe(self):
old_df = self.randomSplitEvent.oldDataFrame
expected_df = modeldb_types.DataFrame(
-1,
[
modeldb_types.DataFrameColumn('A', 'int64'),
modeldb_types.DataFrameColumn('B', 'int64'),
modeldb_types.DataFrameColumn('C', 'int64'),
modeldb_types.DataFrameColumn('D', 'int64'),
],
100,
'digits-dataset')
utils.is_equal_dataframe(old_df, expected_df, self)
def test_split_dataframes(self):
split_data_frames = self.randomSplitEvent.splitDataFrames
self.assertEquals(len(split_data_frames), 2)
dataframe1 = split_data_frames[0]
dataframe2 = split_data_frames[1]
utils.validate_dataframe_struct(dataframe1, self)
utils.validate_dataframe_struct(dataframe2, self)
# Check if dataframes are split according to weights (within some margin of error)
self.assertIn(dataframe1.numRows, range(60,80))
self.assertIn(dataframe2.numRows, range(20,40))
self.assertEquals(dataframe1.numRows + dataframe2.numRows, 100)
if __name__ == '__main__':
unittest.main()
| Python | 0.999144 |
8c4a54690cb99b63a9cf825e2958bb2b48cd7e5d | Complete lc009_palindrome_number.py | lc009_palindrome_number.py | lc009_palindrome_number.py | """Leetcode 9. Palindrome Number
Easy
Determine whether an integer is a palindrome. An integer is a palindrome when
it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes
121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
"""
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
x_str = str(x)
return x_str == x_str[::-1]
class Solution2(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
ls = []
while x > 0:
div, mod = divmod(x, 10)
x = div
ls.append(mod)
return ls == ls[::-1]
def main():
x = 121 # Ans: True.
print(Solution().isPalindrome(x))
print(Solution2().isPalindrome(x))
x = -121 # Ans: False.
print(Solution().isPalindrome(x))
print(Solution2().isPalindrome(x))
x = 10 # Ans: False.
print(Solution().isPalindrome(x))
print(Solution2().isPalindrome(x))
if __name__ == '__main__':
main()
| """Leetcode 9. Palindrome Number
Easy
Determine whether an integer is a palindrome. An integer is a palindrome when
it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes
121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
"""
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
pass
def main():
pass
if __name__ == '__main__':
main()
| Python | 0.999989 |
d325ed4aade30378e050cf2443081a86a6d4438c | Revise to var min_hq | lc0253_meeting_rooms_ii.py | lc0253_meeting_rooms_ii.py | """Leetcode 253. Meeting Rooms II (Premium)
Medium
URL: https://leetcode.com/problems/meeting-rooms-ii
Given an array of meeting time intervals consisting of start and end times
[[s1,e1],[s2,e2],...] (si < ei),
find the minimum number of conference rooms required.
Example1
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
Explanation:
We need two meeting rooms
room1: (0,30)
room2: (5,10),(15,20)
Example2
Input: intervals = [[7, 10], [2, 4]]
Output: 1
Explanation:
Only need one meeting room
"""
class SolutionSortEndMinHeapEnd(object):
def minMeetingRooms(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
Time complexity: O(n*logn).
Space complexity: O(n).
"""
import heapq
if not intervals or not intervals[0]:
return 0
# Sort intervals by start time.
intervals.sort()
# Use min heap to store end times.
end_minhq = []
heapq.heappush(end_minhq, intervals[0][1])
for i in range(1, len(intervals)):
# If next start time is after min end time, remove min end time.
if intervals[i][0] >= end_minhq[0]:
heapq.heappop(end_minhq)
# Add next end time to min heap.
heapq.heappush(end_minhq, intervals[i][1])
return len(end_minhq)
class SolutionTimeCounterListInsort(object):
def minMeetingRooms(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
Time complexity: O(n).
Space complexity: O(n).
"""
from bisect import insort
# Sort times and add increment/decrement counters by start/end.
time_counters = []
for i in range(len(intervals)):
insort(time_counters, (intervals[i][0], 1))
insort(time_counters, (intervals[i][1], -1))
cur_n, max_n = 0, 0
for t, counter in time_counters:
cur_n += counter
max_n = max(max_n, cur_n)
return max_n
def main():
# Output: 2.
intervals = [[0,30],[5,10],[15,20]]
print SolutionSortEndMinHeapEnd().minMeetingRooms(intervals)
print SolutionTimeCounterListInsort().minMeetingRooms(intervals)
# Output: 1.
intervals = [[7, 10], [2, 4]]
print SolutionSortEndMinHeapEnd().minMeetingRooms(intervals)
print SolutionTimeCounterListInsort().minMeetingRooms(intervals)
if __name__ == '__main__':
main()
| """Leetcode 253. Meeting Rooms II (Premium)
Medium
URL: https://leetcode.com/problems/meeting-rooms-ii
Given an array of meeting time intervals consisting of start and end times
[[s1,e1],[s2,e2],...] (si < ei),
find the minimum number of conference rooms required.
Example1
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
Explanation:
We need two meeting rooms
room1: (0,30)
room2: (5,10),(15,20)
Example2
Input: intervals = [[7, 10], [2, 4]]
Output: 1
Explanation:
Only need one meeting room
"""
class SolutionSortEndMinHeapEnd(object):
def minMeetingRooms(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
Time complexity: O(n*logn).
Space complexity: O(n).
"""
import heapq
if not intervals or not intervals[0]:
return 0
# Sort intervals by start time.
intervals.sort()
# Use min heap to store end times.
end_minheap = []
heapq.heappush(end_minheap, intervals[0][1])
for i in range(1, len(intervals)):
# If next start time is after min end time, remove min end time.
if intervals[i][0] >= end_minheap[0]:
heapq.heappop(end_minheap)
# Add next end time to min heap.
heapq.heappush(end_minheap, intervals[i][1])
return len(end_minheap)
class SolutionTimeCounterListInsort(object):
def minMeetingRooms(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
Time complexity: O(n).
Space complexity: O(n).
"""
from bisect import insort
# Sort times and add increment/decrement counters by start/end.
time_counters = []
for i in range(len(intervals)):
insort(time_counters, (intervals[i][0], 1))
insort(time_counters, (intervals[i][1], -1))
cur_n, max_n = 0, 0
for t, counter in time_counters:
cur_n += counter
max_n = max(max_n, cur_n)
return max_n
def main():
# Output: 2.
intervals = [[0,30],[5,10],[15,20]]
print SolutionSortEndMinHeapEnd().minMeetingRooms(intervals)
print SolutionTimeCounterListInsort().minMeetingRooms(intervals)
# Output: 1.
intervals = [[7, 10], [2, 4]]
print SolutionSortEndMinHeapEnd().minMeetingRooms(intervals)
print SolutionTimeCounterListInsort().minMeetingRooms(intervals)
if __name__ == '__main__':
main()
| Python | 0.001577 |
a2dcb94726d0bcc58b08eddcab6ebf433778af2c | Fix error handler to correct view. | zoll_me/urls.py | zoll_me/urls.py | '''
James D. Zoll
1/20/2013
Purpose: Defines URL rules for the project.
License: This is a public work.
'''
# Library Imports
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^scarf/', include('scarf.urls')),
url(r'^rss/', include('rss.urls')),
url(r'^files/', include('files.urls')),
url(r'^xbmc_photos/', include('xbmc_photos.urls')),
url(r'^leapday/', include('leapday.urls')),
url(r'^lensoftruth/', include('lensoftruth.urls')),
url(r'^dk_optimize/', include('dk_optimize.urls')),
url(r'^$', 'zoll_me.views.index'),
url(r'^resume/$', 'zoll_me.views.resume'),
url(r'^projects/$', 'zoll_me.views.projects'),
url(r'^account/login/$','django.contrib.auth.views.login', {'template_name': 'zoll_me/account/login.html'}, name="zoll_me-login"),
url(r'^account/logout/$','django.contrib.auth.views.logout', {'template_name': 'zoll_me/account/logged_out.html'}),
url(r'^account/password_change/$','django.contrib.auth.views.password_change', {'template_name': 'zoll_me/account/password_change.html'}),
url(r'^account/password_change_done/$','django.contrib.auth.views.password_change_done', {'template_name': 'zoll_me/account/password_change_done.html'}),
url(r'^account/password_reset/$','django.contrib.auth.views.password_reset', {'template_name': 'zoll_me/account/password_reset.html', 'email_template_name': 'zoll_me/account/password_reset_email.txt', 'subject_template_name':'zoll_me/account/password_reset_subject.txt'}),
url(r'^account/password_reset_done/$','django.contrib.auth.views.password_reset_done', {'template_name': 'zoll_me/account/password_reset_done.html'}),
url(r'^account/password_reset_complete/$','django.contrib.auth.views.password_reset_complete', {'template_name': 'zoll_me/account/password_reset_complete.html'}),
url(r'^account/password_reset_confirm/(?P<uidb36>\d+)/(?P<token>[\d\w-]+)$','django.contrib.auth.views.password_reset_confirm', {'template_name': 'zoll_me/account/password_reset_confirm.html'})
)
# When we're in DEBUG mode, I want to be able to access some
# resources that aren't accessible directly in production. These URLconfs
# are added to make that possible.
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
url(r'^400/$', 'zoll_me.views.error_400'),
url(r'^403/$', 'zoll_me.views.error_403'),
url(r'^404/$', 'zoll_me.views.error_404'),
url(r'^500/$', 'zoll_me.views.error_500'),
)
# Define error handling views.
handler403 = 'zoll_me.views.error_403'
handler404 = 'zoll_me.views.error_404'
handler500 = 'zoll_me.views.error_500' | '''
James D. Zoll
1/20/2013
Purpose: Defines URL rules for the project.
License: This is a public work.
'''
# Library Imports
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^scarf/', include('scarf.urls')),
url(r'^rss/', include('rss.urls')),
url(r'^files/', include('files.urls')),
url(r'^xbmc_photos/', include('xbmc_photos.urls')),
url(r'^leapday/', include('leapday.urls')),
url(r'^lensoftruth/', include('lensoftruth.urls')),
url(r'^dk_optimize/', include('dk_optimize.urls')),
url(r'^$', 'zoll_me.views.index'),
url(r'^resume/$', 'zoll_me.views.resume'),
url(r'^projects/$', 'zoll_me.views.projects'),
url(r'^account/login/$','django.contrib.auth.views.login', {'template_name': 'zoll_me/account/login.html'}, name="zoll_me-login"),
url(r'^account/logout/$','django.contrib.auth.views.logout', {'template_name': 'zoll_me/account/logged_out.html'}),
url(r'^account/password_change/$','django.contrib.auth.views.password_change', {'template_name': 'zoll_me/account/password_change.html'}),
url(r'^account/password_change_done/$','django.contrib.auth.views.password_change_done', {'template_name': 'zoll_me/account/password_change_done.html'}),
url(r'^account/password_reset/$','django.contrib.auth.views.password_reset', {'template_name': 'zoll_me/account/password_reset.html', 'email_template_name': 'zoll_me/account/password_reset_email.txt', 'subject_template_name':'zoll_me/account/password_reset_subject.txt'}),
url(r'^account/password_reset_done/$','django.contrib.auth.views.password_reset_done', {'template_name': 'zoll_me/account/password_reset_done.html'}),
url(r'^account/password_reset_complete/$','django.contrib.auth.views.password_reset_complete', {'template_name': 'zoll_me/account/password_reset_complete.html'}),
url(r'^account/password_reset_confirm/(?P<uidb36>\d+)/(?P<token>[\d\w-]+)$','django.contrib.auth.views.password_reset_confirm', {'template_name': 'zoll_me/account/password_reset_confirm.html'})
)
# When we're in DEBUG mode, I want to be able to access some
# resources that aren't accessible directly in production. These URLconfs
# are added to make that possible.
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
url(r'^400/$', 'zoll_me.views.error_400'),
url(r'^403/$', 'zoll_me.views.error_403'),
url(r'^404/$', 'zoll_me.views.error_404'),
url(r'^500/$', 'zoll_me.views.error_500'),
)
# Define error handling views.
handler403 = 'zoll_me.views.error_404'
handler404 = 'zoll_me.views.error_404'
handler500 = 'zoll_me.views.error_500' | Python | 0 |
9e9f831a757af01cc3b1edfe590e27f7ab53c2ce | define interfaces | zvmsdk/vmops.py | zvmsdk/vmops.py |
from log import LOG
import utils as zvmutils
VMOPS = None
def _get_vmops():
if VMOPS is None:
VMOPS = VMOps()
return VMOPS
def run_instance(instance_name, image_id, cpu, memory,
login_password, ip_addr):
"""Deploy and provision a virtual machine.
Input parameters:
:instance_name: USERID of the instance, last 8 if length > 8
:image_id: Image ID
:cpu: vcpu
:memory: memory
:login_password: login password
:ip_addr: ip address
"""
pass
def terminate_instance(instance_name):
"""Destroy a virtual machine.
Input parameters:
:instance_name: USERID of the instance, last 8 if length > 8
"""
pass
def start_instance(instance_name):
"""Power on a virtual machine.
Input parameters:
:instance_name: USERID of the instance, last 8 if length > 8
"""
_get_vmops()._power_state(instance_name, "PUT", "on")
def stop_instance(instance_name):
"""Shutdown a virtual machine.
Input parameters:
:instance_name: USERID of the instance, last 8 if length > 8
"""
pass
def create_volume(volume_name, size):
"""Create a volume.
Input parameters:
:volume_name: volume name
:size: size
"""
pass
def delete_volume(volume_name):
"""Create a volume.
Input parameters:
:volume_name: volume name
"""
pass
def attach_volume(instance_name, volume_name):
"""Create a volume.
Input parameters:
:instance_name: USERID of the instance, last 8 if length > 8
:volume_name: volume name
"""
pass
def capture_instance(instance_name, image_name):
"""Caputre a virtual machine image.
Input parameters:
:instance_name: USERID of the instance, last 8 if length > 8
:image_name: Image name
"""
pass
def delete_image(image_name):
"""Delete image.
Input parameters:
:image_name: Image name
"""
pass
def detach_volume(instance_name, volume_name):
"""Create a volume.
Input parameters:
:instance_name: USERID of the instance, last 8 if length > 8
:volume_name: volume name
"""
pass
class VMOps(object):
def __init__(self):
self._xcat_url = zvmutils.get_xcat_url()
def _power_state(self, instance_name, method, state):
"""Invoke xCAT REST API to set/get power state for a instance."""
body = [state]
url = self._xcat_url.rpower('/' + instance_name)
return zvmutils.xcat_request(method, url, body)
def get_power_state(self, instance_name):
"""Get power status of a z/VM instance."""
LOG.debug('Query power stat of %s' % instance_name)
res_dict = self._power_state(instance_name, "GET", "stat")
@zvmutils.wrap_invalid_xcat_resp_data_error
def _get_power_string(d):
tempstr = d['info'][0][0]
return tempstr[(tempstr.find(':') + 2):].strip()
power_stat = _get_power_string(res_dict)
return power_stat
|
from log import LOG
import utils as zvmutils
class VMOps(object):
def __init__(self):
self._xcat_url = zvmutils.get_xcat_url()
def _power_state(self, instance_name, method, state):
"""Invoke xCAT REST API to set/get power state for a instance."""
body = [state]
url = self._xcat_url.rpower('/' + instance_name)
return zvmutils.xcat_request(method, url, body)
def get_power_state(self, instance_name):
"""Get power status of a z/VM instance."""
LOG.debug('Query power stat of %s' % instance_name)
res_dict = self._power_state(instance_name, "GET", "stat")
@zvmutils.wrap_invalid_xcat_resp_data_error
def _get_power_string(d):
tempstr = d['info'][0][0]
return tempstr[(tempstr.find(':') + 2):].strip()
power_stat = _get_power_string(res_dict)
return power_stat
| Python | 0.000003 |
dfaa289465a2cdc837884718624b9a8a65e511b3 | Improve proxy rax example | examples/proxy_rax.py | examples/proxy_rax.py | import random
import sc2
from sc2 import Race, Difficulty
from sc2.constants import *
from sc2.player import Bot, Computer
class ProxyRaxBot(sc2.BotAI):
async def on_step(self, state, iteration):
cc = self.units(COMMANDCENTER)
if not cc.exists:
target = self.known_enemy_structures.random_or(self.enemy_start_locations[0]).position
for unit in self.workers | self.units(MARINE):
await self.do(unit.attack(target))
return
else:
cc = cc.first
if self.units(MARINE).idle.amount > 15 and iteration % 50 == 1:
target = self.known_enemy_structures.random_or(self.enemy_start_locations[0]).position
for marine in self.units(MARINE).idle:
await self.do(marine.attack(target))
if self.can_afford(SCV) and self.workers.amount < 16 and cc.noqueue:
await self.do(cc.train(SCV))
elif self.supply_left < (2 if self.units(BARRACKS).amount < 3 else 4):
if self.can_afford(SUPPLYDEPOT):
await self.build(SUPPLYDEPOT, near=cc.position.towards(self.game_info.map_center, 5))
elif self.units(BARRACKS).amount < 3 or (self.minerals > 400 and self.units(BARRACKS).amount < 5):
if self.can_afford(BARRACKS):
p = self.game_info.map_center.towards(self.enemy_start_locations[0], 25)
await self.build(BARRACKS, near=p)
for rax in self.units(BARRACKS).ready.noqueue:
if not self.can_afford(MARINE):
break
await self.do(rax.train(MARINE))
for scv in self.units(SCV).idle:
await self.do(scv.gather(self.state.mineral_field.closest_to(cc)))
def main():
sc2.run_game(sc2.maps.get("Sequencer LE"), [
Bot(Race.Terran, ProxyRaxBot()),
Computer(Race.Zerg, Difficulty.Hard)
], realtime=False)
if __name__ == '__main__':
main()
| import random
import sc2
from sc2 import Race, Difficulty
from sc2.constants import *
from sc2.player import Bot, Computer
class ProxyRaxBot(sc2.BotAI):
async def on_step(self, state, iteration):
cc = self.units(COMMANDCENTER)
if not cc.exists:
target = self.known_enemy_structures.random_or(self.enemy_start_locations[0]).position
for unit in self.workers | self.units(MARINE):
await self.do(unit.attack(target))
return
else:
cc = cc.first
if self.units(MARINE).idle.amount > 15 and iteration % 50 == 1:
target = self.known_enemy_structures.random_or(self.enemy_start_locations[0]).position
for marine in self.units(MARINE).idle:
await self.do(marine.attack(target))
if self.can_afford(SCV) and self.workers.amount < 16 and cc.noqueue:
await self.do(cc.train(SCV))
elif self.supply_left < 2:
if self.can_afford(SUPPLYDEPOT):
await self.build(SUPPLYDEPOT, near=cc.position.towards(self.game_info.map_center, 5))
elif self.units(BARRACKS).amount < 3 or self.minerals > 400:
if self.can_afford(BARRACKS):
p = self.game_info.map_center.towards(self.enemy_start_locations[0], 25)
await self.build(BARRACKS, near=p)
for rax in self.units(BARRACKS).ready.noqueue:
if not self.can_afford(MARINE):
break
await self.do(rax.train(MARINE))
for scv in self.units(SCV).idle:
await self.do(scv.gather(self.state.mineral_field.closest_to(cc)))
def main():
sc2.run_game(sc2.maps.get("Sequencer LE"), [
Bot(Race.Terran, ProxyRaxBot()),
Computer(Race.Zerg, Difficulty.Hard)
], realtime=True)
if __name__ == '__main__':
main()
| Python | 0.000001 |
a4b7878880f5a8d275129949179b4b30044f0c86 | Update __init__.py | eniric_scripts/__init__.py | eniric_scripts/__init__.py | __all__ = [
"bary_shift_atmmodel",
"phoenix_precision",
"precision_four_panel",
"split_atmmodel",
]
| __all__ = [
"bary_shift_atmmodel",
"phoenix_precision.py",
"precision_four_panel",
"split_atmmodel",
]
| Python | 0.000072 |
39f50aadc98f493a32810af0ba4d0fd87c8108e1 | Update runsegment.py | bin/runsegment.py | bin/runsegment.py | #!/usr/bin/python
import os
import numpy as np
import shutil
import common
from segment import normalizefile, segmentfile
def runAll(args):
print('\n\n\nYou have requested to normalize and segment bincounts files')
print('\tWARNING:')
print('\t\tIF USING ANY REFERENCES OTHER THAN THOSE I PROVIDE I CANNOT GUARANTEE RESULT ACCURACY')
print('\n')
#Set up environment#
args.CountDirectory = common.fixDirName(args.CountDirectory)
lowessDir = os.path.dirname(args.CountDirectory[:-1]) + '/LowessBinCounts/'
segmentDir = os.path.dirname(args.CountDirectory[:-1]) + '/Segments/'
tempDir = os.path.dirname(args.CountDirectory[:-1]) + '/Temp/'
if args.output:
lowessDir = common.fixDirName(args.output) + 'LowessBinCounts/'
segmentDir = common.fixDirName(args.output) + 'Segments/'
common.makeDir(lowessDir)
if not args.normalizeonly:
common.makeDir(segmentDir)
common.makeDir(tempDir)
sampleFiles = common.getSampleList(args.CountDirectory, args.samples, 'bincounts')
info = common.importInfoFile(args.infofile, args.columns, 'normalize')
if args.infofile:
refArray = info
else:
thisDtype = info
refArray = np.array(
[ (os.path.basename(x)[:-14], 'unk', 1,) for x in sampleFiles],
dtype=thisDtype)
sampleDict = {x: [y for y in sampleFiles if x == os.path.basename(y)[:len(x)]][0] for x in refArray['name']}
#Run normalization for all samples#
methodDict = {x: False for x in np.unique(refArray['method'])}
# methodDict['NA'] = False
sampleNormMethodDict = {x: 'NA' for x in methodDict}
if not args.gconly:
for i in methodDict:
refSlice = refArray[(refArray['method'] == i) & (refArray['cells'] == 1)]
methodSamples = [sampleDict[x] for x in refSlice['name']]
methodDict[i] = normalizefile.runMakeMethodRef(args.species, methodSamples, i, lowessDir)
print methodDict
if methodDict[i] == False:
continue
else:
for j in refSlice['name']:
sampleNormMethodDict[j] = i
print methodDict
print sampleNormMethodDict
raise SystemExit
#run multiprocessing for gc (+ method) correction
normArgs = [(args.species, sampleDict[x], methodDict[sampleNormMethodDict[x]], lowessDir + x + '.lowess.txt') for x in sampleDict.keys()]
common.daemon(normalizefile.runNormalizeOne, normArgs, 'normalize bincount files')
print('\nNormalization complete\n\n\n')
# if args.normalizeonly:
# shutil.rmtree(tempDir[:-1])
# return 0
#Run CBS for all samples#
if not args.normalizeonly:
segArgs = [(x, args.species, tempDir, lowessDir, segmentDir) for x in refArray['name']]
common.daemon(segmentfile.segmentOne, segArgs, 'segment bincount data')
shutil.rmtree(tempDir[:-1])
print('\nSegmentation complete\n\n\n')
| #!/usr/bin/python
import os
import numpy as np
import shutil
import common
from segment import normalizefile, segmentfile
def runAll(args):
print('\n\n\nYou have requested to normalize and segment bincounts files')
print('\tWARNING:')
print('\t\tIF USING ANY REFERENCES OTHER THAN THOSE I PROVIDE I CANNOT GUARANTEE RESULT ACCURACY')
print('\n')
#Set up environment#
args.CountDirectory = common.fixDirName(args.CountDirectory)
lowessDir = os.path.dirname(args.CountDirectory[:-1]) + '/LowessBinCounts/'
segmentDir = os.path.dirname(args.CountDirectory[:-1]) + '/Segments/'
tempDir = os.path.dirname(args.CountDirectory[:-1]) + '/Temp/'
if args.output:
lowessDir = common.fixDirName(args.output) + 'LowessBinCounts/'
segmentDir = common.fixDirName(args.output) + 'Segments/'
common.makeDir(lowessDir)
if not args.normalizeonly:
common.makeDir(segmentDir)
common.makeDir(tempDir)
sampleFiles = common.getSampleList(args.CountDirectory, args.samples, 'bincounts')
info = common.importInfoFile(args.infofile, args.columns, 'normalize')
if args.infofile:
refArray = info
else:
thisDtype = info
refArray = np.array(
[ (os.path.basename(x)[:-14], 'unk', 1,) for x in sampleFiles],
dtype=thisDtype)
sampleDict = {x: [y for y in sampleFiles if x == os.path.basename(y)[:len(x)]][0] for x in refArray['name']}
#Run normalization for all samples#
methodDict = {x: False for x in np.unique(refArray['method'])}
# methodDict['NA'] = False
sampleNormMethodDict = {x: 'NA' for x in methodDict}
if not args.gconly:
for i in methodDict:
refSlice = refArray[(refArray['method'] == i) & (refArray['cells'] == 1)]
print refSlice
methodSamples = [sampleDict[x] for x in refSlice['name']]
print methodSamples
methodDict[i] = normalizefile.runMakeMethodRef(args.species, methodSamples, i, lowessDir)
print methodDict
if methodDict[i] != False:
for j in refSlice['name']:
sampleNormMethodDict[j] = i
print methodDict
print sampleNormMethodDict
raise SystemExit
#run multiprocessing for gc (+ method) correction
normArgs = [(args.species, sampleDict[x], methodDict[sampleNormMethodDict[x]], lowessDir + x + '.lowess.txt') for x in sampleDict.keys()]
common.daemon(normalizefile.runNormalizeOne, normArgs, 'normalize bincount files')
print('\nNormalization complete\n\n\n')
# if args.normalizeonly:
# shutil.rmtree(tempDir[:-1])
# return 0
#Run CBS for all samples#
if not args.normalizeonly:
segArgs = [(x, args.species, tempDir, lowessDir, segmentDir) for x in refArray['name']]
common.daemon(segmentfile.segmentOne, segArgs, 'segment bincount data')
shutil.rmtree(tempDir[:-1])
print('\nSegmentation complete\n\n\n')
| Python | 0.000001 |
10d5e90e65e792d0fae3879dd5f512bdc7b95da6 | Add missing dependency to perl-xml-parser (#12903) | var/spack/repos/builtin/packages/perl-xml-parser/package.py | var/spack/repos/builtin/packages/perl-xml-parser/package.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)
#
from spack import *
class PerlXmlParser(PerlPackage):
"""XML::Parser - A perl module for parsing XML documents"""
homepage = "http://search.cpan.org/perldoc/XML::Parser"
url = "http://search.cpan.org/CPAN/authors/id/T/TO/TODDR/XML-Parser-2.44.tar.gz"
version('2.44', 'af4813fe3952362451201ced6fbce379')
depends_on('expat')
depends_on('perl-libwww-perl', type=('build', 'run'))
def configure_args(self):
args = []
p = self.spec['expat'].prefix.lib
args.append('EXPATLIBPATH={0}'.format(p))
p = self.spec['expat'].prefix.include
args.append('EXPATINCPATH={0}'.format(p))
return args
| # 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)
#
from spack import *
class PerlXmlParser(PerlPackage):
"""XML::Parser - A perl module for parsing XML documents"""
homepage = "http://search.cpan.org/perldoc/XML::Parser"
url = "http://search.cpan.org/CPAN/authors/id/T/TO/TODDR/XML-Parser-2.44.tar.gz"
version('2.44', 'af4813fe3952362451201ced6fbce379')
depends_on('expat')
def configure_args(self):
args = []
p = self.spec['expat'].prefix.lib
args.append('EXPATLIBPATH={0}'.format(p))
p = self.spec['expat'].prefix.include
args.append('EXPATINCPATH={0}'.format(p))
return args
| Python | 0.000025 |
26209ff0457c466ee3b95dad8d905edc5220a576 | update class and add additional frame for future actions | bin/slacksible.py | bin/slacksible.py | #! /Users/jhefner/python_dev/uw_python/project/bin/python
from slackclient import SlackClient
import os
import sys
# import logging
# TODOS:
# * create logs:
# 1. Debug log. slacksible_debug.log (10)
# 2. stderr log. slacksible_stderr.log (40)
# 3. usage log. slacksible_metrics.log
# * create slack bot class:
# 1. solve token issue (dont show it in code)
# TODO: change token to non-test token
# TODO: move token out to env var or file and loaded during app boot
# Example: os.environ[" ENV VAR TOKEN ALREADY LOADED "]
token = "xoxb-168959872961-Clds2jLyYvCQY3syhyEUSjKs"
sc = SlackClient(token)
class slacksible():
"""
Ansible slack bot class
"""
def __init__(self, args, **kwargs):
self.token = os.environ["slacksible_token"]
# TODO: find a better way, this is ugly as hell
# this finds one directory up from where the script is being run in /bin
self.log_path = os.path.split(os.path.abspath(os.path.dirname(sys.argv[0])))[0]+"/logs"
def setup_dirs(self):
'''
Creates directory structure for a working application environment
No return, makes changes directly on the filesystem
'''
if not os.path.exists(self.log_path):
os.makedirs(self.log_path)
# add dir creation to debug log
else:
pass
# TODO: note existence of already existing log dir to debug log.
@staticmethod
def seppuku():
'''
Restart application
'''
# TODO: note restarting of application in debug log
os.execv(__file__, sys.argv)
# TODO: app should restart and not get to next line. raise error if it does
def bot_listen(self):
'''
Connect to slack api and listen to data stream it has access to
'''
if sc.rtm_connect():
print("====================Listening====================") # move to debug log
while True: # TODO: capture exit from this loop in debug log
slack_data = sc.rtm_read() # TODO: multi-thread/async this blocking action.
if slack_data != [] and "text" in slack_data[0]:
# move to debug log
if "message" in slack_data[0]["type"]:
print("--------------------------")
print(slack_data)
if "user" in slack_data[0]:
print("user is:", slack_data[0]["user"])
if "type" in slack_data[0]:
print("type is:", slack_data[0]["type"])
if "text" in slack_data[0]:
print("message is:", slack_data[0]["text"])
if "channel" in slack_data[0]:
print("channel is:", slack_data[0]["channel"])
else:
print("Connection failed to Slack") # move to error log
def bot_query_ARA(self):
# TODO: create cli parser for reading existing runs
pass
def bot_query_ansible(self):
# TODO:
pass
def collect_usage_metrics(self):
# TODO: capture commands directed at bot and sort by order of usage.
pass
# simple api test for bot
def test():
sc.api_call(
"chat.postMessage",
channel="#slack_bot",
text="Hello from Python! :tada:"
)
def main():
print(os.path.split(os.path.abspath(os.path.dirname(sys.argv[0])))[0]+"/logs")
if __name__ == '__main__':
main() | #! /Users/jhefner/python_dev/uw_python/project/bin/python
from slackclient import SlackClient
import os
import sys
# import logging
# TODOS:
# * create logs:
# 1. Debug log. slacksible_debug.log (10)
# 2. stderr log. slacksible_stderr.log (40)
def test():
sc.api_call(
"chat.postMessage",
channel="#slack_bot_bullshit",
text="Hello from Python! :tada:"
)
# TODO: change token to non-test token
# TODO: move token out to env var or file and loaded during app boot
# Example: os.environ[" ENV VAR TOKEN ALREADY LOADED "]
token = "xoxb-168959872961-Clds2jLyYvCQY3syhyEUSjKs"
sc = SlackClient(token)
class slacksible():
"""
"""
def __init__(self, args, **kwargs):
self.token = os.environ["slacksible_token"]
# TODO: find a better way
self.log_path = os.path.split(os.path.abspath(os.path.dirname(sys.argv[0])))[0]
def main():
if sc.rtm_connect(): # TODO: multi-thread this blocking action.
print("====================Listening====================") # move to debug log
while True:
slack_data = sc.rtm_read()
if slack_data != [] and "text" in slack_data[0]:
# move to debug log
if "message" in slack_data[0]["type"]:
print("--------------------------")
print(slack_data)
if "user" in slack_data[0]:
print("user is:", slack_data[0]["user"])
if "type" in slack_data[0]:
print("type is:", slack_data[0]["type"])
if "text" in slack_data[0]:
print("message is:", slack_data[0]["text"])
if "channel" in slack_data[0]:
print("channel is:", slack_data[0]["channel"])
else:
print("Connection failed to Slack") # move to error log
if __name__ == '__main__':
main() | Python | 0 |
0153a20201cfeff37512733b2e85106f69ba5f47 | replace use of 'unicode' builtin | monasca_log_api/app/base/model.py | monasca_log_api/app/base/model.py | # Copyright 2016 FUJITSU LIMITED
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_utils import timeutils
import six
from monasca_common.rest import utils as rest_utils
def serialize_envelope(envelope):
"""Returns json representation of an envelope.
:return: json object of envelope
:rtype: six.text_type
"""
json = rest_utils.as_json(envelope, ensure_ascii=False)
if six.PY2:
raw = six.text_type(json.replace(r'\\', r'\\\\'), encoding='utf-8',
errors='replace')
else:
raw = json
return raw
class LogEnvelopeException(Exception):
pass
class Envelope(dict):
def __init__(self, log, meta):
if not log:
error_msg = 'Envelope cannot be created without log'
raise LogEnvelopeException(error_msg)
if 'tenantId' not in meta or not meta.get('tenantId'):
error_msg = 'Envelope cannot be created without tenant'
raise LogEnvelopeException(error_msg)
creation_time = self._get_creation_time()
super(Envelope, self).__init__(
log=log,
creation_time=creation_time,
meta=meta
)
@staticmethod
def _get_creation_time():
return timeutils.utcnow_ts()
@classmethod
def new_envelope(cls, log, tenant_id, region, dimensions=None):
"""Creates new log envelope
Log envelope is combined ouf of following properties
* log - dict
* creation_time - timestamp
* meta - meta block
Example output json would like this:
.. code-block:: json
{
"log": {
"message": "Some message",
"dimensions": {
"hostname": "devstack"
}
},
"creation_time": 1447834886,
"meta": {
"tenantId": "e4bd29509eda473092d32aadfee3e7b1",
"region": "pl"
}
}
:param dict log: original log element (containing message and other
params
:param str tenant_id: tenant id to be put in meta field
:param str region: region to be put in meta field
:param dict dimensions: additional dimensions to be appended to log
object dimensions
"""
if dimensions:
log['dimensions'].update(dimensions)
log_meta = {
'region': region,
'tenantId': tenant_id
}
return cls(log, log_meta)
@property
def log(self):
return self.get('log', None)
@property
def creation_time(self):
return self.get('creation_time', None)
@property
def meta(self):
return self.get('meta', None)
| # Copyright 2016 FUJITSU LIMITED
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_utils import timeutils
import six
from monasca_common.rest import utils as rest_utils
def serialize_envelope(envelope):
"""Returns json representation of an envelope.
:return: json object of envelope
:rtype: six.text_type
"""
json = rest_utils.as_json(envelope, ensure_ascii=False)
if six.PY2:
raw = unicode(json.replace(r'\\', r'\\\\'), encoding='utf-8',
errors='replace')
else:
raw = json
return raw
class LogEnvelopeException(Exception):
pass
class Envelope(dict):
def __init__(self, log, meta):
if not log:
error_msg = 'Envelope cannot be created without log'
raise LogEnvelopeException(error_msg)
if 'tenantId' not in meta or not meta.get('tenantId'):
error_msg = 'Envelope cannot be created without tenant'
raise LogEnvelopeException(error_msg)
creation_time = self._get_creation_time()
super(Envelope, self).__init__(
log=log,
creation_time=creation_time,
meta=meta
)
@staticmethod
def _get_creation_time():
return timeutils.utcnow_ts()
@classmethod
def new_envelope(cls, log, tenant_id, region, dimensions=None):
"""Creates new log envelope
Log envelope is combined ouf of following properties
* log - dict
* creation_time - timestamp
* meta - meta block
Example output json would like this:
.. code-block:: json
{
"log": {
"message": "Some message",
"dimensions": {
"hostname": "devstack"
}
},
"creation_time": 1447834886,
"meta": {
"tenantId": "e4bd29509eda473092d32aadfee3e7b1",
"region": "pl"
}
}
:param dict log: original log element (containing message and other
params
:param str tenant_id: tenant id to be put in meta field
:param str region: region to be put in meta field
:param dict dimensions: additional dimensions to be appended to log
object dimensions
"""
if dimensions:
log['dimensions'].update(dimensions)
log_meta = {
'region': region,
'tenantId': tenant_id
}
return cls(log, log_meta)
@property
def log(self):
return self.get('log', None)
@property
def creation_time(self):
return self.get('creation_time', None)
@property
def meta(self):
return self.get('meta', None)
| Python | 0.000617 |
ee75d9530bb6b9e409449c8e9d5ffb3a3578f5d8 | Fix not coloring for new repositories | bin/commands/stateextensions/status.py | bin/commands/stateextensions/status.py | import os
import re
import subprocess
from colorama import Fore
def title():
return 'status'
def accent(**kwargs):
new_repository = kwargs.get('new_repository', False)
show_color = kwargs.get('show_color', 'always')
if new_repository:
status_title = '{no_color}({green}master{no_color})'.format(no_color=Fore.RESET, green=Fore.GREEN)
else:
status_title = subprocess.check_output(
('git', '-c', 'color.status=' + show_color, 'status', '--branch', '--short')
).splitlines()[0]
status_title = re.match('.*##.*? (.*)', status_title).group(1)
status_title = '{}({})'.format(Fore.RESET, status_title)
return status_title
def get(**kwargs):
new_repository = kwargs.get('new_repository', False)
show_color = kwargs.get('show_color', 'always')
show_clean_message = kwargs.get('show_clean_message', True)
if new_repository:
# check if status is empty
status_output = subprocess.check_output(['git', '-c', 'color.status=' + show_color, 'status', '--short'])
if not status_output:
status_output = 'Empty repository'
else:
status_output = subprocess.check_output(['git', '-c', 'color.status=' + show_color, 'status', '--short', '--untracked-files=all'])
if not status_output and show_clean_message:
status_output = 'nothing to commit, working directory is clean' + os.linesep
return status_output
| import os
import re
import subprocess
from colorama import Fore
def title():
return 'status'
def accent(**kwargs):
new_repository = kwargs.get('new_repository', False)
show_color = kwargs.get('show_color', 'always')
if new_repository:
status_title = '{no_color}({green}master{no_color})'.format(no_color=Fore.RESET, green=Fore.GREEN)
else:
status_title = subprocess.check_output(
('git', '-c', 'color.status=' + show_color, 'status', '--branch', '--short')
).splitlines()[0]
status_title = re.match('.*##.*? (.*)', status_title).group(1)
status_title = '{}({})'.format(Fore.RESET, status_title)
return status_title
def get(**kwargs):
new_repository = kwargs.get('new_repository', False)
show_color = kwargs.get('show_color', 'always')
show_clean_message = kwargs.get('show_clean_message', True)
if new_repository:
# check if status is empty
status_output = subprocess.check_output(['git', 'status', '--short'])
if not status_output:
status_output = 'Empty repository'
else:
status_output = subprocess.check_output(['git', '-c', 'color.status=' + show_color, 'status', '--short', '--untracked-files=all'])
if not status_output and show_clean_message:
status_output = 'nothing to commit, working directory is clean' + os.linesep
return status_output
| Python | 0.000001 |
6258026193d52de5168007b833a2fd35c807b734 | fix main to pass until further dev is done | bin/slacksible.py | bin/slacksible.py | #! /Users/jhefner/python_dev/uw_python/project/bin/python
from slackclient import SlackClient
import os
import sys
# import logging
# TODOS:
# * create logs:
# 1. Debug log. slacksible_debug.log (10)
# 2. stderr log. slacksible_stderr.log (40)
# 3. usage log. slacksible_metrics.log
# * create slack bot class:
# 1. solve token issue (dont show it in code)
# TODO: change token to non-test token
# TODO: move token out to env var or file and loaded during app boot
# Example: os.environ[" ENV VAR TOKEN ALREADY LOADED "]
token = "xoxb-168959872961-Clds2jLyYvCQY3syhyEUSjKs"
sc = SlackClient(token)
class slacksible():
"""
Ansible slack bot class
"""
def __init__(self, args, **kwargs):
self.token = os.environ["slacksible_token"]
# TODO: find a better way, this is ugly as hell
# this finds one directory up from where the script is being run in /bin
self.log_path = os.path.split(os.path.abspath(os.path.dirname(sys.argv[0])))[0]+"/logs"
def setup_dirs(self):
'''
Creates directory structure for a working application environment
No return, makes changes directly on the filesystem
'''
if not os.path.exists(self.log_path):
os.makedirs(self.log_path)
# add dir creation to debug log
else:
pass
# TODO: note existence of already existing log dir to debug log.
@staticmethod
def seppuku():
'''
Restart application
'''
# TODO: note restarting of application in debug log
os.execv(__file__, sys.argv)
# TODO: app should restart and not get to next line. raise error if it does
def bot_listen(self):
'''
Connect to slack api and listen to data stream it has access to
'''
if sc.rtm_connect():
print("====================Listening====================") # move to debug log
while True: # TODO: capture exit from this loop in debug log
slack_data = sc.rtm_read() # TODO: multi-thread/async this blocking action.
if slack_data != [] and "text" in slack_data[0]:
# move to debug log
if "message" in slack_data[0]["type"]:
print("--------------------------")
print(slack_data)
if "user" in slack_data[0]:
print("user is:", slack_data[0]["user"])
if "type" in slack_data[0]:
print("type is:", slack_data[0]["type"])
if "text" in slack_data[0]:
print("message is:", slack_data[0]["text"])
if "channel" in slack_data[0]:
print("channel is:", slack_data[0]["channel"])
else:
print("Connection failed to Slack") # move to error log
def bot_query_ARA(self):
# TODO: create cli parser for reading existing runs
pass
def bot_query_ansible(self):
# TODO:
pass
def collect_usage_metrics(self):
# TODO: capture commands directed at bot and sort by order of usage.
pass
# simple api test for bot
def test():
sc.api_call(
"chat.postMessage",
channel="#slack_bot",
text="Hello from Python! :tada:"
)
def main():
pass
if __name__ == '__main__':
main() | #! /Users/jhefner/python_dev/uw_python/project/bin/python
from slackclient import SlackClient
import os
import sys
# import logging
# TODOS:
# * create logs:
# 1. Debug log. slacksible_debug.log (10)
# 2. stderr log. slacksible_stderr.log (40)
# 3. usage log. slacksible_metrics.log
# * create slack bot class:
# 1. solve token issue (dont show it in code)
# TODO: change token to non-test token
# TODO: move token out to env var or file and loaded during app boot
# Example: os.environ[" ENV VAR TOKEN ALREADY LOADED "]
token = "xoxb-168959872961-Clds2jLyYvCQY3syhyEUSjKs"
sc = SlackClient(token)
class slacksible():
"""
Ansible slack bot class
"""
def __init__(self, args, **kwargs):
self.token = os.environ["slacksible_token"]
# TODO: find a better way, this is ugly as hell
# this finds one directory up from where the script is being run in /bin
self.log_path = os.path.split(os.path.abspath(os.path.dirname(sys.argv[0])))[0]+"/logs"
def setup_dirs(self):
'''
Creates directory structure for a working application environment
No return, makes changes directly on the filesystem
'''
if not os.path.exists(self.log_path):
os.makedirs(self.log_path)
# add dir creation to debug log
else:
pass
# TODO: note existence of already existing log dir to debug log.
@staticmethod
def seppuku():
'''
Restart application
'''
# TODO: note restarting of application in debug log
os.execv(__file__, sys.argv)
# TODO: app should restart and not get to next line. raise error if it does
def bot_listen(self):
'''
Connect to slack api and listen to data stream it has access to
'''
if sc.rtm_connect():
print("====================Listening====================") # move to debug log
while True: # TODO: capture exit from this loop in debug log
slack_data = sc.rtm_read() # TODO: multi-thread/async this blocking action.
if slack_data != [] and "text" in slack_data[0]:
# move to debug log
if "message" in slack_data[0]["type"]:
print("--------------------------")
print(slack_data)
if "user" in slack_data[0]:
print("user is:", slack_data[0]["user"])
if "type" in slack_data[0]:
print("type is:", slack_data[0]["type"])
if "text" in slack_data[0]:
print("message is:", slack_data[0]["text"])
if "channel" in slack_data[0]:
print("channel is:", slack_data[0]["channel"])
else:
print("Connection failed to Slack") # move to error log
def bot_query_ARA(self):
# TODO: create cli parser for reading existing runs
pass
def bot_query_ansible(self):
# TODO:
pass
def collect_usage_metrics(self):
# TODO: capture commands directed at bot and sort by order of usage.
pass
# simple api test for bot
def test():
sc.api_call(
"chat.postMessage",
channel="#slack_bot",
text="Hello from Python! :tada:"
)
def main():
print(os.path.split(os.path.abspath(os.path.dirname(sys.argv[0])))[0]+"/logs")
if __name__ == '__main__':
main() | Python | 0 |
c0841b6a38fc042f95f931eead6bc5733d975644 | Update forms.py | cla_public/apps/base/forms.py | cla_public/apps/base/forms.py | # coding: utf-8
"Base forms"
from flask import render_template, current_app, request
from flask_wtf import Form
from flask.ext.babel import lazy_gettext as _, get_translations
from wtforms import TextAreaField, RadioField, SelectMultipleField, StringField, widgets
from wtforms.validators import InputRequired, Length
from cla_public.apps.base.constants import (
FEEL_ABOUT_SERVICE,
HELP_FILLING_IN_FORM,
REASONS_FOR_CONTACTING_CHOICES,
REASONS_FOR_CONTACTING,
)
from cla_public.libs.honeypot import Honeypot
class BabelTranslations(object):
def gettext(self, string):
t = get_translations()
if t is None:
return string
return t.ugettext(string)
def ngettext(self, singular, plural, num):
variables = {"num": num}
t = get_translations()
if t is None:
return (singular if num == 1 else plural) % variables
return t.ungettext(singular, plural, num) % variables
class BabelTranslationsFormMixin(object):
def _get_translations(self):
return BabelTranslations()
_textarea_length_validator = Length(max=1000, message=u"Field cannot contain more than %(max)d characters")
class FeedbackForm(Honeypot, BabelTranslationsFormMixin, Form):
referrer = StringField(widget=widgets.HiddenInput())
difficulty = TextAreaField(
label=_(u"Did you have any difficulty using this service? Tell us about the problem."), validators=[_textarea_length_validator]
)
ideas = TextAreaField(
label=_(u"Do you have any ideas for how it could be improved?"), validators=[_textarea_length_validator]
)
feel_about_service = RadioField(
_(u"Overall, how did you feel about the service you received today?"),
choices=FEEL_ABOUT_SERVICE,
validators=[InputRequired()],
)
help_filling_in_form = RadioField(
_(u"Did you have any help filling in this form?"), choices=HELP_FILLING_IN_FORM, validators=[InputRequired()]
)
def api_payload(self):
user_agent = request.headers.get("User-Agent")
comment_body = render_template("emails/zendesk-feedback.txt", form=self, user_agent=user_agent)
environment = current_app.config["CLA_ENV"]
subject = "CLA Public Feedback"
if environment != "prod":
subject = "[TEST] - " + subject
ticket = {
"requester_id": current_app.config["ZENDESK_DEFAULT_REQUESTER"],
"subject": subject,
"comment": {"body": comment_body},
"group_id": 23832817, # CLA Public
"tags": ["feedback", "civil_legal_advice_public"],
"custom_fields": [
{"id": 23791776, "value": user_agent}, # Browser field
{"id": 26047167, "value": self.referrer.data}, # Referrer URL field
],
}
return {"ticket": ticket}
class ReasonsForContactingForm(Honeypot, BabelTranslationsFormMixin, Form):
"""
Interstitial form to ascertain why users are dropping out of
the checker service
"""
referrer = StringField(widget=widgets.HiddenInput())
reasons = SelectMultipleField(
label=_(u"You can select more than one option"),
choices=REASONS_FOR_CONTACTING_CHOICES,
widget=widgets.ListWidget(prefix_label=False),
option_widget=widgets.CheckboxInput(),
)
other_reasons = TextAreaField(label=_(u"Please specify"), validators=[_textarea_length_validator])
REASONS_FOR_CONTACTING_OTHER = REASONS_FOR_CONTACTING.OTHER
def api_payload(self):
return {
"reasons": [{"category": category} for category in self.reasons.data],
"other_reasons": self.other_reasons.data or "",
"user_agent": request.headers.get("User-Agent") or "Unknown",
"referrer": self.referrer.data or "Unknown",
}
| # coding: utf-8
"Base forms"
from flask import render_template, current_app, request
from flask_wtf import Form
from flask.ext.babel import lazy_gettext as _, get_translations
from wtforms import TextAreaField, RadioField, SelectMultipleField, StringField, widgets
from wtforms.validators import InputRequired, Length
from cla_public.apps.base.constants import (
FEEL_ABOUT_SERVICE,
HELP_FILLING_IN_FORM,
REASONS_FOR_CONTACTING_CHOICES,
REASONS_FOR_CONTACTING,
)
from cla_public.libs.honeypot import Honeypot
class BabelTranslations(object):
def gettext(self, string):
t = get_translations()
if t is None:
return string
return t.ugettext(string)
def ngettext(self, singular, plural, num):
variables = {"num": num}
t = get_translations()
if t is None:
return (singular if num == 1 else plural) % variables
return t.ungettext(singular, plural, num) % variables
class BabelTranslationsFormMixin(object):
def _get_translations(self):
return BabelTranslations()
_textarea_length_validator = Length(max=1000, message=u"Field cannot contain more than %(max)d characters")
class FeedbackForm(Honeypot, BabelTranslationsFormMixin, Form):
referrer = StringField(widget=widgets.HiddenInput())
difficulty = TextAreaField(
label=_(u"Did you have any difficulty with this service?"), validators=[_textarea_length_validator]
)
ideas = TextAreaField(
label=_(u"Do you have any ideas for how it could be improved?"), validators=[_textarea_length_validator]
)
feel_about_service = RadioField(
_(u"Overall, how did you feel about the service you received today?"),
choices=FEEL_ABOUT_SERVICE,
validators=[InputRequired()],
)
help_filling_in_form = RadioField(
_(u"Did you have any help filling in this form?"), choices=HELP_FILLING_IN_FORM, validators=[InputRequired()]
)
def api_payload(self):
user_agent = request.headers.get("User-Agent")
comment_body = render_template("emails/zendesk-feedback.txt", form=self, user_agent=user_agent)
environment = current_app.config["CLA_ENV"]
subject = "CLA Public Feedback"
if environment != "prod":
subject = "[TEST] - " + subject
ticket = {
"requester_id": current_app.config["ZENDESK_DEFAULT_REQUESTER"],
"subject": subject,
"comment": {"body": comment_body},
"group_id": 23832817, # CLA Public
"tags": ["feedback", "civil_legal_advice_public"],
"custom_fields": [
{"id": 23791776, "value": user_agent}, # Browser field
{"id": 26047167, "value": self.referrer.data}, # Referrer URL field
],
}
return {"ticket": ticket}
class ReasonsForContactingForm(Honeypot, BabelTranslationsFormMixin, Form):
"""
Interstitial form to ascertain why users are dropping out of
the checker service
"""
referrer = StringField(widget=widgets.HiddenInput())
reasons = SelectMultipleField(
label=_(u"You can select more than one option"),
choices=REASONS_FOR_CONTACTING_CHOICES,
widget=widgets.ListWidget(prefix_label=False),
option_widget=widgets.CheckboxInput(),
)
other_reasons = TextAreaField(label=_(u"Please specify"), validators=[_textarea_length_validator])
REASONS_FOR_CONTACTING_OTHER = REASONS_FOR_CONTACTING.OTHER
def api_payload(self):
return {
"reasons": [{"category": category} for category in self.reasons.data],
"other_reasons": self.other_reasons.data or "",
"user_agent": request.headers.get("User-Agent") or "Unknown",
"referrer": self.referrer.data or "Unknown",
}
| Python | 0 |
c71730cf4f3d8937f0ef1608bf670c28ec44eb0b | Complete and prettified | Challenge3.py | Challenge3.py | # Exercise 3 (and Solution)
# Take a list, say for example this one:
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# and write a program that prints out all the elements of the list that are less than 5.
# Extras:
# Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
# Write this in one line of Python.
# Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.
# OUR PLAN: ask user to give 10 numbers (check to see if it is an actual interger) - for each additional number at it to a list, then check the list to see if any of the numbers are less than 5
print ("\nLet's play a game!\n I'll ask for 10 numbers.")
# create a list and start a counter to get desired numbers
list = []
counter = 0
# ask for 10 numbers and add each one to the empty list
while counter < 10:
user_number = raw_input("Please give a number:\n")
try:
val = int(user_number)
list.append(int(user_number))
counter = counter + 1
# if the value entered is not a number remind people about MATH :)
except ValueError:
print("\nThat's not an int! Pleases use real numbers only. That is REAL numbers from math class.")
# Parot back the number list to the user
print ("\nThanks! Here are your numbers:%s" % (list))
# make a function that can judge which numbers in the list are less than a new value that the user gives
def get_less_than_value():
# get the new value to determine which numbers are less than it
start_value = raw_input("\nNow give a new number and I will tell you which number or numbers in your list are smaller. ")
# to evaluate the numbers they have to be integers so make them so
try:
start_value = int(start_value)
# if the number is not a interger let the user know to try again and recall the function to start again
except ValueError:
print("\nSoooo, remember we need real numbers here. Try again!")
get_less_than_value()
# create the list to hold the values less than
list_less_than = []
# evaluate each number and add it to the empty list
for values in list:
if values < start_value:
list_less_than.append(values)
# print (list_less_than) - use to check if list built correctly
# using the length of list let the user know what numbers are less or if there are no numbers that are less than
if len(list_less_than) < 1 :
print("\nThere are no numbers in your list less than %s " % (start_value))
elif len(list_less_than) > 1 :
print (("\nThe numbers less than are: %s") % (list_less_than))
get_less_than_value()
| # Exercise 3 (and Solution)
# Take a list, say for example this one:
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# and write a program that prints out all the elements of the list that are less than 5.
# Extras:
# Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
# Write this in one line of Python.
# Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.
# OUR PLAN: ask user to give 10 numbers (check to see if it is an actual interger) - for each additional number at it to a list, then check the list to see if any of the numbers are less than 5
print ("\nLet's play a game!\n I'll ask for 10 numbers.")
list = []
counter = 0
while counter < 10:
user_number = raw_input("Please give us a number:\n")
try:
val = int(user_number)
list.append(user_number)
counter = counter + 1
except ValueError:
print("That's not an int! Pleases use real numbers only. That is REAL numbers from math class.")
print list
def get_less_than_value():
start_value = raw_input("\nNow tell me a new number and I will tell you which one in your list are smaller. ")
try:
is_an_integer = int(start_value)
###MAKE A NEW FUNCTION HERE TO SPLIT list based on less than - us a for loop
except ValueError:
print("Soooo, remember we need real numbers here. Try again!")
get_less_than_value()
get_less_than_value() | Python | 0 |
d6f4d9b76d6f12cc9eae1614a33ebb9fa6aa1724 | Fix error handling on missing dest with unarchive | lib/ansible/runner/action_plugins/unarchive.py | lib/ansible/runner/action_plugins/unarchive.py | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2013, Dylan Martin <dmartin@seattlecentral.edu>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
import os
from ansible import utils
import ansible.utils.template as template
from ansible import errors
from ansible.runner.return_data import ReturnData
## fixes https://github.com/ansible/ansible/issues/3518
# http://mypy.pythonblogs.com/12_mypy/archive/1253_workaround_for_python_bug_ascii_codec_cant_encode_character_uxa0_in_position_111_ordinal_not_in_range128.html
import sys
reload(sys)
sys.setdefaultencoding("utf8")
import pipes
class ActionModule(object):
TRANSFERS_FILES = True
def __init__(self, runner):
self.runner = runner
def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
''' handler for file transfer operations '''
# load up options
options = {}
if complex_args:
options.update(complex_args)
options.update(utils.parse_kv(module_args))
source = options.get('src', None)
dest = options.get('dest', None)
copy = utils.boolean(options.get('copy', 'yes'))
if source is None or dest is None:
result = dict(failed=True, msg="src (or content) and dest are required")
return ReturnData(conn=conn, result=result)
dest = os.path.expanduser(dest)
source = template.template(self.runner.basedir, os.path.expanduser(source), inject)
if copy:
if '_original_file' in inject:
source = utils.path_dwim_relative(inject['_original_file'], 'files', source, self.runner.basedir)
else:
source = utils.path_dwim(self.runner.basedir, source)
remote_md5 = self.runner._remote_md5(conn, tmp, dest)
if remote_md5 != '3':
result = dict(failed=True, msg="dest '%s' must be an existing dir" % dest)
return ReturnData(conn=conn, result=result)
if copy:
# transfer the file to a remote tmp location
tmp_src = tmp + 'source'
conn.put_file(source, tmp_src)
# handle diff mode client side
# handle check mode client side
# fix file permissions when the copy is done as a different user
if copy:
if self.runner.sudo and self.runner.sudo_user != 'root':
self.runner._low_level_exec_command(conn, "chmod a+r %s" % tmp_src, tmp)
module_args = "%s src=%s original_basename=%s" % (module_args, pipes.quote(tmp_src), pipes.quote(os.path.basename(source)))
else:
module_args = "%s original_basename=%s" % (module_args, pipes.quote(os.path.basename(source)))
return self.runner._execute_module(conn, tmp, 'unarchive', module_args, inject=inject, complex_args=complex_args)
| # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2013, Dylan Martin <dmartin@seattlecentral.edu>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
import os
from ansible import utils
import ansible.utils.template as template
from ansible import errors
from ansible.runner.return_data import ReturnData
## fixes https://github.com/ansible/ansible/issues/3518
# http://mypy.pythonblogs.com/12_mypy/archive/1253_workaround_for_python_bug_ascii_codec_cant_encode_character_uxa0_in_position_111_ordinal_not_in_range128.html
import sys
reload(sys)
sys.setdefaultencoding("utf8")
import pipes
class ActionModule(object):
TRANSFERS_FILES = True
def __init__(self, runner):
self.runner = runner
def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
''' handler for file transfer operations '''
# load up options
options = {}
if complex_args:
options.update(complex_args)
options.update(utils.parse_kv(module_args))
source = os.path.expanduser(options.get('src', None))
dest = os.path.expanduser(options.get('dest', None))
copy = utils.boolean(options.get('copy', 'yes'))
if source is None or dest is None:
result = dict(failed=True, msg="src (or content) and dest are required")
return ReturnData(conn=conn, result=result)
source = template.template(self.runner.basedir, source, inject)
if copy:
if '_original_file' in inject:
source = utils.path_dwim_relative(inject['_original_file'], 'files', source, self.runner.basedir)
else:
source = utils.path_dwim(self.runner.basedir, source)
remote_md5 = self.runner._remote_md5(conn, tmp, dest)
if remote_md5 != '3':
result = dict(failed=True, msg="dest '%s' must be an existing dir" % dest)
return ReturnData(conn=conn, result=result)
if copy:
# transfer the file to a remote tmp location
tmp_src = tmp + 'source'
conn.put_file(source, tmp_src)
# handle diff mode client side
# handle check mode client side
# fix file permissions when the copy is done as a different user
if copy:
if self.runner.sudo and self.runner.sudo_user != 'root':
self.runner._low_level_exec_command(conn, "chmod a+r %s" % tmp_src, tmp)
module_args = "%s src=%s original_basename=%s" % (module_args, pipes.quote(tmp_src), pipes.quote(os.path.basename(source)))
else:
module_args = "%s original_basename=%s" % (module_args, pipes.quote(os.path.basename(source)))
return self.runner._execute_module(conn, tmp, 'unarchive', module_args, inject=inject, complex_args=complex_args)
| Python | 0 |
d4ee599fe9cd88315d129e036fb034111bfc2272 | Add types to common url parameters (#50000) | lib/ansible/utils/module_docs_fragments/url.py | lib/ansible/utils/module_docs_fragments/url.py | # -*- coding: utf-8 -*-
# Copyright: (c) 2018, John Barker <gundalow@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
# Standard files documentation fragment
DOCUMENTATION = r'''
options:
url:
description:
- HTTP, HTTPS, or FTP URL in the form (http|https|ftp)://[user[:pass]]@host.domain[:port]/path
type: str
force:
description:
- If C(yes) do not get a cached copy.
aliases:
- thirsty
type: bool
default: no
http_agent:
description:
- Header to identify as, generally appears in web server logs.
type: str
default: ansible-httpget
use_proxy:
description:
- If C(no), it will not use a proxy, even if one is defined in an environment variable on the target hosts.
type: bool
default: yes
validate_certs:
description:
- If C(no), SSL certificates will not be validated.
- This should only be used on personally controlled sites using self-signed certificates.
type: bool
default: yes
url_username:
description:
- The username for use in HTTP basic authentication.
- This parameter can be used without I(url_password) for sites that allow empty passwords
type: str
url_password:
description:
- The password for use in HTTP basic authentication.
- If the I(url_username) parameter is not specified, the I(url_password) parameter will not be used.
type: str
force_basic_auth:
description:
- Credentials specified with I(url_username) and I(url_password) should be passed in HTTP Header.
type: bool
default: no
client_cert:
description:
- PEM formatted certificate chain file to be used for SSL client authentication.
- This file can also include the key as well, and if the key is included, C(client_key) is not required.
type: str
client_key:
description:
- PEM formatted file that contains your private key to be used for SSL client authentication.
- If C(client_cert) contains both the certificate and key, this option is not required.
type: str
'''
| # (c) 2018, John Barker<gundalow@redhat.com>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
class ModuleDocFragment(object):
# Standard files documentation fragment
DOCUMENTATION = """
options:
url:
description:
- HTTP, HTTPS, or FTP URL in the form (http|https|ftp)://[user[:pass]]@host.domain[:port]/path
force:
description:
- If C(yes) do not get a cached copy.
aliases:
- thirsty
type: bool
default: no
http_agent:
description:
- Header to identify as, generally appears in web server logs.
default: ansible-httpget
use_proxy:
description:
- If C(no), it will not use a proxy, even if one is defined in an environment variable on the target hosts.
type: bool
default: yes
validate_certs:
description:
- If C(no), SSL certificates will not be validated. This should only be used
on personally controlled sites using self-signed certificates.
default: yes
type: bool
url_username:
description:
- The username for use in HTTP basic authentication.
- This parameter can be used without I(url_password) for sites that allow empty passwords
url_password:
description:
- The password for use in HTTP basic authentication.
- If the I(url_username) parameter is not specified, the I(url_password) parameter will not be used.
force_basic_auth:
description:
- Credentials specified with I(url_username) and I(url_password) should be passed in HTTP Header.
default: no
type: bool
client_cert:
description:
- PEM formatted certificate chain file to be used for SSL client
authentication. This file can also include the key as well, and if
the key is included, C(client_key) is not required.
client_key:
description:
- PEM formatted file that contains your private key to be used for SSL
client authentication. If C(client_cert) contains both the certificate
and key, this option is not required.
"""
| Python | 0 |
e9df15b0f084ed9e026a5de129b109a3c546f99c | Handle comments in parse tree. | src/libeeyore/parse_tree_to_cpp.py | src/libeeyore/parse_tree_to_cpp.py | from itertools import imap
import builtins
from cpp.cpprenderer import EeyCppRenderer
from environment import EeyEnvironment
from functionvalues import *
from languagevalues import *
from values import *
def parse_tree_string_to_values( string ):
return eval( string )
def remove_comments( ln ):
i = ln.find( "#" )
if i != -1:
return ln[:i]
else:
return ln
def non_empty_line( ln ):
return ( ln.strip() != "" )
def parse_tree_to_cpp( parse_tree_in_fl, cpp_out_fl ):
env = EeyEnvironment( EeyCppRenderer() )
builtins.add_builtins( env )
values = ( parse_tree_string_to_values( ln ) for ln in
filter( non_empty_line, imap( remove_comments, parse_tree_in_fl ) ) )
cpp_out_fl.write( env.render_exe( values ) )
|
import builtins
from cpp.cpprenderer import EeyCppRenderer
from environment import EeyEnvironment
from values import *
def parse_tree_string_to_values( string ):
return eval( string )
def non_empty_line( ln ):
return ( ln.strip() != "" )
def parse_tree_to_cpp( parse_tree_in_fl, cpp_out_fl ):
env = EeyEnvironment( EeyCppRenderer() )
builtins.add_builtins( self )
values = ( parse_tree_string_to_values( ln ) for ln in
filter( non_empty_line, parse_tree_in_fl ) )
cpp_out_fl.write( env.render_exe( values ) )
| Python | 0 |
7d09f713b929f60cd62ce48de2e2a8f27aa4de45 | Fix unit tests. | Orange/tests/test_random_forest.py | Orange/tests/test_random_forest.py | import unittest
import Orange.data
import Orange.classification.random_forest as rf
from Orange.evaluation import scoring, testing
class RandomForestTest(unittest.TestCase):
def test_RandomForest(self):
table = Orange.data.Table('iris')
forest = rf.RandomForestLearner()
results = testing.CrossValidation(table, [forest], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.9)
self.assertLess(ca, 0.99)
def test_predict_single_instance(self):
table = Orange.data.Table('iris')
forest = rf.RandomForestLearner()
c = forest(table)
for ins in table:
c(ins)
val, prob = c(ins, c.ValueProbs)
def test_predict_table(self):
table = Orange.data.Table('iris')
forest = rf.RandomForestLearner()
c = forest(table)
c(table)
vals, probs = c(table, c.ValueProbs)
def test_predict_numpy(self):
table = Orange.data.Table('iris')
forest = rf.RandomForestLearner()
c = forest(table)
c(table.X)
vals, probs = c(table.X, c.ValueProbs)
| import unittest
import Orange.data
import Orange.classification.random_forest as rf
from Orange.evaluation import scoring, testing
class RandomForestTest(unittest.TestCase):
def test_RandomForest(self):
table = Orange.data.Table('titanic')
forest = rf.RandomForestLearner()
results = testing.CrossValidation(table[::20], [forest], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.7)
self.assertLess(ca, 0.9)
def test_predict_single_instance(self):
table = Orange.data.Table('titanic')
forest = rf.RandomForestLearner()
c = forest(table)
for ins in table[::20]:
c(ins)
val, prob = c(ins, c.ValueProbs)
def test_predict_table(self):
table = Orange.data.Table('titanic')
forest = rf.RandomForestLearner()
c = forest(table)
table = table[::20]
c(table)
vals, probs = c(table, c.ValueProbs)
def test_predict_numpy(self):
table = Orange.data.Table('titanic')
forest = rf.RandomForestLearner()
c = forest(table)
X = table.X[::20]
c(X)
vals, probs = c(X, c.ValueProbs) | Python | 0 |
7041d2649b08d961cf5c7c4c663282e55526f2eb | Update pictures.py | cogs/pictures.py | cogs/pictures.py | from discord.ext import commands
import copy
import requests
class Pic:
"""Мемасики и просто картинки."""
def __init__(self, bot):
self.bot = bot
self.pic_dir = 'pictures/'
self.pic_dict = {}
self.update_pics()
def update_pics(self):
file_list = self.bot.pycopy.list_files(self.pic_dir)
for file_name in file_list:
self.pic_dict[file_name.split('.')[0]] = file_name
self.pic.aliases = list(self.pic_dict.values())
@commands.group(pass_context=True, aliases=[])
async def pic(self, ctx):
"""База картинок, мемесов etc."""
if ctx.invoked_with in self.pic_dict:
file = self.bot.pycopy.get_file(self.pic_path + self.pic_dict[ctx.invoked_with])
await self.bot.upload(file, self.pic_dict[ctx.invoked_with])
elif ctx.invoked_subcommand is None:
msg = copy.copy(ctx.message)
msg.content = ctx.prefix + 'help pic'
await self.bot.process_commands(msg)
@pic.command()
async def update(self):
"""Обновить список картиночек."""
self.update_pics()
await self.bot.say("Найдено {} картиночек.".format(len(self.pic_dict)))
@pic.command()
async def list(self):
"""Вывести список картиночек."""
pic_list = ''
id = 1
for pic in self.pic_dict:
pic_list += "{}. {}\n".format(id, pic)
id += 1
if len(pic_list) > 1800:
await self.bot.say(pic_list)
pic_list = ''
await self.bot.say(pic_list)
def setup(bot):
bot.add_cog(Pic(bot))
| from discord.ext import commands
import copy
import requests
class Pic:
"""Мемасики и просто картинки."""
def __init__(self, bot):
self.bot = bot
self.pic_dir = 'pictures/'
self.pic_dict = {}
self.update_pics()
def update_pics(self):
file_list = self.bot.pycopy.list_files(self.pic_dir)
for file_name in file_list:
self.pic_dict[file_name.split('.')[0]] = file_name
self.pic.aliases = list(self.pic_dict.values())
@commands.group(pass_context=True, aliases=[])
async def pic(self, ctx):
"""База картинок, мемесов etc."""
if ctx.invoked_with in self.pic_dict:
url = self.bot.pycopy.direct_link(self.pic_path + self.pic_dict[ctx.invoked_with])
r = requests.get(url, stream=True)
if r.status_code == 200:
r.raw.decode_content = True
await self.bot.upload(r.raw, self.pic_dict[ctx.invoked_with])
elif ctx.invoked_subcommand is None:
msg = copy.copy(ctx.message)
msg.content = ctx.prefix + 'help pic'
await self.bot.process_commands(msg)
@pic.command()
async def update(self):
"""Обновить список картиночек."""
self.update_pics()
await self.bot.say("Найдено {} картиночек.".format(len(self.pic_dict)))
@pic.command()
async def list(self):
"""Вывести список картиночек."""
pic_list = ''
id = 1
for pic in self.pic_dict:
pic_list += "{}. {}\n".format(id, pic)
id += 1
if len(pic_list) > 1800:
await self.bot.say(pic_list)
pic_list = ''
await self.bot.say(pic_list)
def setup(bot):
bot.add_cog(Pic(bot))
| Python | 0 |
25f3da8409a6fe31eded302cd14a78b575ff2399 | Please lxml | cogs/saucenao.py | cogs/saucenao.py | from discord.ext import commands
from discord.ext.commands import Cog
from lxml import etree
from bot import BeattieBot
from context import BContext
class SauceNao(Cog):
sauce_url = "https://saucenao.com/search.php"
def __init__(self, bot: BeattieBot):
self.session = bot.session
self.parser = etree.HTMLParser()
@commands.command(aliases=["sauce"])
async def saucenao(self, ctx: BContext, *, link: str = "") -> None:
"""Find the source of a linked or attached image using saucenao."""
async with ctx.typing():
if not link:
if len(ctx.message.attachments) == 1:
link = ctx.message.attachments[0].url
else:
raise commands.BadArgument
elif ctx.message.attachments:
raise commands.BadArgument
link = link.strip("<>")
payload = {"url": link}
async with self.session.post(self.sauce_url, data=payload) as resp:
root = etree.fromstring(await resp.text(), self.parser)
results = root.xpath('.//div[@class="result"]')
sim_percent = 0.0
if len(results):
similarity = root.find(".//div[@class='resultsimilarityinfo']").text
sim_percent = float(similarity[:-1])
if not results or sim_percent <= 60:
await ctx.send("No sauce found.")
else:
result = results[0]
if (
booru_link := result.find('.//div[@class="resultmiscinfo"]/a')
) is not None:
link = f"<{booru_link.get('href')}>"
elif (
source_link := result.find('.//div[@class="resultcontentcolumn"]/a')
) is not None:
link = f"<{source_link.get('href')}>"
else:
link = "with no author information."
await ctx.send(f"Sauce found ({similarity}) {link}")
@saucenao.error
async def saucenao_error(self, ctx: BContext, e: Exception) -> None:
if isinstance(e, commands.BadArgument):
await ctx.send("Please include a link or attach a single image.")
else:
await ctx.bot.handle_error(ctx, e)
def setup(bot: BeattieBot) -> None:
bot.add_cog(SauceNao(bot))
| from discord.ext import commands
from discord.ext.commands import Cog
from lxml import etree
from bot import BeattieBot
from context import BContext
class SauceNao(Cog):
sauce_url = "https://saucenao.com/search.php"
def __init__(self, bot: BeattieBot):
self.session = bot.session
self.parser = etree.HTMLParser()
@commands.command(aliases=["sauce"])
async def saucenao(self, ctx: BContext, *, link: str = "") -> None:
"""Find the source of a linked or attached image using saucenao."""
async with ctx.typing():
if not link:
if len(ctx.message.attachments) == 1:
link = ctx.message.attachments[0].url
else:
raise commands.BadArgument
elif ctx.message.attachments:
raise commands.BadArgument
link = link.strip("<>")
payload = {"url": link}
async with self.session.post(self.sauce_url, data=payload) as resp:
root = etree.fromstring(await resp.text(), self.parser)
results = root.xpath('.//div[@class="result"]')
sim_percent = 0.0
if results:
similarity = root.find(".//div[@class='resultsimilarityinfo']").text
sim_percent = float(similarity[:-1])
if not results or sim_percent <= 60:
await ctx.send("No sauce found.")
else:
result = results[0]
if (
booru_link := result.find('.//div[@class="resultmiscinfo"]/a')
) is not None:
link = f"<{booru_link.get('href')}>"
elif (
source_link := result.find('.//div[@class="resultcontentcolumn"]/a')
) is not None:
link = f"<{source_link.get('href')}>"
else:
link = "with no author information."
await ctx.send(f"Sauce found ({similarity}) {link}")
@saucenao.error
async def saucenao_error(self, ctx: BContext, e: Exception) -> None:
if isinstance(e, commands.BadArgument):
await ctx.send("Please include a link or attach a single image.")
else:
await ctx.bot.handle_error(ctx, e)
def setup(bot: BeattieBot) -> None:
bot.add_cog(SauceNao(bot))
| Python | 0.998141 |
a6a78260b47f3a632564e7a80ce25b3b75e242e9 | Add sample code for API key authentication | examples/authentication.py | examples/authentication.py | '''A basic example of authentication requests within a hug API'''
import hug
# Several authenticators are included in hug/authentication.py. These functions
# accept a verify_user function, which can be either an included function (such
# as the basic username/bassword function demonstrated below), or logic of your
# own. Verification functions return an object to store in the request context
# on successful authentication. Naturally, this is a trivial demo, and a much
# more robust verification function is recommended. This is for strictly
# illustrative purposes.
authentication = hug.authentication.basic(hug.authentication.verify('User1', 'mypassword'))
@hug.get('/public')
def public_api_call():
return "Needs no authentication"
# Note that the logged in user can be accessed via a built-in directive.
# Directives can provide computed input parameters via an abstraction
# layer so as not to clutter your API functions with access to the raw
# request object.
@hug.get('/authenticated', requires=authentication)
def basic_auth_api_call(user: hug.directives.user):
return 'Successfully authenticated with user: {0}'.format(user)
# Here is a slightly less trivial example of how authentication might
# look in an API that uses keys.
# First, the user object stored in the context need not be a string,
# but can be any Python object.
class APIUser(object):
"""A minimal example of a rich User object"""
def __init__(self, user_id, api_key):
self.user_id = user_id
self.api_key = api_key
def api_key_verify(api_key):
magic_key = '5F00832B-DE24-4CAF-9638-C10D1C642C6C' # Obviously, this would hit your database
if api_key == magic_key:
# Success!
return APIUser('user_foo', api_key)
else:
# Invalid key
return None
api_key_authentication = hug.authentication.api_key(api_key_verify)
@hug.get('/key_authenticated', requires=api_key_authentication)
def basic_auth_api_call(user: hug.directives.user):
return 'Successfully authenticated with user: {0}'.format(user.user_id)
| '''A basic example of authentication requests within a hug API'''
import hug
# Several authenticators are included in hug/authentication.py. These functions
# accept a verify_user function, which can be either an included function (such
# as the basic username/bassword function demonstrated below), or logic of your
# own. Verification functions return an object to store in the request context
# on successful authentication. Naturally, this is a trivial demo, and a much
# more robust verification function is recommended. This is for strictly
# illustrative purposes.
authentication = hug.authentication.basic(hug.authentication.verify('User1', 'mypassword'))
# Note that the logged in user can be accessed via a built-in directive.
# Directives can provide computed input parameters via an abstraction
# layer so as not to clutter your API functions with access to the raw
# request object.
@hug.get('/authenticated', requires=authentication)
def api_call1(user: hug.directives.user):
return "Successfully authenticated with user: {0}".format(user)
@hug.get('/public')
def api_call2():
return "Needs no authentication"
| Python | 0 |
73fc80dd8ece1f5ecb1fb529412cd97a804ffccd | Test fetch_emails_from_wiki command | remo/profiles/tests/test_commands.py | remo/profiles/tests/test_commands.py | import os
import tempfile
import json
import requests
import fudge
from django.conf import settings
from django.core import management, mail
from django.contrib.auth.models import User
from nose.tools import eq_, raises
from test_utils import TestCase
class CreateUserTest(TestCase):
"""
Tests for create_user management command
"""
def setUp(self):
# check if actual email sending is enabled and if yes do not run
if settings.EMAIL_BACKEND != 'django.core.mail.backends.locmem.EmailBackend':
raise ValueError("Please change local.py to avoid "
"sending testing emails")
# create a temporaty file with emails
self.TEST_EMAILS = ["foo@example.com", "bar@example.com",
"bogusemail.com"]
self.NO_VALID_EMAILS = 2
self.temp_file = tempfile.NamedTemporaryFile(delete=False)
for email in self.TEST_EMAILS:
self.temp_file.write(email)
self.temp_file.write('\n')
self.temp_file.close()
def test_command_without_input_file(self):
args = []
opts = {}
self.assertRaises(SystemExit, management.call_command,
'create_users', *args, **opts)
def test_command_input_file_no_email(self):
args = [self.temp_file.name]
opts = {'email':False}
management.call_command('create_users', *args, **opts)
eq_(len(mail.outbox), 0)
eq_(User.objects.count(), self.NO_VALID_EMAILS)
def test_command_input_file_send_email(self):
args = [self.temp_file.name]
opts = {'email':True}
management.call_command('create_users', *args, **opts)
eq_(len(mail.outbox), self.NO_VALID_EMAILS)
eq_(User.objects.count(), self.NO_VALID_EMAILS)
def tearDown(self):
os.unlink(self.temp_file.name)
class FetchEmailsFromWikiTest(TestCase):
"""
Tests for fetch_emails_from_wiki management command
"""
@raises(SystemExit)
@fudge.patch('requests.get')
def test_command_with_connection_error(self, fake_requests_obj):
(fake_requests_obj.expects_call().raises(requests.ConnectionError))
management.call_command('fetch_emails_from_wiki')
@raises(SystemExit)
@fudge.patch('requests.get')
def test_command_with_invalid_code(self, fake_requests_obj):
request = requests.Request()
request.status_code=404
request.text='foo'
(fake_requests_obj.expects_call().returns(request))
management.call_command('fetch_emails_from_wiki')
@raises(SystemExit)
@fudge.patch('requests.get')
def test_command_with_bogus_data(self, fake_requests_obj):
request = requests.Request()
request.status_code = 200
request.text='foo'
(fake_requests_obj.expects_call().returns(request))
management.call_command('fetch_emails_from_wiki')
@fudge.patch('requests.get')
def test_command_with_valid_data(self, fake_requests_obj):
request = requests.Request()
request.status_code = 200
request.text = json.dumps(
{'ask': {
'query': {
},
'results': {
'items': [
{
'properties':{
'bugzillamail':'foo@example.com',
},
"uri": "https:\/\/wiki.mozilla.org\/index.php?title=User:fooexample",
},
{
'properties':{
'bugzillamail':'test@example.com',
},
"uri": "https:\/\/wiki.mozilla.org\/index.php?title=User:testexample",
},
],
}
}
})
(fake_requests_obj.expects_call().returns(request))
management.call_command('fetch_emails_from_wiki')
| import os
import tempfile
from django.conf import settings
from django.core import management, mail
from django.contrib.auth.models import User
from nose.tools import eq_
from test_utils import TestCase
class CreateUserTest(TestCase):
"""
Create tests for create_user management command
"""
def setUp(self):
# check if actual email sending is enabled and if yes do not run
if settings.EMAIL_BACKEND != 'django.core.mail.backends.locmem.EmailBackend':
raise ValueError("Please change local.py to avoid "
"sending testing emails")
# create a temporaty file with emails
self.TEST_EMAILS = ["foo@example.com", "bar@example.com",
"bogusemail.com"]
self.NO_VALID_EMAILS = 2
self.temp_file = tempfile.NamedTemporaryFile(delete=False)
for email in self.TEST_EMAILS:
self.temp_file.write(email)
self.temp_file.write('\n')
self.temp_file.close()
def test_command_without_input_file(self):
args = []
opts = {}
self.assertRaises(SystemExit, management.call_command,
'create_users', *args, **opts)
def test_command_input_file_no_email(self):
args = [self.temp_file.name]
opts = {'email':False}
management.call_command('create_users', *args, **opts)
eq_(len(mail.outbox), 0)
eq_(User.objects.count(), self.NO_VALID_EMAILS)
def test_command_input_file_send_email(self):
args = [self.temp_file.name]
opts = {'email':True}
management.call_command('create_users', *args, **opts)
eq_(len(mail.outbox), self.NO_VALID_EMAILS)
eq_(User.objects.count(), self.NO_VALID_EMAILS)
def tearDown(self):
os.unlink(self.temp_file.name)
| Python | 0.000004 |
5d8929986d278d97e33d425ae10bee0d29631886 | Encode the hostname to a str | mopidy/frontends/http/__init__.py | mopidy/frontends/http/__init__.py | from __future__ import absolute_import
import logging
import pykka
from mopidy import exceptions, settings
try:
import cherrypy
except ImportError as import_error:
raise exceptions.OptionalDependencyError(import_error)
logger = logging.getLogger('mopidy.frontends.http')
class HttpFrontend(pykka.ThreadingActor):
def __init__(self, core):
super(HttpFrontend, self).__init__()
self.core = core
cherrypy.config.update({
'server.socket_host':
settings.HTTP_SERVER_HOSTNAME.encode('utf-8'),
'server.socket_port': settings.HTTP_SERVER_PORT,
})
app = cherrypy.tree.mount(Root(self.core), '/')
self._setup_logging(app)
def _setup_logging(self, app):
cherrypy.log.access_log.setLevel(logging.NOTSET)
cherrypy.log.error_log.setLevel(logging.NOTSET)
cherrypy.log.screen = False
app.log.access_log.setLevel(logging.NOTSET)
app.log.error_log.setLevel(logging.NOTSET)
def on_start(self):
logger.debug(u'Starting HTTP server')
cherrypy.server.start()
logger.info(u'HTTP server running at %s',
cherrypy.server.base())
def on_stop(self):
cherrypy.server.stop()
class Root(object):
def __init__(self, core):
self.core = core
@cherrypy.expose
@cherrypy.tools.json_out()
def index(self):
playback_state = self.core.playback.state.get()
track = self.core.playback.current_track.get()
if track:
track = track.serialize()
return {
'playback_state': playback_state,
'current_track': track,
}
| from __future__ import absolute_import
import logging
import pykka
from mopidy import exceptions, settings
try:
import cherrypy
except ImportError as import_error:
raise exceptions.OptionalDependencyError(import_error)
logger = logging.getLogger('mopidy.frontends.http')
class HttpFrontend(pykka.ThreadingActor):
def __init__(self, core):
super(HttpFrontend, self).__init__()
self.core = core
cherrypy.config.update({
'server.socket_host': settings.HTTP_SERVER_HOSTNAME,
'server.socket_port': settings.HTTP_SERVER_PORT,
})
app = cherrypy.tree.mount(Root(self.core), '/')
self._setup_logging(app)
def _setup_logging(self, app):
cherrypy.log.access_log.setLevel(logging.NOTSET)
cherrypy.log.error_log.setLevel(logging.NOTSET)
cherrypy.log.screen = False
app.log.access_log.setLevel(logging.NOTSET)
app.log.error_log.setLevel(logging.NOTSET)
def on_start(self):
logger.debug(u'Starting HTTP server')
cherrypy.server.start()
logger.info(u'HTTP server running at %s',
cherrypy.server.base())
def on_stop(self):
cherrypy.server.stop()
class Root(object):
def __init__(self, core):
self.core = core
@cherrypy.expose
@cherrypy.tools.json_out()
def index(self):
playback_state = self.core.playback.state.get()
track = self.core.playback.current_track.get()
if track:
track = track.serialize()
return {
'playback_state': playback_state,
'current_track': track,
}
| Python | 0.999999 |
6e660da290db674eebb0c353662e5400bc735397 | Update backplane demo to be py3 only | examples/backplane_demo.py | examples/backplane_demo.py | #!/usr/bin/python
import time
from guild.actor import *
from guild.components import Backplane, PublishTo, SubscribeTo, Printer
class Producer(Actor):
@process_method
def process(self):
self.output("hello")
@late_bind_safe
def output(self, value):
pass
Backplane("HELLO").start()
p = Producer()
pr = Printer()
time.sleep(1)
pub = PublishTo("HELLO")
sub = SubscribeTo("HELLO")
print("pub", pub, repr(pub), pub.input)
pipeline(p, pub)
pipeline(sub, pr)
start(p, pr, sub)
time.sleep(1.0)
stop(p, pr, sub)
wait_for(p, pr, sub)
| #!/usr/bin/python
import time
from guild.actor import *
from guild.components import Backplane, PublishTo, SubscribeTo, Printer
class Producer(Actor):
@process_method
def process(self):
self.output("hello")
@late_bind_safe
def output(self, value):
pass
Backplane("HELLO").start()
p = Producer()
pr = Printer()
time.sleep(1)
pub = PublishTo("HELLO")
sub = SubscribeTo("HELLO")
print "pub", pub, repr(pub), pub.input
pipeline(p, pub)
pipeline(sub, pr)
start(p, pr, sub)
time.sleep(1.0)
stop(p, pr, sub)
wait_for(p, pr, sub)
| Python | 0 |
0b37c0f1cba1a6e89a63f9597d61383b81b1a2d9 | Fix typo | haas/client/network.py | haas/client/network.py | import json
from haas.client.base import ClientBase
class Network(ClientBase):
"""Consists of calls to query and manipulate network related
objects and relations.
"""
def list(self):
"""Lists all networks under HIL """
url = self.object_url('networks')
return self.check_response(self.httpClient.request("GET", url))
def show(self, network):
"""Shows attributes of a network. """
url = self.object_url('network', network)
return self.check_response(self.httpClient.request("GET", url))
def create(self, network, owner, access, net_id):
"""Create a link-layer <network>.
See docs/networks.md for details.
"""
url = self.object_url('network', network)
payload = json.dumps({
'owner': owner, 'access': access,
'net_id': net_id
})
return self.check_response(
self.httpClient.request("PUT", url, data=payload)
)
def delete(self, network):
"""Delete a <network>. """
url = self.object_url('network', network)
return self.check_response(self.httpClient.request("DELETE", url))
def grant_access(self, project, network):
"""Grants <project> access to <network>. """
url = self.object_url(
'network', network, 'access', project
)
return self.check_response(self.httpClient.request("PUT", url))
def revoke_access(self, project, network):
"""Removes access of <network> from <project>. """
url = self.object_url(
'network', network, 'access', project
)
return self.check_response(self.httpClient.request("DELETE", url))
| import json
from haas.client.base import ClientBase
class Network(ClientBase):
"""Consists of calls to query and manipulate network related
objects and relations.
"""
def list(self):
"""Lists all projects under HIL """
url = self.object_url('networks')
return self.check_response(self.httpClient.request("GET", url))
def show(self, network):
"""Shows attributes of a network. """
url = self.object_url('network', network)
return self.check_response(self.httpClient.request("GET", url))
def create(self, network, owner, access, net_id):
"""Create a link-layer <network>.
See docs/networks.md for details.
"""
url = self.object_url('network', network)
payload = json.dumps({
'owner': owner, 'access': access,
'net_id': net_id
})
return self.check_response(
self.httpClient.request("PUT", url, data=payload)
)
def delete(self, network):
"""Delete a <network>. """
url = self.object_url('network', network)
return self.check_response(self.httpClient.request("DELETE", url))
def grant_access(self, project, network):
"""Grants <project> access to <network>. """
url = self.object_url(
'network', network, 'access', project
)
return self.check_response(self.httpClient.request("PUT", url))
def revoke_access(self, project, network):
"""Removes access of <network> from <project>. """
url = self.object_url(
'network', network, 'access', project
)
return self.check_response(self.httpClient.request("DELETE", url))
| Python | 0.999999 |
56f6339401fe5f792915279d98f553f3415e2c62 | Fix module docstring (#163) | netdisco/discoverables/harmony.py | netdisco/discoverables/harmony.py | """Discover Harmony Hub remotes."""
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
"""Add support for discovering Harmony Hub remotes"""
def get_entries(self):
"""Get all the Harmony uPnP entries."""
return self.find_by_device_description({
"manufacturer": "Logitech",
"deviceType": "urn:myharmony-com:device:harmony:1"
})
| """Discover Netgear routers."""
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
"""Add support for discovering Harmony Hub remotes"""
def get_entries(self):
"""Get all the Harmony uPnP entries."""
return self.find_by_device_description({
"manufacturer": "Logitech",
"deviceType": "urn:myharmony-com:device:harmony:1"
})
| Python | 0 |
b5c5f9f0e97c9273c18936ea57ad866b4865fc68 | Revert 47344b | install/build.py | install/build.py | import distutils
import os
import shutil
import subprocess
import tempfile
import setuptools
from install import utils
minimum_cuda_version = 6050
minimum_cudnn_version = 2000
def check_cuda_version(compiler, settings):
out = build_and_run(compiler, '''
#include <cuda.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
printf("%d", CUDA_VERSION);
return 0;
}
''', include_dirs=settings['include_dirs'])
if out is None:
utils.print_warning('Cannot check CUDA version')
return False
cuda_version = int(out)
if cuda_version < minimum_cuda_version:
utils.print_warning(
'CUDA version is too old: %d' % cuda_version,
'CUDA v6.5 or newer is required')
return False
return True
def check_cudnn_version(compiler, settings):
out = build_and_run(compiler, '''
#include <cudnn.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
printf("%d", CUDNN_VERSION);
return 0;
}
''', include_dirs=settings['include_dirs'])
if out is None:
utils.print_warning('Cannot check cuDNN version')
return False
cudnn_version = int(out)
if cudnn_version < minimum_cudnn_version:
utils.print_warning(
'cuDNN version is too old: %d' % cudnn_version,
'cuDNN v2 or newer is required')
return False
return True
def build_and_run(compiler, source, libraries=[],
include_dirs=[], library_dirs=[]):
temp_dir = tempfile.mkdtemp()
try:
fname = os.path.join(temp_dir, 'a.cpp')
with open(fname, 'w') as f:
f.write(source)
try:
objects = compiler.compile([fname], output_dir=temp_dir,
include_dirs=include_dirs)
except distutils.errors.CompileError:
return None
try:
postargs = ['/MANIFEST'] if sys.platform == 'win32' else []
compiler.link_executable(objects,
os.path.join(temp_dir, 'a'),
libraries=libraries,
library_dirs=library_dirs,
extra_postargs=postargs)
except (distutils.errors.LinkError, TypeError):
return None
try:
out = subprocess.check_output(os.path.join(temp_dir, 'a'))
return out
except Exception:
return None
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
| import distutils
import os
import shutil
import subprocess
import tempfile
import setuptools
from install import utils
minimum_cuda_version = 6050
minimum_cudnn_version = 2000
def check_cuda_version(compiler, settings):
out = build_and_run(compiler, '''
#include <cuda.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
printf("%d", CUDA_VERSION);
return 0;
}
''', include_dirs=settings['include_dirs'])
if out is None:
utils.print_warning('Cannot check CUDA version')
return False
cuda_version = int(out)
if cuda_version < minimum_cuda_version:
utils.print_warning(
'CUDA version is too old: %d' % cuda_version,
'CUDA v6.5 or newer is required')
return False
return True
def check_cudnn_version(compiler, settings):
out = build_and_run(compiler, '''
#include <cudnn.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
printf("%d", CUDNN_VERSION);
return 0;
}
''', include_dirs=settings['include_dirs'])
if out is None:
utils.print_warning('Cannot check cuDNN version')
return False
cudnn_version = int(out)
if cudnn_version < minimum_cudnn_version:
utils.print_warning(
'cuDNN version is too old: %d' % cudnn_version,
'cuDNN v2 or newer is required')
return False
return True
def build_and_run(compiler, source, libraries=[],
include_dirs=[], library_dirs=[]):
temp_dir = tempfile.mkdtemp()
try:
fname = os.path.join(temp_dir, 'a.cpp')
with open(fname, 'w') as f:
f.write(source)
try:
objects = compiler.compile([fname], output_dir=temp_dir,
include_dirs=include_dirs)
except distutils.errors.CompileError:
return None
try:
compiler.link_executable(objects,
os.path.join(temp_dir, 'a'),
libraries=libraries,
library_dirs=library_dirs)
except (distutils.errors.LinkError, TypeError):
return None
try:
out = subprocess.check_output(os.path.join(temp_dir, 'a'))
return out
except Exception:
return None
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
| Python | 0.000001 |
d3425693d245c9dfa5350017903fc02a11ecd881 | use width/height as percent base for x/y | compiler/lang.py | compiler/lang.py | import re
def value_is_trivial(value):
if value is None or not isinstance(value, str):
return False
if value[0] == '(' and value[-1] == ')':
value = value[1:-1]
if value == 'true' or value == 'false':
return True
try:
float(value)
return True
except:
pass
if value[0] == '"' and value[-1] == '"':
if value.count('"') == value.count('\\"') + 2:
return True
#print "?trivial", value
return False
class DocumentationString(object):
def __init__(self, text):
self.text = text
class Entity(object):
def __init__(self):
self.doc = None
class Component(Entity):
def __init__(self, name, children):
super(Component, self).__init__()
self.name = name
self.children = children
class Property(Entity):
def __init__(self, type, name, value = None):
super(Property, self).__init__()
self.type = type
self.name = name
self.value = value
def is_trivial(self):
return value_is_trivial(self.value)
class AliasProperty(Entity):
def __init__(self, name, target):
super(AliasProperty, self).__init__()
self.name = name
self.target = target
class EnumProperty(Entity):
def __init__(self, name, values, default):
super(EnumProperty, self).__init__()
self.name = name
self.values = values
self.default = default
class Constructor(Entity):
def __init__(self, args, code):
super(Constructor, self).__init__()
if len(args) != 0:
raise Exception("no arguments for constructor allowed")
self.code = code
class Method(Entity):
def __init__(self, name, args, code, event):
super(Method, self).__init__()
self.name = name
self.args = args
self.code = code
self.event = event
class IdAssignment(Entity):
def __init__(self, name):
super(IdAssignment, self).__init__()
self.name = name
class Assignment(Entity):
re_name = re.compile('<property-name>')
def __init__(self, target, value):
super(Assignment, self).__init__()
self.target = target
dot = target.rfind('.')
property_name = target[dot + 1:] if dot >= 0 else target
if property_name == 'x':
property_name = 'width'
elif property_name == 'y':
property_name = 'height'
self.value = Assignment.re_name.sub(property_name, value) if isinstance(value, str) else value
def is_trivial(self):
return value_is_trivial(self.value)
class AssignmentScope(Entity):
def __init__(self, target, values):
super(AssignmentScope, self).__init__()
self.target = target
self.values = values
class Behavior(Entity):
def __init__(self, target, animation):
super(Behavior, self).__init__()
self.target = target
self.animation = animation
class Signal(Entity):
def __init__(self, name):
super(Signal, self).__init__()
self.name = name
class ListElement(Entity):
def __init__(self, data):
super(ListElement, self).__init__()
self.data = data
| import re
def value_is_trivial(value):
if value is None or not isinstance(value, str):
return False
if value[0] == '(' and value[-1] == ')':
value = value[1:-1]
if value == 'true' or value == 'false':
return True
try:
float(value)
return True
except:
pass
if value[0] == '"' and value[-1] == '"':
if value.count('"') == value.count('\\"') + 2:
return True
#print "?trivial", value
return False
class DocumentationString(object):
def __init__(self, text):
self.text = text
class Entity(object):
def __init__(self):
self.doc = None
class Component(Entity):
def __init__(self, name, children):
super(Component, self).__init__()
self.name = name
self.children = children
class Property(Entity):
def __init__(self, type, name, value = None):
super(Property, self).__init__()
self.type = type
self.name = name
self.value = value
def is_trivial(self):
return value_is_trivial(self.value)
class AliasProperty(Entity):
def __init__(self, name, target):
super(AliasProperty, self).__init__()
self.name = name
self.target = target
class EnumProperty(Entity):
def __init__(self, name, values, default):
super(EnumProperty, self).__init__()
self.name = name
self.values = values
self.default = default
class Constructor(Entity):
def __init__(self, args, code):
super(Constructor, self).__init__()
if len(args) != 0:
raise Exception("no arguments for constructor allowed")
self.code = code
class Method(Entity):
def __init__(self, name, args, code, event):
super(Method, self).__init__()
self.name = name
self.args = args
self.code = code
self.event = event
class IdAssignment(Entity):
def __init__(self, name):
super(IdAssignment, self).__init__()
self.name = name
class Assignment(Entity):
re_name = re.compile('<property-name>')
def __init__(self, target, value):
super(Assignment, self).__init__()
self.target = target
def replace_name(m):
dot = target.rfind('.')
name = target.substr(dot + 1) if dot >= 0 else target
return name
self.value = Assignment.re_name.sub(replace_name, value) if isinstance(value, str) else value
def is_trivial(self):
return value_is_trivial(self.value)
class AssignmentScope(Entity):
def __init__(self, target, values):
super(AssignmentScope, self).__init__()
self.target = target
self.values = values
class Behavior(Entity):
def __init__(self, target, animation):
super(Behavior, self).__init__()
self.target = target
self.animation = animation
class Signal(Entity):
def __init__(self, name):
super(Signal, self).__init__()
self.name = name
class ListElement(Entity):
def __init__(self, data):
super(ListElement, self).__init__()
self.data = data
| Python | 0.000003 |
08d11dc308db007750fe06ea906264a6ab9f44cd | Add logging when cloning repository | instance/repo.py | instance/repo.py | # -*- coding: utf-8 -*-
#
# OpenCraft -- tools to aid developing and hosting free software projects
# Copyright (C) 2015 OpenCraft <xavier@opencraft.com>
#
# 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/>.
#
"""
Git repository - Helper functions
"""
# Imports #####################################################################
import git
import tempfile
import shutil
from contextlib import contextmanager
# Logging #####################################################################
import logging
logger = logging.getLogger(__name__)
# Functions ###################################################################
@contextmanager
def open_repository(repo_url, ref='master'):
"""
Get a `Git` object for a repository URL and switch it to the branch `ref`
Note that this clones the repository locally
"""
repo_dir_path = tempfile.mkdtemp()
logger.info('Cloning repository %s (ref=%s) in %s...', repo_url, ref, repo_dir_path)
git.repo.base.Repo.clone_from(repo_url, repo_dir_path)
g = git.Git(repo_dir_path)
g.checkout(ref)
yield g
shutil.rmtree(repo_dir_path)
| # -*- coding: utf-8 -*-
#
# OpenCraft -- tools to aid developing and hosting free software projects
# Copyright (C) 2015 OpenCraft <xavier@opencraft.com>
#
# 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/>.
#
"""
Git repository - Helper functions
"""
# Imports #####################################################################
import git
import tempfile
import shutil
from contextlib import contextmanager
# Functions ###################################################################
@contextmanager
def open_repository(repo_url, ref='master'):
"""
Get a `Git` object for a repository URL and switch it to the branch `ref`
Note that this clones the repository locally
"""
repo_dir_path = tempfile.mkdtemp()
git.repo.base.Repo.clone_from(repo_url, repo_dir_path)
g = git.Git(repo_dir_path)
g.checkout(ref)
yield g
shutil.rmtree(repo_dir_path)
| Python | 0.000001 |
b2b4d0b49e755da0fc56e83ce81312d148f315d6 | add comments to code | instapaperbot.py | instapaperbot.py | import logging
import re #searching url in message
from telegram.ext import Updater
from telegram.ext import CommandHandler
from telegram.ext import MessageHandler, Filters
import instapaper #add link to instapaper
import config #временно загружаю логин-пароль ль instapaper
#логирование всех данных
def log_message(log_info):
user_id = log_info['message']['chat']['id']
user_username = log_info['message']['chat']['username']
user_text = log_info['message']['text']
debug_info = 'id:{} user:{} text:"{}"'.format(user_id,user_username,user_text)
logging.info(debug_info)
#реакция при нажатии команды Start
def start (bot, update):
bot.sendMessage(chat_id = update.message.chat_id, text = 'Hello, new user!')
print ('New user')
#добавлении адреса в Instapaper конкретного человека
#пока можно установить собственный логин-пароль и постить туда адреса
def add_url_to_instapaper(chat_id,url):
username = config.user
password = config.password
if str(chat_id) == config.id:
instapaper.add_urls(username,password,url)
else:
print ("can't add link:{} from id:{}".format(url,chat_id))
#регулярное выражение для поиска URL в сообщении
def find_url(text):
pattern = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]|[А-Яа-я]))+')
res = pattern.findall(text)
return res
#основная функция по общению с пользователем
def conversation (bot, update):
message_text = update['message']['text']
clear_url = find_url(message_text)
if len(clear_url) != 0:
print ('url=',clear_url)
for single_url in clear_url:
add_url_to_instapaper(update.message.chat_id,single_url)
bot.sendMessage(chat_id = update.message.chat_id,text = 'Thanks for the link, I soon learned to handle it')
else:
bot.sendMessage(chat_id = update.message.chat_id,text = update.message.text)
log_message(update)
#реакция на неизвестные команды
def unknown(bot,update):
bot.sendMessage(chat_id = update.message.chat_id,text = "I didn't understand that command.")
#основная функция программы
def main ():
TOKEN = config.TOKEN
#простое логгирование в файл
logging.basicConfig(filename='info.log',level = logging.INFO,format='%(asctime)s - %(message)s')
updater = Updater (token = TOKEN)
dispatcher = updater.dispatcher
#handlers
start_handler = CommandHandler('start', start)
conversation_handler = MessageHandler (Filters.text, conversation)
unknown_handler = MessageHandler(Filters.command, unknown)
#dispatchers
dispatcher.add_handler(start_handler)
dispatcher.add_handler(conversation_handler)
dispatcher.add_handler(unknown_handler)
#updater
updater.start_polling()
if __name__ == '__main__':
main()
| import logging
import re #searching url in message
from telegram.ext import Updater
from telegram.ext import CommandHandler
from telegram.ext import MessageHandler, Filters
import instapaper #add link to instapaper
import config #временно загружаю логин-пароль ль instapaper
def log_message(log_info):
user_id = log_info['message']['chat']['id']
user_username = log_info['message']['chat']['username']
user_text = log_info['message']['text']
debug_info = 'id:{} user:{} text:"{}"'.format(user_id,user_username,user_text)
#print (debug_info)
logging.info(debug_info)
def start (bot, update):
bot.sendMessage(chat_id = update.message.chat_id, text = 'Hello, new user!')
print ('New user')
def add_url_to_instapaper(chat_id,url):
username = config.user
password = config.password
if str(chat_id) == config.id:
instapaper.add_urls(username,password,url)
else:
print ("can't add link:{} from id:{}".format(url,chat_id))
def find_url(text):
pattern = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]|[А-Яа-я]))+')
res = pattern.findall(text)
return res
def conversation (bot, update):
message_text = update['message']['text']
clear_url = find_url(message_text)
if len(clear_url) != 0:
print ('url=',clear_url)
for single_url in clear_url:
add_url_to_instapaper(update.message.chat_id,single_url)
bot.sendMessage(chat_id = update.message.chat_id,text = 'Thanks for the link, I soon learned to handle it')
else:
bot.sendMessage(chat_id = update.message.chat_id,text = update.message.text)
log_message(update)
def unknown(bot,update):
bot.sendMessage(chat_id = update.message.chat_id,text = "I didn't understand that command.")
def main ():
TOKEN = config.TOKEN
#простое логгирование в файл
logging.basicConfig(filename='info.log',level = logging.INFO,format='%(asctime)s - %(message)s')
updater = Updater (token = TOKEN)
dispatcher = updater.dispatcher
#handlers
start_handler = CommandHandler('start', start)
conversation_handler = MessageHandler (Filters.text, conversation)
unknown_handler = MessageHandler(Filters.command, unknown)
#dispatchers
dispatcher.add_handler(start_handler)
dispatcher.add_handler(conversation_handler)
dispatcher.add_handler(unknown_handler)
#updater
updater.start_polling()
if __name__ == '__main__':
main()
| Python | 0 |
a2a4a8e4636051fa84a5cfbaf7f4ff796c59171a | Add build.parent to api response | changes/api/serializer/models/build.py | changes/api/serializer/models/build.py | from changes.api.serializer import Serializer, register
from changes.constants import Result, Status
from changes.models.build import Build
@register(Build)
class BuildSerializer(Serializer):
def serialize(self, instance):
# TODO(dcramer): this shouldnt be calculated at runtime
last_5_builds = list(Build.query.filter_by(
result=Result.passed,
status=Status.finished,
project=instance.project,
).order_by(Build.date_finished.desc())[:3])
if last_5_builds:
avg_build_time = sum(
b.duration for b in last_5_builds
if b.duration
) / len(last_5_builds)
else:
avg_build_time = None
data = instance.data or {}
backend_details = data.get('backend')
if backend_details:
external = {
'link': backend_details['uri'],
'label': backend_details['label'],
}
else:
external = None
if instance.parent_id:
parent = {
'id': instance.parent_id.hex,
'link': '/builds/%s/' % (instance.parent_id.hex,),
}
else:
parent = None
return {
'id': instance.id.hex,
'name': instance.label,
'result': instance.result,
'status': instance.status,
'project': instance.project,
'cause': instance.cause,
'author': instance.author,
'parent_revision': {
'sha': instance.parent_revision_sha,
},
'parent': parent,
'message': instance.message,
'duration': instance.duration,
'estimatedDuration': avg_build_time,
'link': '/builds/%s/' % (instance.id.hex,),
'external': external,
'dateCreated': instance.date_created.isoformat(),
'dateModified': instance.date_modified.isoformat() if instance.date_modified else None,
'dateStarted': instance.date_started.isoformat() if instance.date_started else None,
'dateFinished': instance.date_finished.isoformat() if instance.date_finished else None,
}
| from changes.api.serializer import Serializer, register
from changes.constants import Result, Status
from changes.models.build import Build
@register(Build)
class BuildSerializer(Serializer):
def serialize(self, instance):
# TODO(dcramer): this shouldnt be calculated at runtime
last_5_builds = list(Build.query.filter_by(
result=Result.passed,
status=Status.finished,
project=instance.project,
).order_by(Build.date_finished.desc())[:3])
if last_5_builds:
avg_build_time = sum(
b.duration for b in last_5_builds
if b.duration
) / len(last_5_builds)
else:
avg_build_time = None
data = instance.data or {}
backend_details = data.get('backend')
if backend_details:
external = {
'link': backend_details['uri'],
'label': backend_details['label'],
}
else:
external = None
return {
'id': instance.id.hex,
'name': instance.label,
'result': instance.result,
'status': instance.status,
'project': instance.project,
'cause': instance.cause,
'author': instance.author,
'parent_revision': {
'sha': instance.parent_revision_sha,
},
'message': instance.message,
'duration': instance.duration,
'estimatedDuration': avg_build_time,
'link': '/builds/%s/' % (instance.id.hex,),
'external': external,
'dateCreated': instance.date_created.isoformat(),
'dateModified': instance.date_modified.isoformat() if instance.date_modified else None,
'dateStarted': instance.date_started.isoformat() if instance.date_started else None,
'dateFinished': instance.date_finished.isoformat() if instance.date_finished else None,
}
| Python | 0.000001 |
39154c1c5dcb192079060083ecc0a97e776cee3d | Fix bug in redirect | website/views.py | website/views.py | import bcrypt
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from website.models import UndergroundComptoir
from .forms import AnonymousForm, RegisteredForm
def index(req):
# Homepage of the website
# If a form was posted
if "form_type" in req.POST.keys():
username = req.POST.get("username")
# Anonymous registration
if req.POST["form_type"] == "anonymous":
password = getattr(settings, "ANONYMOUS_PASSWORD", None)
# If username does not exist,
# create it with default anonymous password
user, created = User.objects.get_or_create(username=username)
if created:
print("user created")
user.set_password(password)
user.save()
elif req.POST["form_type"] == "registered":
password = req.POST.get("password")
print(username, password)
user = authenticate(username=username, password=password)
if user is not None and user.is_authenticated():
login(req, user)
next_page = req.POST.get("next")
if next_page is not None and next_page != "":
return redirect(next_page)
return render(req, "website/index.html", {
'anonymousForm': AnonymousForm(),
'registeredForm': RegisteredForm(),
})
@login_required(login_url="index")
def underground_comptoir(req, label):
# First, key provided or not?
if "key" in req.POST.keys():
key = req.POST["key"]
elif "key" in req.GET.keys():
key = req.GET["key"]
else:
key = None
# First, see if comptoir exists
try:
comptoir = UndergroundComptoir.objects.get(label=label)
# Get fingerprint from the key
if key is not None:
salt = comptoir.keyprint
keyprint = bcrypt.hashpw(key.encode("utf-8"), salt.encode("utf-8"))
else:
keyprint = None
# Check the keyprint
if keyprint != comptoir.keyprint:
# TODO error message
# TODO handle error correctly
# (redirect to home is NOT a reliable way to do)
return redirect("index")
# If not
except ObjectDoesNotExist:
# We create it
if key is None:
keyprint = None
else:
keyprint = bcrypt(key.encode("utf-8"), bcrypt.gensalt()),
comptoir = UndergroundComptoir(
label=label,
keyprint=keyprint,
)
comptoir.save()
# We want to show the last 50 messages, ordered most-recent-last
messages = reversed(comptoir.messages.order_by('-timestamp')[:50])
return render(req, "website/comptoir.html", {
'comptoir': comptoir,
'messages': messages,
})
# Authentication views
def register(req):
reg_form = UserCreationForm(req.POST or None, label_suffix='')
# Check the form validity
if reg_form.is_valid():
# Register the new user
new_user = reg_form.save()
# Authenticate
new_user = authenticate(username=new_user.username, password=req.POST["password1"])
# Log the new user in
login(req, new_user)
else:
# TODO better
print(reg_form.errors)
return redirect("index")
| import bcrypt
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from website.models import UndergroundComptoir
from .forms import AnonymousForm, RegisteredForm
def index(req):
# Homepage of the website
# If a form was posted
if "form_type" in req.POST.keys():
username = req.POST.get("username")
# Anonymous registration
if req.POST["form_type"] == "anonymous":
password = getattr(settings, "ANONYMOUS_PASSWORD", None)
# If username does not exist,
# create it with default anonymous password
user, created = User.objects.get_or_create(username=username)
if created:
print("user created")
user.set_password(password)
user.save()
elif req.POST["form_type"] == "registered":
password = req.POST.get("password")
print(username, password)
user = authenticate(username=username, password=password)
if user is not None and user.is_authenticated():
login(req, user)
return render(req, "website/index.html", {
'anonymousForm': AnonymousForm(),
'registeredForm': RegisteredForm(),
})
@login_required(login_url="index")
def underground_comptoir(req, label):
# First, key provided or not?
if "key" in req.POST.keys():
key = req.POST["key"]
elif "key" in req.GET.keys():
key = req.GET["key"]
else:
key = None
# First, see if comptoir exists
try:
comptoir = UndergroundComptoir.objects.get(label=label)
# Get fingerprint from the key
if key is not None:
salt = comptoir.keyprint
keyprint = bcrypt.hashpw(key.encode("utf-8"), salt.encode("utf-8"))
else:
keyprint = None
# Check the keyprint
if keyprint != comptoir.keyprint:
# TODO error message
# TODO handle error correctly
# (redirect to home is NOT a reliable way to do)
return redirect("index")
# If not
except ObjectDoesNotExist:
# We create it
if key is None:
keyprint = None
else:
keyprint = bcrypt(key.encode("utf-8"), bcrypt.gensalt()),
comptoir = UndergroundComptoir(
label=label,
keyprint=keyprint,
)
comptoir.save()
# We want to show the last 50 messages, ordered most-recent-last
messages = reversed(comptoir.messages.order_by('-timestamp')[:50])
return render(req, "website/comptoir.html", {
'comptoir': comptoir,
'messages': messages,
})
# Authentication views
def register(req):
reg_form = UserCreationForm(req.POST or None, label_suffix='')
# Check the form validity
if reg_form.is_valid():
# Register the new user
new_user = reg_form.save()
# Authenticate
new_user = authenticate(username=new_user.username, password=req.POST["password1"])
# Log the new user in
login(req, new_user)
else:
# TODO better
print(reg_form.errors)
return redirect("index")
| Python | 0 |
469fc6ff805e845ac922a7334612f67f194eb93b | Fix flake8 errors in late_command script | deployment/puppet/cobbler/templates/scripts/late_command.py | deployment/puppet/cobbler/templates/scripts/late_command.py | #!/usr/bin/python
#
# Copyright (C) 2011 Mirantis Inc.
#
# Authors: Vladimir Kozhukalov <vkozhukalov@mirantis.com>
#
# 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, version 3 of the License.
#
# 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/>.
from base64 import b64encode
from cStringIO import StringIO
from gzip import GzipFile
TEMPLATE_FILE = (
"sh -c 'filename=${1}; shift; echo ${0} | base64 --decode | "
"gunzip -c > ${filename} && chmod %(mode)s ${filename}' "
"%(content64)s %(destfile)s"
)
TEMPLATE_COMMAND = (
"sh -c 'echo ${0} | base64 --decode | gunzip -c | sh -' %(content64)s"
)
TEMPLATE_FILE_PLAIN = (
"sh -c 'filename=${1}; shift; echo ${0} | base64 --decode "
"> ${filename} && chmod %(mode)s ${filename}' "
"%(content64)s %(destfile)s"
)
TEMPLATE_COMMAND_PLAIN = (
"sh -c 'echo ${0} | base64 --decode | sh -' %(content64)s"
)
def base64_gzip(content, gzip=True):
"""Gzip and enconde bas64 provided content
This method returns content gzipped and then base64 encoded
so such line can be inserted into preseed file
"""
if gzip:
gzipped = StringIO()
gzip_file = GzipFile(fileobj=gzipped, mode="wb", compresslevel=9)
gzip_file.write(content)
gzip_file.close()
content2 = gzipped.getvalue()
else:
content2 = content
return b64encode(content2)
def get_content(source, source_method):
if source_method == 'file':
try:
f = open(source, 'r')
content = f.read()
f.close()
except Exception:
return ""
else:
return content
return source
def get_content64(source, source_method, gzip=True):
return base64_gzip(get_content(source, source_method), gzip).strip()
def late_file(source, destfile, source_method='file', mode='0644', gzip=True):
if gzip:
return TEMPLATE_FILE % {
'mode': mode,
'content64': get_content64(source, source_method, True),
'destfile': destfile,
}
else:
return TEMPLATE_FILE_PLAIN % {
'mode': mode,
'content64': get_content64(source, source_method, False),
'destfile': destfile,
}
def late_command(source, source_method='file', gzip=True):
if gzip:
return TEMPLATE_COMMAND % {
'content64': get_content64(source, source_method, True)
}
else:
return TEMPLATE_COMMAND_PLAIN % {
'content64': get_content64(source, source_method, False)
}
| #!/usr/bin/python
#
# Copyright (C) 2011 Mirantis Inc.
#
# Authors: Vladimir Kozhukalov <vkozhukalov@mirantis.com>
#
# 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, version 3 of the License.
#
# 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/>.
# flake8: noqa
from base64 import b64encode
from cStringIO import StringIO
from gzip import GzipFile
import commands, os
TEMPLATE_FILE = (
"sh -c 'filename=${1}; shift; echo ${0} | base64 --decode | "
"gunzip -c > ${filename} && chmod %(mode)s ${filename}' "
"%(content64)s %(destfile)s"
)
TEMPLATE_COMMAND = (
"sh -c 'echo ${0} | base64 --decode | gunzip -c | sh -' %(content64)s"
)
TEMPLATE_FILE_PLAIN = (
"sh -c 'filename=${1}; shift; echo ${0} | base64 --decode "
"> ${filename} && chmod %(mode)s ${filename}' "
"%(content64)s %(destfile)s"
)
TEMPLATE_COMMAND_PLAIN = (
"sh -c 'echo ${0} | base64 --decode | sh -' %(content64)s"
)
def base64_gzip(content, gzip=True):
"""
This method returns content gzipped and then base64 encoded
so such line can be inserted into preseed file
"""
if gzip:
gzipped = StringIO()
gzip_file = GzipFile(fileobj=gzipped, mode="wb", compresslevel=9)
gzip_file.write(content)
gzip_file.close()
content2 = gzipped.getvalue()
else:
content2 = content
return b64encode(content2)
def get_content(source, source_method):
if source_method == 'file':
try:
f = open(source, 'r')
content = f.read()
f.close()
except:
return ""
else:
return content
return source
def get_content64(source, source_method, gzip=True):
return base64_gzip(get_content(source, source_method), gzip).strip()
def late_file(source, destfile, source_method='file', mode='0644', gzip=True):
if gzip:
return TEMPLATE_FILE % {
'mode': mode,
'content64': get_content64(source, source_method, True),
'destfile': destfile,
}
else:
return TEMPLATE_FILE_PLAIN % {
'mode': mode,
'content64': get_content64(source, source_method, False),
'destfile': destfile,
}
def late_command(source, source_method='file', gzip=True):
if gzip:
return TEMPLATE_COMMAND % {
'content64': get_content64(source, source_method, True)
}
else:
return TEMPLATE_COMMAND_PLAIN % {
'content64': get_content64(source, source_method, False)
}
| Python | 0.00004 |
2413a2042745a00b5a220a753aa46177065f3793 | bump version to 0.0.3 | nose_warnings_filters/__init__.py | nose_warnings_filters/__init__.py |
"""
Nose plugin to add warnings filters (turn them into error) using nose.cfg file.
"""
__version__ = '0.0.3'
from nose.plugins import Plugin
import warnings
import sys
if sys.version_info < (3,):
import builtins
else:
builtins = __builtins__
class WarningFilter(Plugin):
def options(self, parser, env):
"""
Add options to command line.
"""
super(WarningFilter, self).options(parser, env)
parser.add_option("--warningfilters",
default=None,
help="Treat warnings that occur WITHIN tests as errors.")
def configure(self, options, conf):
"""
Configure plugin.
"""
for opt in options.warningfilters.split( '\n'):
vs = [s.strip() for s in opt.split('|')]
vs[2] = getattr(builtins, vs[2])
warnings.filterwarnings(*vs)
super(WarningFilter, self).configure(options, conf)
def prepareTestRunner(self, runner):
"""
Treat warnings as errors.
"""
return WarningFilterRunner(runner)
class WarningFilterRunner(object):
def __init__(self, runner):
self.runner=runner
def run(self, test):
return self.runner.run(test)
|
"""
Nose plugin to add warnings filters (turn them into error) using nose.cfg file.
"""
__version__ = '0.0.2'
from nose.plugins import Plugin
import warnings
import sys
if sys.version_info < (3,):
import builtins
else:
builtins = __builtins__
class WarningFilter(Plugin):
def options(self, parser, env):
"""
Add options to command line.
"""
super(WarningFilter, self).options(parser, env)
parser.add_option("--warningfilters",
default=None,
help="Treat warnings that occur WITHIN tests as errors.")
def configure(self, options, conf):
"""
Configure plugin.
"""
for opt in options.warningfilters.split( '\n'):
vs = [s.strip() for s in opt.split('|')]
vs[2] = getattr(builtins, vs[2])
warnings.filterwarnings(*vs)
super(WarningFilter, self).configure(options, conf)
def prepareTestRunner(self, runner):
"""
Treat warnings as errors.
"""
return WarningFilterRunner(runner)
class WarningFilterRunner(object):
def __init__(self, runner):
self.runner=runner
def run(self, test):
return self.runner.run(test)
| Python | 0.000001 |
f8685d8ca3d4d18ca5895d765185993ed2d5bcd7 | Fix citizen subscription to report : DatabaseError: current transaction is aborted, commands ignored until end of transaction block | django_fixmystreet/fixmystreet/views/reports/subscribers.py | django_fixmystreet/fixmystreet/views/reports/subscribers.py |
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from django.contrib import messages
from django.db import IntegrityError
from django_fixmystreet.fixmystreet.models import FMSUser
from django_fixmystreet.fixmystreet.models import Report, ReportSubscription
def create(request, report_id):
report = get_object_or_404(Report, id=report_id)
#CREATE USER CITIZEN IF NECESSARY
try:
user = FMSUser.objects.get(email=request.REQUEST.get('citizen_email'))
except FMSUser.DoesNotExist:
#Add information about the citizen connected if it does not exist
user = FMSUser.objects.create(username=request.REQUEST.get('citizen_email'), email=request.REQUEST.get('citizen_email'), first_name='ANONYMOUS', last_name='ANONYMOUS', agent=False, contractor=False, manager=False, leader=False)
#VERIFY THAT A SUBSCRIPTION DOES NOT ALREADY EXIST
if not ReportSubscription.objects.filter(subscriber=user, report=report).exists():
subscriber = ReportSubscription(subscriber=user, report=report)
subscriber.save()
messages.add_message(request, messages.SUCCESS, _("You have subscribed from updates successfully"))
return HttpResponseRedirect(report.get_absolute_url())
def remove(request, report_id):
report = get_object_or_404(Report, id=report_id)
try:
user = FMSUser.objects.get(email=request.REQUEST.get('citizen_email'))
except FMSUser.DoesNotExist:
HttpResponseRedirect(report.get_absolute_url())
#VERIFY THAT A SUBSCRIPTION DOES NOT ALREADY EXIST
try:
subscription = ReportSubscription.objects.get(subscriber=user, report=report)
subscription.delete()
messages.add_message(request, messages.SUCCESS, _("You have unsubscribed from updates successfully"))
except ReportSubscription.DoesNotExist:
#Do nothing. A subscription for this user already exists...
messages.add_message(request, messages.SUCCESS, _("You have unsubscribed from updates successfully"))
return HttpResponseRedirect(report.get_absolute_url())
|
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from django.contrib import messages
from django.db import IntegrityError
from django_fixmystreet.fixmystreet.models import FMSUser
from django_fixmystreet.fixmystreet.models import Report, ReportSubscription
def create(request, report_id):
report = get_object_or_404(Report, id=report_id)
#CREATE USER CITIZEN IF NECESSARY
try:
user = FMSUser.objects.get(email=request.REQUEST.get('citizen_email'))
except FMSUser.DoesNotExist:
#Add information about the citizen connected if it does not exist
user = FMSUser.objects.create(username=request.REQUEST.get('citizen_email'), email=request.REQUEST.get('citizen_email'), first_name='ANONYMOUS', last_name='ANONYMOUS', agent=False, contractor=False, manager=False, leader=False)
#VERIFY THAT A SUBSCRIPTION DOES NOT ALREADY EXIST
try:
subscriber = ReportSubscription(subscriber=user, report=report)
subscriber.save()
messages.add_message(request, messages.SUCCESS, _("You have subscribed from updates successfully"))
except IntegrityError:
#Do nothing. A subscription for this user already exists...
messages.add_message(request, messages.SUCCESS, _("You have subscribed from updates successfully"))
return HttpResponseRedirect(report.get_absolute_url())
def remove(request, report_id):
report = get_object_or_404(Report, id=report_id)
try:
user = FMSUser.objects.get(email=request.REQUEST.get('citizen_email'))
except FMSUser.DoesNotExist:
HttpResponseRedirect(report.get_absolute_url())
#VERIFY THAT A SUBSCRIPTION DOES NOT ALREADY EXIST
try:
subscription = ReportSubscription.objects.get(subscriber=user, report=report)
subscription.delete()
messages.add_message(request, messages.SUCCESS, _("You have unsubscribed from updates successfully"))
except ReportSubscription.DoesNotExist:
#Do nothing. A subscription for this user already exists...
messages.add_message(request, messages.SUCCESS, _("You have unsubscribed from updates successfully"))
return HttpResponseRedirect(report.get_absolute_url())
| Python | 0.000001 |
9a87f83c7060b66f7f95f2823db11b5e86a4fd67 | fix #210 | src/you_get/downloader/dailymotion.py | src/you_get/downloader/dailymotion.py | #!/usr/bin/env python
__all__ = ['dailymotion_download']
from ..common import *
def dailymotion_download(url, output_dir = '.', merge = True, info_only = False):
"""Downloads Dailymotion videos by URL.
"""
id = match1(url, r'/video/([^\?]+)')
embed_url = 'http://www.dailymotion.com/embed/video/%s' % id
html = get_content(embed_url)
info = json.loads(match1(html, r'var\s*info\s*=\s*({.+}),\n'))
title = info['title']
for quality in ['stream_h264_hd1080_url', 'stream_h264_hd_url', 'stream_h264_hq_url', 'stream_h264_url', 'stream_h264_ld_url']:
real_url = info[quality]
if real_url:
break
type, ext, size = url_info(real_url)
print_info(site_info, title, type, size)
if not info_only:
download_urls([real_url], title, ext, size, output_dir, merge = merge)
site_info = "Dailymotion.com"
download = dailymotion_download
download_playlist = playlist_not_supported('dailymotion')
| #!/usr/bin/env python
__all__ = ['dailymotion_download']
from ..common import *
def dailymotion_download(url, output_dir = '.', merge = True, info_only = False):
html = get_html(url)
html = parse.unquote(html).replace('\/', '/')
title = r1(r'meta property="og:title" content="([^"]+)"', html)
title = escape_file_path(title)
for quality in ['hd720URL', 'hqURL', 'sdURL']:
real_url = r1(r',\"' + quality + '\"\:\"([^\"]+?)\",', html)
if real_url:
break
type, ext, size = url_info(real_url)
print_info(site_info, title, type, size)
if not info_only:
download_urls([real_url], title, ext, size, output_dir, merge = merge)
site_info = "Dailymotion.com"
download = dailymotion_download
download_playlist = playlist_not_supported('dailymotion')
| Python | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.