commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4 values | license stringclasses 13 values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
46a30fa8d52c1c36e110a8e028444b27e39c9b6d | radio/management/commands/export_talkgroups.py | radio/management/commands/export_talkgroups.py | import sys
import datetime
import csv
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.utils import timezone
from radio.models import *
class Command(BaseCommand):
help = 'Import talkgroup info'
def add_arguments(self, parser):
parser.add_argument('file')
parser.add_argument(
'--system',
type=int,
default=-1,
help='Export talkgroups from only this system',
)
def handle(self, *args, **options):
export_tg_file(options)
def export_tg_file(options):
''' Using the talkgroup file from trunk-recorder'''
file_name = options['file']
system = options['system']
talkgroups = TalkGroup.objects.all()
if system >= 0:
talkgroups = talkgroups.filter(system=system)
with open(file_name, "w") as tg_file:
for t in talkgroups:
alpha = t.alpha_tag
description = t.description
hex_val = str(hex(t.dec_id))[2:-1].zfill(3)
try:
alpha = alpha.rstrip()
except AttributeError:
pass
try:
description = description.rstrip()
except AttributeError:
pass
common = ''
if(t.common_name):
common = t.common_name
tg_file.write("{},{},{},{},{},{}\n".format(t.dec_id,hex_val,t.mode,alpha,description,t.priority))
| import sys
import datetime
import csv
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.utils import timezone
from radio.models import *
class Command(BaseCommand):
help = 'Export talkgroup info'
def add_arguments(self, parser):
parser.add_argument('file')
parser.add_argument(
'--system',
type=int,
default=-1,
help='Export talkgroups from only this system',
)
def handle(self, *args, **options):
export_tg_file(self, options)
def export_tg_file(self, options):
''' Using the talkgroup file from trunk-recorder'''
file_name = options['file']
system = options['system']
talkgroups = TalkGroup.objects.all()
if system >= 0:
talkgroups = talkgroups.filter(system=system)
self.stdout.write("Exporting talkgroups for system #{}".format(system))
else:
self.stdout.write("Exporting talkgroups for all systems")
with open(file_name, "w") as tg_file:
for t in talkgroups:
alpha = t.alpha_tag
description = t.description
hex_val = str(hex(t.dec_id))[2:-1].zfill(3)
try:
alpha = alpha.rstrip()
except AttributeError:
pass
try:
description = description.rstrip()
except AttributeError:
pass
common = ''
if(t.common_name):
common = t.common_name
tg_file.write("{},{},{},{},{},{}\n".format(t.dec_id,hex_val,t.mode,alpha,description,t.priority))
| Update help line and print system number | Update help line and print system number
| Python | mit | ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player | ---
+++
@@ -8,7 +8,7 @@
from radio.models import *
class Command(BaseCommand):
- help = 'Import talkgroup info'
+ help = 'Export talkgroup info'
def add_arguments(self, parser):
parser.add_argument('file')
@@ -21,16 +21,19 @@
def handle(self, *args, **options):
- export_tg_file(options)
+ export_tg_file(self, options)
-def export_tg_file(options):
+def export_tg_file(self, options):
''' Using the talkgroup file from trunk-recorder'''
file_name = options['file']
system = options['system']
talkgroups = TalkGroup.objects.all()
if system >= 0:
talkgroups = talkgroups.filter(system=system)
+ self.stdout.write("Exporting talkgroups for system #{}".format(system))
+ else:
+ self.stdout.write("Exporting talkgroups for all systems")
with open(file_name, "w") as tg_file:
for t in talkgroups:
alpha = t.alpha_tag |
0c29ab9f906ca73605e3626c06dd14f573d5fa8f | TM1py/Exceptions/Exceptions.py | TM1py/Exceptions/Exceptions.py | # -*- coding: utf-8 -*-
# TM1py Exceptions are defined here
class TM1pyException(Exception):
""" The default exception for TM1py
"""
def __init__(self, response, status_code, reason, headers):
self._response = response
self._status_code = status_code
self._reason = reason
self._headers = headers
@property
def status_code(self):
return self._status_code
@property
def reason(self):
return self.reason
@property
def response(self):
return self._response
@property
def headers(self):
return self._headers
def __str__(self):
return "Text: {} Status Code: {} Reason: {}".format(self._response, self._status_code, self._reason)
| # -*- coding: utf-8 -*-
# TM1py Exceptions are defined here
class TM1pyException(Exception):
""" The default exception for TM1py
"""
def __init__(self, response, status_code, reason, headers):
self._response = response
self._status_code = status_code
self._reason = reason
self._headers = headers
@property
def status_code(self):
return self._status_code
@property
def reason(self):
return self.reason
@property
def response(self):
return self._response
@property
def headers(self):
return self._headers
def __str__(self):
return "Text: {} Status Code: {} Reason: {} Headers {}".format(self._response,
self._status_code,
self._reason,
self._headers)
| Update to expand exception string | Update to expand exception string
| Python | mit | OLAPLINE/TM1py | ---
+++
@@ -30,4 +30,7 @@
return self._headers
def __str__(self):
- return "Text: {} Status Code: {} Reason: {}".format(self._response, self._status_code, self._reason)
+ return "Text: {} Status Code: {} Reason: {} Headers {}".format(self._response,
+ self._status_code,
+ self._reason,
+ self._headers) |
188ac85b8e8f82a06426467554d608d713d258ef | test/test_get_new.py | test/test_get_new.py | from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
from .pytest_skipif import needinternet
from .pytest_makevers import fixture_update_dir
import os
import sys
import pytest
@needinternet
def test_check_get_new(fixture_update_dir):
"""Test that gets new version from internet"""
package=fixture_update_dir("0.0.1")
launch = Launcher('filling up the boring replacements',
r'http://rlee287.github.io/pyautoupdate/testing/')
launch._get_new()
with open(os.path.abspath("downloads/extradir/blah.py"), "r") as file_code:
file_text=file_code.read()
assert "new version" in file_text
@needinternet
def test_check_get_invalid_archive(fixture_update_dir):
"""Test that gets new version from internet"""
package=fixture_update_dir("0.0.1")
launch = Launcher('what file? hahahaha',
r'http://rlee287.github.io/pyautoupdate/testing2/',
newfiles="project.tar.gz")
launch._get_new()
assert os.path.isfile("project.tar.gz.dump")
os.remove("project.tar.gz.dump")
| from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
from .pytest_skipif import needinternet
from .pytest_makevers import fixture_update_dir
import os
@needinternet
def test_check_get_new(fixture_update_dir):
"""Test that gets new version from internet"""
package=fixture_update_dir("0.0.1")
launch = Launcher('filling up the boring replacements',
r'http://rlee287.github.io/pyautoupdate/testing/')
launch._get_new()
with open(os.path.abspath("downloads/extradir/blah.py"), "r") as file_code:
file_text=file_code.read()
assert "new version" in file_text
@needinternet
def test_check_get_invalid_archive(fixture_update_dir):
"""Test that gets new version from internet"""
package=fixture_update_dir("0.0.1")
launch = Launcher('what file? hahahaha',
r'http://rlee287.github.io/pyautoupdate/testing2/',
newfiles="project.tar.gz")
launch._get_new()
assert os.path.isfile("project.tar.gz.dump")
os.remove("project.tar.gz.dump")
| Remove unused imports from test_check_get_new | Remove unused imports from test_check_get_new
| Python | lgpl-2.1 | rlee287/pyautoupdate,rlee287/pyautoupdate | ---
+++
@@ -5,9 +5,6 @@
from .pytest_makevers import fixture_update_dir
import os
-import sys
-
-import pytest
@needinternet
def test_check_get_new(fixture_update_dir): |
4cfc0967cef576ab5d6ddd0fff7d648e77739727 | test_scriptrunner.py | test_scriptrunner.py | from antZoo.ant import AntJobRunner
ant = AntJobRunner( None )
ant.start()
class Job:
def __init__( self, source ):
self.source = source
j = Job( "/Users/elchupa/code/school/antZoo/localenv/bin/python /Users/elchupa/code/school/antZoo/example_code/word_count.py" )
ant.push( j )
for i in range( 100 ):
ant.new_task( "this is a test\n" )
print "Done sending tasks."
ant.finish()
ant._runner.join()
| from antZoo.ant import AntJobRunner
ant = AntJobRunner( None )
ant.start()
class Job:
def __init__( self, source ):
self.source = source
j = Job( "/Users/elchupa/code/school/antZoo/localenv/bin/python /Users/elchupa/code/school/antZoo/example_code/word_count.py" )
ant.push( j )
for i in range( 100 ):
ant.new_task( "this is a test\n" )
print "Done sending tasks."
ant.finish()
ant._runner.join()
j = Job( "/Users/elchupa/code/school/antZoo/localenv/bin/python /Users/elchupa/code/school/antZoo/example_code/word_count.py" )
ant.push( j )
for i in range( 100 ):
ant.new_task( "this is another test that is to be run :D\n" )
print "Done sending tasks."
ant.finish()
ant._runner.join()
| Test runs two jobs and 200 tasks | Test runs two jobs and 200 tasks
| Python | mit | streed/antZoo,streed/antZoo | ---
+++
@@ -18,3 +18,14 @@
print "Done sending tasks."
ant.finish()
ant._runner.join()
+
+j = Job( "/Users/elchupa/code/school/antZoo/localenv/bin/python /Users/elchupa/code/school/antZoo/example_code/word_count.py" )
+
+ant.push( j )
+
+for i in range( 100 ):
+ ant.new_task( "this is another test that is to be run :D\n" )
+
+print "Done sending tasks."
+ant.finish()
+ant._runner.join() |
4661a04d159e0583f16c28d087427fab31c676f6 | foodsaving/management/tests/test_makemessages.py | foodsaving/management/tests/test_makemessages.py | from django.test import TestCase
from ..commands.makemessages import Command as MakeMessagesCommand
class CustomMakeMessagesTest(TestCase):
def test_update_options(self):
options = {
'locale': [],
}
modified_options = MakeMessagesCommand.update_options(**options)
self.assertIn('jinja', modified_options['extensions'])
self.assertIn('en', modified_options['locale'])
options['extensions'] = ['py']
modified_options_with_initial_extension = MakeMessagesCommand.update_options(**options)
self.assertIn('jinja', modified_options_with_initial_extension['extensions'])
| from unittest.mock import patch
from django.test import TestCase
from ..commands.makemessages import Command as MakeMessagesCommand
from django_jinja.management.commands.makemessages import Command as DjangoJinjaMakeMessagesCommand
makemessages = MakeMessagesCommand
django_jinja_makemessages = DjangoJinjaMakeMessagesCommand
class CustomMakeMessagesTest(TestCase):
def test_update_options(self):
options = {
'locale': [],
}
modified_options = MakeMessagesCommand.update_options(**options)
self.assertIn('jinja', modified_options['extensions'])
self.assertIn('en', modified_options['locale'])
options['extensions'] = ['py']
modified_options_with_initial_extension = MakeMessagesCommand.update_options(**options)
self.assertIn('jinja', modified_options_with_initial_extension['extensions'])
@patch(__name__ + '.django_jinja_makemessages.handle')
@patch(__name__ + '.makemessages.update_options', return_value={})
def test_handle(self, mock1, mock2):
MakeMessagesCommand.handle(MakeMessagesCommand())
assert MakeMessagesCommand.update_options.called
assert DjangoJinjaMakeMessagesCommand.handle.called
| Add additional test to increase test coverage | Add additional test to increase test coverage
| Python | agpl-3.0 | yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend | ---
+++
@@ -1,6 +1,11 @@
+from unittest.mock import patch
from django.test import TestCase
from ..commands.makemessages import Command as MakeMessagesCommand
+from django_jinja.management.commands.makemessages import Command as DjangoJinjaMakeMessagesCommand
+
+makemessages = MakeMessagesCommand
+django_jinja_makemessages = DjangoJinjaMakeMessagesCommand
class CustomMakeMessagesTest(TestCase):
@@ -16,3 +21,10 @@
options['extensions'] = ['py']
modified_options_with_initial_extension = MakeMessagesCommand.update_options(**options)
self.assertIn('jinja', modified_options_with_initial_extension['extensions'])
+
+ @patch(__name__ + '.django_jinja_makemessages.handle')
+ @patch(__name__ + '.makemessages.update_options', return_value={})
+ def test_handle(self, mock1, mock2):
+ MakeMessagesCommand.handle(MakeMessagesCommand())
+ assert MakeMessagesCommand.update_options.called
+ assert DjangoJinjaMakeMessagesCommand.handle.called |
6f0d09ff5f81518daf30b00311ce4ac052e08c14 | admission_notes/models.py | admission_notes/models.py | import datetime
#from labsys.patients import Patient
from django.db import models
class AdmissionNote(models.Model):
id_gal = models.CharField(max_length=30)
requester = models.CharField(
max_length=255,
help_text="LACEN ou instituto que solicitou o exame",
)
health_unit = models.CharField(
max_length=255,
help_text="unidade onde o paciente foi avaliado",
)
state = models.CharField(max_length=2)
city = models.CharField(max_length=255)
admission_date = models.DateField(
verbose_name="Data de entrada (LVRS)",
help_text="quando a amostra chegou no LVRS",
null=True,
blank=True,
)
def __str__(self):
return "ID Gal: {}".format(self.id_gal)
| import datetime
#from labsys.patients import Patient
from django.db import models
class AdmissionNote(models.Model):
id_gal = models.CharField(
'Número da requisição (GAL interno)',
max_length=30
)
requester = models.CharField(
'Instituto solicitante',
max_length=255,
help_text='LACEN ou instituto que solicitou o exame',
)
health_unit = models.CharField(
'Unidade de saúde',
max_length=255,
help_text='unidade onde o paciente foi avaliado',
)
state = models.CharField(max_length=2)
city = models.CharField(max_length=255)
admission_date = models.DateField(
'Data de entrada (LVRS)',
help_text='quando a amostra chegou no LVRS',
null=True,
blank=True,
)
def __str__(self):
return "ID Gal: {}".format(self.id_gal)
| Rename fields and remove verbose_name attr (1st arg is it by default) | :art: Rename fields and remove verbose_name attr (1st arg is it by default)
| Python | mit | gems-uff/labsys,gems-uff/labsys,gems-uff/labsys | ---
+++
@@ -4,21 +4,27 @@
from django.db import models
+
class AdmissionNote(models.Model):
- id_gal = models.CharField(max_length=30)
+ id_gal = models.CharField(
+ 'Número da requisição (GAL interno)',
+ max_length=30
+ )
requester = models.CharField(
+ 'Instituto solicitante',
max_length=255,
- help_text="LACEN ou instituto que solicitou o exame",
+ help_text='LACEN ou instituto que solicitou o exame',
)
health_unit = models.CharField(
+ 'Unidade de saúde',
max_length=255,
- help_text="unidade onde o paciente foi avaliado",
+ help_text='unidade onde o paciente foi avaliado',
)
state = models.CharField(max_length=2)
city = models.CharField(max_length=255)
admission_date = models.DateField(
- verbose_name="Data de entrada (LVRS)",
- help_text="quando a amostra chegou no LVRS",
+ 'Data de entrada (LVRS)',
+ help_text='quando a amostra chegou no LVRS',
null=True,
blank=True,
) |
85878d23d598b7d7622f8aa70ef82b7a627aed23 | integration-test/912-missing-building-part.py | integration-test/912-missing-building-part.py | # http://www.openstreetmap.org/way/287494678
z = 18
x = 77193
y = 98529
while z >= 16:
assert_has_feature(
z, x, y, 'buildings',
{ 'kind': 'building',
'id': 287494678 })
z -= 1
x /= 2
y /= 2
| # http://www.openstreetmap.org/way/287494678
z = 18
x = 77193
y = 98529
while z >= 16:
assert_has_feature(
z, x, y, 'buildings',
{ 'kind': 'building_part',
'id': 287494678,
'min_zoom': 16 })
z -= 1
x /= 2
y /= 2
| Update feature kind to account for normalisation and test min_zoom. | Update feature kind to account for normalisation and test min_zoom.
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource | ---
+++
@@ -5,8 +5,9 @@
while z >= 16:
assert_has_feature(
z, x, y, 'buildings',
- { 'kind': 'building',
- 'id': 287494678 })
+ { 'kind': 'building_part',
+ 'id': 287494678,
+ 'min_zoom': 16 })
z -= 1
x /= 2 |
2a0c9cc447e1dffe2eb03c49c0c6801f4303a620 | plugins/imagetypes.py | plugins/imagetypes.py | #
# Copyright (c) SAS Institute 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.
#
"""
List image types
"""
from rbuild import pluginapi
from rbuild.pluginapi import command
class ListImageTypesCommand(command.ListCommand):
help = "List image types"
resource = "imagetypes"
listFields = ("description", "name")
class ImageTypes(pluginapi.Plugin):
name = 'imagetypes'
def initialize(self):
for command, subcommand, commandClass in (
('list', 'imagetypes', ListImageTypesCommand),
):
cmd = self.handle.Commands.getCommandClass(command)
cmd.registerSubCommand(subcommand, commandClass)
def list(self):
rb = self.handle.facade.rbuilder
return [type for type in rb.getImageTypes() if type.name]
| #
# Copyright (c) SAS Institute 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.
#
"""
List image types
"""
from rbuild import pluginapi
from rbuild.pluginapi import command
class ListImageTypesCommand(command.ListCommand):
help = "List image types"
resource = "imagetypes"
listFields = ("name", "description")
class ImageTypes(pluginapi.Plugin):
name = 'imagetypes'
def initialize(self):
for command, subcommand, commandClass in (
('list', 'imagetypes', ListImageTypesCommand),
):
cmd = self.handle.Commands.getCommandClass(command)
cmd.registerSubCommand(subcommand, commandClass)
def list(self):
rb = self.handle.facade.rbuilder
return [type for type in rb.getImageTypes() if type.name]
| Swap order of name and description when listing image types | Swap order of name and description when listing image types
Uses the same order as target types, which puts the most important information,
the name, in front.
Refs APPENG-3419
| Python | apache-2.0 | sassoftware/rbuild,sassoftware/rbuild | ---
+++
@@ -25,7 +25,7 @@
class ListImageTypesCommand(command.ListCommand):
help = "List image types"
resource = "imagetypes"
- listFields = ("description", "name")
+ listFields = ("name", "description")
class ImageTypes(pluginapi.Plugin): |
405cc83e1532f5277d180964907e964ded5f5da7 | routeros_api/api_communicator/async_decorator.py | routeros_api/api_communicator/async_decorator.py | class AsyncApiCommunicator(object):
def __init__(self, inner):
self.inner = inner
def call(self, *args, **kwargs):
tag = self.inner.send(*args, **kwargs)
return ResponsePromise(self.inner, tag)
class ResponsePromise(object):
def __init__(self, receiver, tag):
self.receiver = receiver
self.tag = tag
def get(self):
return self.receiver.receive(self.tag)
| class AsyncApiCommunicator(object):
def __init__(self, inner):
self.inner = inner
def call(self, *args, **kwargs):
tag = self.inner.send(*args, **kwargs)
return ResponsePromise(self.inner, tag)
class ResponsePromise(object):
def __init__(self, receiver, tag):
self.receiver = receiver
self.tag = tag
self.response = None
def get(self):
if self.response is None:
self.response = self.receiver.receive(self.tag)
return self.response
| Allow to run get on promise multiple times. | Allow to run get on promise multiple times.
| Python | mit | kramarz/RouterOS-api,pozytywnie/RouterOS-api,socialwifi/RouterOS-api | ---
+++
@@ -10,6 +10,9 @@
def __init__(self, receiver, tag):
self.receiver = receiver
self.tag = tag
+ self.response = None
def get(self):
- return self.receiver.receive(self.tag)
+ if self.response is None:
+ self.response = self.receiver.receive(self.tag)
+ return self.response |
0ed72241dc9f540615954f58995d96401d954a41 | courtreader/opener.py | courtreader/opener.py | import cookielib
import os
import pickle
import urllib2
class Opener:
user_agent = u"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; " + \
u"en-US; rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11"
def __init__(self, name):
self.name = name
# Create page opener that stores cookie
self.cookieJar = cookielib.CookieJar()
cookie_processor = urllib2.HTTPCookieProcessor(self.cookieJar)
self.opener = urllib2.build_opener(cookie_processor)
self.opener.addheaders = [('User-Agent', Opener.user_agent)]
# Try to load cookies
#if os.path.isfile(self.name + '.cookie'):
# with open(self.name + '.cookie', 'r') as f:
# for cookie in pickle.loads(f.read()):
# self.cookieJar.set_cookie(cookie)
def set_cookie(self, name, value):
for cookie in self.cookieJar:
if cookie.name == name:
cookie.value = value
def save_cookies(self):
with open(self.name + '.cookie', 'w') as f:
f.write(pickle.dumps(list(self.cookieJar)))
def open(self, *args):
url = args[0]
if len(args) == 2:
data = args[1]
return self.opener.open(url, data)
return self.opener.open(url)
| import cookielib
import os
import pickle
import mechanize
class Opener:
def __init__(self, name):
self.opener = mechanize.Browser()
self.opener.set_handle_robots(False)
def set_cookie(self, name, value):
self.opener.set_cookie(str(name) + '=' + str(value))
def save_cookies(self):
return
def open(self, *args):
url = args[0]
if len(args) == 2:
data = args[1]
return self.opener.open(url, data)
return self.opener.open(url)
| Use mechanize instead of urllib2 | Use mechanize instead of urllib2
| Python | mit | bschoenfeld/va-court-scraper,bschoenfeld/va-court-scraper | ---
+++
@@ -1,34 +1,18 @@
import cookielib
import os
import pickle
-import urllib2
+import mechanize
class Opener:
- user_agent = u"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; " + \
- u"en-US; rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11"
-
def __init__(self, name):
- self.name = name
- # Create page opener that stores cookie
- self.cookieJar = cookielib.CookieJar()
- cookie_processor = urllib2.HTTPCookieProcessor(self.cookieJar)
- self.opener = urllib2.build_opener(cookie_processor)
- self.opener.addheaders = [('User-Agent', Opener.user_agent)]
-
- # Try to load cookies
- #if os.path.isfile(self.name + '.cookie'):
- # with open(self.name + '.cookie', 'r') as f:
- # for cookie in pickle.loads(f.read()):
- # self.cookieJar.set_cookie(cookie)
+ self.opener = mechanize.Browser()
+ self.opener.set_handle_robots(False)
def set_cookie(self, name, value):
- for cookie in self.cookieJar:
- if cookie.name == name:
- cookie.value = value
+ self.opener.set_cookie(str(name) + '=' + str(value))
def save_cookies(self):
- with open(self.name + '.cookie', 'w') as f:
- f.write(pickle.dumps(list(self.cookieJar)))
+ return
def open(self, *args):
url = args[0] |
90b9a1e6638fd638450b46c6b12439eeb8e40f90 | cumulusci/tasks/github/tests/test_pull_request.py | cumulusci/tasks/github/tests/test_pull_request.py | import mock
import unittest
from cumulusci.core.config import ServiceConfig
from cumulusci.core.config import TaskConfig
from cumulusci.tasks.github import PullRequests
from cumulusci.tests.util import create_project_config
@mock.patch("cumulusci.tasks.github.base.get_github_api_for_user", mock.Mock())
class TestPullRequests(unittest.TestCase):
project_config = create_project_config()
project_config.keychain.set_service(
"github",
ServiceConfig(
{
"username": "TestUser",
"password": "TestPass",
"email": "testuser@testdomain.com",
}
),
)
task_config = TaskConfig()
task = PullRequests(project_config, task_config)
repo = mock.Mock()
repo.pull_requests.return_value = [mock.Mock(number=1, title="Test PR")]
task.get_repo = mock.Mock(return_value=repo)
task.logger = mock.Mock()
task()
task.logger.info.assert_called_with("#1: Test PR")
| import mock
import unittest
from cumulusci.core.config import ServiceConfig
from cumulusci.core.config import TaskConfig
from cumulusci.tasks.github import PullRequests
from cumulusci.tests.util import create_project_config
class TestPullRequests(unittest.TestCase):
def test_run_task(self):
project_config = create_project_config()
project_config.keychain.set_service(
"github",
ServiceConfig(
{
"username": "TestUser",
"password": "TestPass",
"email": "testuser@testdomain.com",
}
),
)
task_config = TaskConfig()
task = PullRequests(project_config, task_config)
repo = mock.Mock()
repo.pull_requests.return_value = [mock.Mock(number=1, title="Test PR")]
task.get_repo = mock.Mock(return_value=repo)
task.logger = mock.Mock()
task()
task.logger.info.assert_called_with("#1: Test PR")
| Fix test that wasn't running | Fix test that wasn't running
| Python | bsd-3-clause | SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI | ---
+++
@@ -7,24 +7,24 @@
from cumulusci.tests.util import create_project_config
-@mock.patch("cumulusci.tasks.github.base.get_github_api_for_user", mock.Mock())
class TestPullRequests(unittest.TestCase):
- project_config = create_project_config()
- project_config.keychain.set_service(
- "github",
- ServiceConfig(
- {
- "username": "TestUser",
- "password": "TestPass",
- "email": "testuser@testdomain.com",
- }
- ),
- )
- task_config = TaskConfig()
- task = PullRequests(project_config, task_config)
- repo = mock.Mock()
- repo.pull_requests.return_value = [mock.Mock(number=1, title="Test PR")]
- task.get_repo = mock.Mock(return_value=repo)
- task.logger = mock.Mock()
- task()
- task.logger.info.assert_called_with("#1: Test PR")
+ def test_run_task(self):
+ project_config = create_project_config()
+ project_config.keychain.set_service(
+ "github",
+ ServiceConfig(
+ {
+ "username": "TestUser",
+ "password": "TestPass",
+ "email": "testuser@testdomain.com",
+ }
+ ),
+ )
+ task_config = TaskConfig()
+ task = PullRequests(project_config, task_config)
+ repo = mock.Mock()
+ repo.pull_requests.return_value = [mock.Mock(number=1, title="Test PR")]
+ task.get_repo = mock.Mock(return_value=repo)
+ task.logger = mock.Mock()
+ task()
+ task.logger.info.assert_called_with("#1: Test PR") |
5839e1e551df96b3766722d8a87d42b12b3cfa5d | cronos/accounts/models.py | cronos/accounts/models.py | from cronos.teilar.models import Departments
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.ForeignKey(User, unique = True)
dionysos_username = models.CharField(max_length = 15, unique = True)
dionysos_password = models.CharField(max_length = 30)
eclass_username = models.CharField(max_length = 30, null = True, blank = True)
eclass_password = models.CharField(max_length = 30, null = True, blank = True)
eclass_lessons = models.TextField(null = True, blank = True)
introduction_year = models.CharField(max_length = 5)
registration_number = models.CharField(max_length = 8)
school = models.ForeignKey(Departments)
semester = models.CharField(max_length = 2)
webmail_username = models.CharField(max_length = 30, null = True, blank = True)
webmail_password = models.CharField(max_length = 30, null = True, blank = True)
teacher_announcements = models.TextField(null = True, blank = True)
other_announcements = models.TextField(null = True, blank = True)
declaration = models.TextField(null = True, blank = True)
grades = models.TextField(null = True, blank = True)
def __unicode__(self):
return self.user.username
| from cronos.teilar.models import Departments, Teachers, EclassLessons, Websites
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.OneToOneField(User, primary_key = True, unique = True)
dionysos_username = models.CharField(max_length = 15, unique = True)
dionysos_password = models.CharField(max_length = 30)
eclass_username = models.CharField(max_length = 30, null = True, blank = True)
eclass_password = models.CharField(max_length = 30, null = True, blank = True)
eclass_lessons = models.ManyToManyField(EclassLessons)
introduction_year = models.CharField(max_length = 5)
registration_number = models.CharField(max_length = 8)
school = models.ForeignKey(Departments)
semester = models.CharField(max_length = 2)
webmail_username = models.CharField(max_length = 30, null = True, blank = True)
webmail_password = models.CharField(max_length = 30, null = True, blank = True)
teacher_announcements = models.ManyToManyField(Teachers)
other_announcements = models.ManyToManyField(Websites)
declaration = models.TextField(null = True, blank = True)
grades = models.TextField(null = True, blank = True)
def __unicode__(self):
return self.user.username
| Improve db relations: - User->UserProfile is One to One - UserProfile <-> Teachers/Websites/EclassLessons are Many to Many | Improve db relations:
- User->UserProfile is One to One
- UserProfile <-> Teachers/Websites/EclassLessons are Many to Many
| Python | agpl-3.0 | LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr | ---
+++
@@ -1,22 +1,22 @@
-from cronos.teilar.models import Departments
+from cronos.teilar.models import Departments, Teachers, EclassLessons, Websites
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
- user = models.ForeignKey(User, unique = True)
+ user = models.OneToOneField(User, primary_key = True, unique = True)
dionysos_username = models.CharField(max_length = 15, unique = True)
dionysos_password = models.CharField(max_length = 30)
eclass_username = models.CharField(max_length = 30, null = True, blank = True)
eclass_password = models.CharField(max_length = 30, null = True, blank = True)
- eclass_lessons = models.TextField(null = True, blank = True)
+ eclass_lessons = models.ManyToManyField(EclassLessons)
introduction_year = models.CharField(max_length = 5)
registration_number = models.CharField(max_length = 8)
school = models.ForeignKey(Departments)
semester = models.CharField(max_length = 2)
webmail_username = models.CharField(max_length = 30, null = True, blank = True)
webmail_password = models.CharField(max_length = 30, null = True, blank = True)
- teacher_announcements = models.TextField(null = True, blank = True)
- other_announcements = models.TextField(null = True, blank = True)
+ teacher_announcements = models.ManyToManyField(Teachers)
+ other_announcements = models.ManyToManyField(Websites)
declaration = models.TextField(null = True, blank = True)
grades = models.TextField(null = True, blank = True)
|
4c7ea928782c976919a055379a921983c5bbf97a | memegen/routes/_cache.py | memegen/routes/_cache.py | import logging
import yorm
from yorm.types import List, Object
log = logging.getLogger(__name__)
@yorm.attr(items=List.of_type(Object))
@yorm.sync("data/images/cache.yml")
class Cache:
SIZE = 9
def __init__(self):
self.items = []
def add(self, **kwargs):
log.info("Caching: %s", kwargs)
self.items.insert(0, kwargs)
while len(self.items) > self.SIZE:
self.items.pop()
yorm.save(self)
def get(self, index):
log.info("Getting cache index: %s", index)
try:
data = self.items[index]
except IndexError:
data = {}
log.info("Retrieved cache: %s", data)
return data
| import logging
import yorm
from yorm.types import List, Object
log = logging.getLogger(__name__)
@yorm.attr(items=List.of_type(Object))
@yorm.sync("data/images/cache.yml")
class Cache:
SIZE = 9
def __init__(self):
self.items = []
def add(self, **kwargs):
if kwargs['key'] == 'custom':
return
log.info("Caching: %s", kwargs)
self.items.insert(0, kwargs)
while len(self.items) > self.SIZE:
self.items.pop()
yorm.save(self)
def get(self, index):
log.info("Getting cache index: %s", index)
try:
data = self.items[index]
except IndexError:
data = {}
log.info("Retrieved cache: %s", data)
return data
| Disable caching on custom images | Disable caching on custom images
| Python | mit | DanLindeman/memegen,DanLindeman/memegen,DanLindeman/memegen,DanLindeman/memegen | ---
+++
@@ -17,6 +17,9 @@
self.items = []
def add(self, **kwargs):
+ if kwargs['key'] == 'custom':
+ return
+
log.info("Caching: %s", kwargs)
self.items.insert(0, kwargs) |
fd11e57f736fff6ef23972dee642554c6e8f5495 | urls.py | urls.py | from django.conf.urls import url
from . import views
from django.conf import settings
urlpatterns=[
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^users/$', views.users, name='users'),
url(r'^users/(?P<username>[^/]*)/$', views.user, name='user'),
]
| from django.conf.urls import url
from . import views
from django.conf import settings
urlpatterns=[
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^users/$', views.users, name='users'),
url(r'^users/(?P<user>[^/]*)/$', views.user, name='user'),
url(r'^users/(?P<user>[^/]*)/prefs/$', views.prefs, name='prefs'),
url(r'^users/(?P<user>[^/]*)/prefs/(?P<prefId>[^/]*)/$', views.pref, name='pref'),
]
| Add the prefs and pref url | Add the prefs and pref url
| Python | apache-2.0 | kensonman/webframe,kensonman/webframe,kensonman/webframe | ---
+++
@@ -6,5 +6,7 @@
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^users/$', views.users, name='users'),
- url(r'^users/(?P<username>[^/]*)/$', views.user, name='user'),
+ url(r'^users/(?P<user>[^/]*)/$', views.user, name='user'),
+ url(r'^users/(?P<user>[^/]*)/prefs/$', views.prefs, name='prefs'),
+ url(r'^users/(?P<user>[^/]*)/prefs/(?P<prefId>[^/]*)/$', views.pref, name='pref'),
] |
db2fdb6a1df9324a4661967069488e981d06b0f1 | bi_view_editor/wizard/wizard_ir_model_menu_create.py | bi_view_editor/wizard/wizard_ir_model_menu_create.py | # -*- coding: utf-8 -*-
# Copyright 2017 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class WizardModelMenuCreate(models.TransientModel):
_inherit = 'wizard.ir.model.menu.create'
@api.multi
def menu_create(self):
if self._context.get('active_model') == 'bve.view':
self.ensure_one()
active_id = self._context.get('active_id')
bve_view = self.env['bve.view'].browse(active_id)
self.env['ir.ui.menu'].create({
'name': self.name,
'parent_id': self.menu_id.id,
'action': 'ir.actions.act_window,%d' % (bve_view.action_id,)
})
return {'type': 'ir.actions.act_window_close'}
return super(WizardModelMenuCreate, self).menu_create()
@api.model
def default_get(self, fields_list):
defaults = super(WizardModelMenuCreate, self).default_get(fields_list)
if self._context.get('active_model') == 'bve.view':
active_id = self._context.get('active_id')
bve_view = self.env['bve.view'].browse(active_id)
defaults.setdefault('name', bve_view.name)
return defaults
| # -*- coding: utf-8 -*-
# Copyright 2017 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class WizardModelMenuCreate(models.TransientModel):
_inherit = 'wizard.ir.model.menu.create'
@api.multi
def menu_create(self):
if self._context.get('active_model') == 'bve.view':
self.ensure_one()
active_id = self._context.get('active_id')
bve_view = self.env['bve.view'].browse(active_id)
self.env['ir.ui.menu'].create({
'name': self.name,
'parent_id': self.menu_id.id,
'action': 'ir.actions.act_window,%d' % (bve_view.action_id,)
})
return {'type': 'ir.actions.client', 'tag': 'reload'}
return super(WizardModelMenuCreate, self).menu_create()
@api.model
def default_get(self, fields_list):
defaults = super(WizardModelMenuCreate, self).default_get(fields_list)
if self._context.get('active_model') == 'bve.view':
active_id = self._context.get('active_id')
bve_view = self.env['bve.view'].browse(active_id)
defaults.setdefault('name', bve_view.name)
return defaults
| Refresh page when creating menus, module bi_view_editor | Refresh page when creating menus, module bi_view_editor
| Python | agpl-3.0 | VitalPet/addons-onestein,VitalPet/addons-onestein,VitalPet/addons-onestein | ---
+++
@@ -19,7 +19,7 @@
'parent_id': self.menu_id.id,
'action': 'ir.actions.act_window,%d' % (bve_view.action_id,)
})
- return {'type': 'ir.actions.act_window_close'}
+ return {'type': 'ir.actions.client', 'tag': 'reload'}
return super(WizardModelMenuCreate, self).menu_create()
@api.model |
e01eb66aeb853261c80cb476e71f91a9569b1676 | client.py | client.py | import requests
from Adafruit_BMP085 import BMP085
import json
#initialise sensor
print ('Initialising sensor...')
bmp = BMP085(0x77, 3) # ULTRAHIRES Mode
print ('Reading sensor...')
temp = bmp.readTemperature()
pressure = bmp.readPressure()
payload = {'temperature': temp, 'pressure': pressure}
print ('POSTing data...')
server_url = 'http://zephos.duckdns.org:5000/temperature_pressure'
r = requests.post(server_url, data=json.dumps(payload))
print(r.status_code)
| import requests
from Adafruit_BMP085 import BMP085
import json
#initialise sensor
print ('Initialising sensor...')
bmp = BMP085(0x77, 3) # ULTRAHIRES Mode
print ('Reading sensor...')
temp = bmp.readTemperature()
pressure = bmp.readPressure()
payload = {'temperature': temp, 'pressure': pressure}
print ('POSTing data...')
server_url = 'http://zephos.duckdns.org:5000/temperature_pressure'
headers = {'content-type': 'application/json'}
r = requests.post(server_url, data=json.dumps(payload), headers=headers)
print(r.status_code)
| Set content-type header of POST. | Set content-type header of POST.
| Python | mit | JTKBowers/kelvin | ---
+++
@@ -14,5 +14,6 @@
print ('POSTing data...')
server_url = 'http://zephos.duckdns.org:5000/temperature_pressure'
-r = requests.post(server_url, data=json.dumps(payload))
+headers = {'content-type': 'application/json'}
+r = requests.post(server_url, data=json.dumps(payload), headers=headers)
print(r.status_code) |
c7ccfd82298c2c8c90c230f846ca9319bcf40441 | lib/tagnews/__init__.py | lib/tagnews/__init__.py | from . import utils
from . import crimetype
from .crimetype.tag import CrimeTags
from .geoloc.tag import GeoCoder, get_lat_longs_from_geostrings
from .utils.load_data import load_data
from .utils.load_data import load_ner_data
from .utils.load_vectorizer import load_glove
__version__ = '1.0.2'
def test(verbosity=None, **kwargs):
"""run the test suite"""
import pytest
args = kwargs.pop('argv', [])
if verbosity:
args += ['-' + 'v' * verbosity]
return pytest.main(args, **kwargs)
test.__test__ = False # pytest: this function is not a test
| from . import utils
from . import crimetype
from .crimetype.tag import CrimeTags
from .geoloc.tag import GeoCoder, get_lat_longs_from_geostrings
from .utils.load_data import load_data
from .utils.load_data import load_ner_data
from .utils.load_vectorizer import load_glove
__version__ = '1.0.2'
| Remove unused test function at top level. | Remove unused test function at top level.
| Python | mit | kbrose/article-tagging,kbrose/article-tagging,chicago-justice-project/article-tagging,chicago-justice-project/article-tagging | ---
+++
@@ -8,18 +8,3 @@
from .utils.load_vectorizer import load_glove
__version__ = '1.0.2'
-
-def test(verbosity=None, **kwargs):
- """run the test suite"""
-
- import pytest
-
- args = kwargs.pop('argv', [])
-
- if verbosity:
- args += ['-' + 'v' * verbosity]
-
- return pytest.main(args, **kwargs)
-
-
-test.__test__ = False # pytest: this function is not a test |
1f8845f89aa936379fbea4d8707fbb4887c62696 | examples/pystray_icon.py | examples/pystray_icon.py | from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
if sys.platform == 'darwin':
# System tray icon needs to run in it's own process on Mac OS X
from multiprocessing import Process as Thread, Queue
else:
from threading import Thread
from queue import Queue
"""
This example demonstrates running pywebview alongside with pystray to display a system tray icon.
"""
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
return window
def run_pystray(queue: Queue):
def on_open(icon, item):
queue.put('open')
def on_exit(icon, item):
icon.stop()
queue.put('exit')
image = Image.open("logo/logo.png")
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
icon = Icon("Pystray", image, "Pystray", menu)
icon.run()
if __name__ == '__main__':
queue = Queue()
icon_thread = Thread(target=run_pystray, args=(queue,))
icon_thread.start()
window = run_webview()
while True:
event = queue.get()
if event == 'open':
if window.closed.is_set():
window = run_webview()
if event == 'exit':
if not window.closed.is_set():
window.destroy()
break
icon_thread.join()
| from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
if sys.platform == 'darwin':
# System tray icon needs to run in it's own process on Mac OS X
import multiprocessing
from multiprocessing import Process as Thread, Queue
multiprocessing.set_start_method('spawn')
else:
from threading import Thread
from queue import Queue
"""
This example demonstrates running pywebview alongside with pystray to display a system tray icon.
"""
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
def run_pystray(queue: Queue):
def on_open(icon, item):
queue.put('open')
def on_exit(icon, item):
icon.stop()
queue.put('exit')
image = Image.open("logo/logo.png")
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
icon = Icon("Pystray", image, "Pystray", menu)
icon.run()
if __name__ == '__main__':
queue = Queue()
icon_thread = Thread(target=run_pystray, args=(queue,))
icon_thread.start()
run_webview()
while True:
event = queue.get()
if event == 'open':
run_webview()
if event == 'exit':
break
icon_thread.join()
| Fix process spawn on Mac os, simplify logic | Fix process spawn on Mac os, simplify logic
| Python | bsd-3-clause | r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview | ---
+++
@@ -5,7 +5,9 @@
import sys
if sys.platform == 'darwin':
# System tray icon needs to run in it's own process on Mac OS X
+ import multiprocessing
from multiprocessing import Process as Thread, Queue
+ multiprocessing.set_start_method('spawn')
else:
from threading import Thread
from queue import Queue
@@ -19,7 +21,6 @@
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
- return window
def run_pystray(queue: Queue):
@@ -43,16 +44,13 @@
icon_thread = Thread(target=run_pystray, args=(queue,))
icon_thread.start()
- window = run_webview()
+ run_webview()
while True:
event = queue.get()
if event == 'open':
- if window.closed.is_set():
- window = run_webview()
+ run_webview()
if event == 'exit':
- if not window.closed.is_set():
- window.destroy()
break
icon_thread.join() |
21efff52ebc879134f83c08ab5eed214267b2496 | scipy/io/matlab/setup.py | scipy/io/matlab/setup.py | #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('matlab', parent_package, top_path)
config.add_data_dir('tests')
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| #!/usr/bin/env python
def configuration(parent_package='io',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('matlab', parent_package, top_path)
config.add_data_dir('tests')
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| Fix parent package of io.matlab. | Fix parent package of io.matlab.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@3963 d6536bca-fef9-0310-8506-e4c0a848fbcf
| Python | bsd-3-clause | scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,scipy/scipy-svn,scipy/scipy-svn,lesserwhirls/scipy-cwt,scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor | ---
+++
@@ -1,6 +1,6 @@
#!/usr/bin/env python
-def configuration(parent_package='',top_path=None):
+def configuration(parent_package='io',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('matlab', parent_package, top_path)
config.add_data_dir('tests') |
256d16c1c31d75442e014554fc0e8ed1d3e96adf | get_value.py | get_value.py | # Domestic-Workers
# ================
import csv
def read_data(filename):
"""
Read specified csv file, and return it as a list of dicts.
"""
with open(filename, 'r') as f:
return list(csv.DictReader(f))
dataset=read_data('Nids_w3.csv')
print(dataset[1]['food_wgt'])
| # Domestic-Workers
# ================
import csv
def read_data(filename):
"""
Read specified csv file, and return it as a list of dicts.
"""
with open(filename, 'r') as f:
return list(csv.DictReader(f))
dataset=read_data('Book1.csv')
print(dataset[1]['food_wgt'])
| Read data from correct CSV file. | Read data from correct CSV file.
| Python | apache-2.0 | shakermaker/Domestic-Workers,shakermaker/Domestic-Workers,Code4SA/Domestic-Workers,Code4SA/Domestic-Workers | ---
+++
@@ -11,6 +11,6 @@
with open(filename, 'r') as f:
return list(csv.DictReader(f))
-dataset=read_data('Nids_w3.csv')
+dataset=read_data('Book1.csv')
print(dataset[1]['food_wgt']) |
1cec2df8bcb7f877c813d6470d454244630b050a | semantic_release/pypi.py | semantic_release/pypi.py | """PyPI
"""
from invoke import run
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:param dists: The dists string passed to setup.py. Default: 'bdist_wheel'
:param username: PyPI account username string
:param password: PyPI account password string
"""
run('python setup.py {}'.format(dists))
run('twine upload -u {} -p {} {}'.format(username, password, '--skip-existing' if skip_existing else ''))
run('rm -rf build dist')
| """PyPI
"""
from invoke import run
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:param dists: The dists string passed to setup.py. Default: 'bdist_wheel'
:param username: PyPI account username string
:param password: PyPI account password string
"""
run('python setup.py {}'.format(dists))
run(
'twine upload -u {} -p {} {} {}'.format(
username,
password,
'--skip-existing' if skip_existing else '',
'dist/*'
)
)
run('rm -rf build dist')
| Add dists to twine call | fix: Add dists to twine call
| Python | mit | relekang/python-semantic-release,relekang/python-semantic-release | ---
+++
@@ -16,5 +16,12 @@
:param password: PyPI account password string
"""
run('python setup.py {}'.format(dists))
- run('twine upload -u {} -p {} {}'.format(username, password, '--skip-existing' if skip_existing else ''))
+ run(
+ 'twine upload -u {} -p {} {} {}'.format(
+ username,
+ password,
+ '--skip-existing' if skip_existing else '',
+ 'dist/*'
+ )
+ )
run('rm -rf build dist') |
f959e9213f27cee5ed5739655d4f85c7d0d442aa | tests/functional/customer/test_notification.py | tests/functional/customer/test_notification.py | from http import client as http_client
from oscar.test.testcases import WebTestCase
from oscar.apps.customer.notifications import services
from oscar.test.factories import UserFactory
from django.urls import reverse
from oscar.apps.customer.models import Notification
class TestAUserWithUnreadNotifications(WebTestCase):
def setUp(self):
self.user = UserFactory()
services.notify_user(self.user, "Test message")
def test_can_see_them_in_page_header(self):
homepage = self.app.get('/', user=self.user)
self.assertEqual(1, homepage.context['num_unread_notifications'])
def test_notification_list_view_shows_user_notifications(self):
response = self.app.get(reverse('customer:notifications-inbox'), user=self.user)
self.assertEqual(1, len(response.context['notifications']))
self.assertEqual(False, response.context['notifications'][0].is_read)
def test_notification_marked_as_read(self):
n = Notification.objects.first()
path = reverse('customer:notifications-detail', kwargs={'pk': n.id})
response = self.app.get(path, user=self.user)
# notification should be marked as read
self.assertEqual(http_client.OK, response.status_code)
n.refresh_from_db()
self.assertTrue(n.is_read)
| from http import client as http_client
from oscar.test.testcases import WebTestCase
from oscar.apps.customer.notifications import services
from oscar.test.factories import UserFactory
from django.urls import reverse
from oscar.apps.customer.models import Notification
class TestAUserWithUnreadNotifications(WebTestCase):
def setUp(self):
self.user = UserFactory()
services.notify_user(self.user, "Test message")
def test_can_see_them_in_page_header(self):
homepage = self.app.get('/', user=self.user)
if homepage.status_code == 302:
homepage = homepage.follow()
self.assertEqual(1, homepage.context['num_unread_notifications'])
def test_notification_list_view_shows_user_notifications(self):
response = self.app.get(reverse('customer:notifications-inbox'), user=self.user)
self.assertEqual(1, len(response.context['notifications']))
self.assertEqual(False, response.context['notifications'][0].is_read)
def test_notification_marked_as_read(self):
n = Notification.objects.first()
path = reverse('customer:notifications-detail', kwargs={'pk': n.id})
response = self.app.get(path, user=self.user)
# notification should be marked as read
self.assertEqual(http_client.OK, response.status_code)
n.refresh_from_db()
self.assertTrue(n.is_read)
| Update test in case if home page has redirection. | Update test in case if home page has redirection.
| Python | bsd-3-clause | solarissmoke/django-oscar,django-oscar/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,sasha0/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,sasha0/django-oscar,django-oscar/django-oscar | ---
+++
@@ -16,6 +16,8 @@
def test_can_see_them_in_page_header(self):
homepage = self.app.get('/', user=self.user)
+ if homepage.status_code == 302:
+ homepage = homepage.follow()
self.assertEqual(1, homepage.context['num_unread_notifications'])
def test_notification_list_view_shows_user_notifications(self): |
2ff6e50e0a4db641b026faa324c4cf0204e3a192 | src/hotchocolate/templates.py | src/hotchocolate/templates.py | # -*- encoding: utf-8
"""
Provides template utilities.
"""
import jinja2
from . import markdown as md, plugins
# TODO: Make this a setting
TEMPLATE_DIR = 'templates'
# TODO: Make this a setting
def locale_date(date):
"""Render a date in the current locale date."""
return date.strftime('%-d %B %Y')
def render_title(title):
return md.convert_markdown(
title,
extra_extensions=plugins.load_markdown_extensions()
)[0].replace('<p>', '').replace('</p>', '')
def build_environment(template_dir=None):
"""Build the appropriate Jinja2 environment."""
if template_dir is None:
template_dir = TEMPLATE_DIR
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_dir),
autoescape=jinja2.select_autoescape(['html']),
undefined=jinja2.StrictUndefined
)
# TODO: Extension mechanism for additional filters?
env.filters['locale_date'] = locale_date
env.filters['title'] = render_title
return env
| # -*- encoding: utf-8
"""
Provides template utilities.
"""
import jinja2
from . import markdown as md, plugins
# TODO: Make this a setting
TEMPLATE_DIR = 'templates'
# TODO: Make this a setting
def locale_date(date):
"""Render a date in the current locale date."""
return date.strftime('%d %B %Y').lstrip('0')
def render_title(title):
return md.convert_markdown(
title,
extra_extensions=plugins.load_markdown_extensions()
)[0].replace('<p>', '').replace('</p>', '')
def build_environment(template_dir=None):
"""Build the appropriate Jinja2 environment."""
if template_dir is None:
template_dir = TEMPLATE_DIR
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_dir),
autoescape=jinja2.select_autoescape(['html']),
undefined=jinja2.StrictUndefined
)
# TODO: Extension mechanism for additional filters?
env.filters['locale_date'] = locale_date
env.filters['title'] = render_title
return env
| Fix locale_date for the Alpine strftime | Fix locale_date for the Alpine strftime
| Python | mit | alexwlchan/hot-chocolate,alexwlchan/hot-chocolate | ---
+++
@@ -14,7 +14,7 @@
# TODO: Make this a setting
def locale_date(date):
"""Render a date in the current locale date."""
- return date.strftime('%-d %B %Y')
+ return date.strftime('%d %B %Y').lstrip('0')
def render_title(title): |
b00d93901a211a35bdb30e00da530dde823c4a2d | frontends/etiquette_flask/etiquette_flask_launch.py | frontends/etiquette_flask/etiquette_flask_launch.py | import gevent.monkey
gevent.monkey.patch_all()
import logging
handler = logging.StreamHandler()
log_format = '{levelname}:etiquette.{module}.{funcName}: {message}'
handler.setFormatter(logging.Formatter(log_format, style='{'))
logging.getLogger().addHandler(handler)
import etiquette_flask
import gevent.pywsgi
import gevent.wsgi
import sys
if len(sys.argv) == 2:
port = int(sys.argv[1])
else:
port = 5000
if port == 443:
http = gevent.pywsgi.WSGIServer(
listener=('0.0.0.0', port),
application=etiquette_flask.site,
keyfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.key',
certfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.crt',
)
else:
http = gevent.pywsgi.WSGIServer(
listener=('0.0.0.0', port),
application=etiquette_flask.site,
)
print('Starting server on port %d' % port)
http.serve_forever()
| import gevent.monkey
gevent.monkey.patch_all()
import logging
handler = logging.StreamHandler()
log_format = '{levelname}:etiquette.{module}.{funcName}: {message}'
handler.setFormatter(logging.Formatter(log_format, style='{'))
logging.getLogger().addHandler(handler)
import etiquette_flask
import gevent.pywsgi
import gevent.wsgi
import sys
import werkzeug.contrib.fixers
etiquette_flask.site.wsgi_app = werkzeug.contrib.fixers.ProxyFix(etiquette_flask.site.wsgi_app)
if len(sys.argv) == 2:
port = int(sys.argv[1])
else:
port = 5000
if port == 443:
http = gevent.pywsgi.WSGIServer(
listener=('0.0.0.0', port),
application=etiquette_flask.site,
keyfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.key',
certfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.crt',
)
else:
http = gevent.pywsgi.WSGIServer(
listener=('0.0.0.0', port),
application=etiquette_flask.site,
)
print('Starting server on port %d' % port)
http.serve_forever()
| Apply werkzeug ProxyFix so that request.remote_addr is correct. | Apply werkzeug ProxyFix so that request.remote_addr is correct.
| Python | bsd-3-clause | voussoir/etiquette,voussoir/etiquette,voussoir/etiquette | ---
+++
@@ -11,6 +11,11 @@
import gevent.pywsgi
import gevent.wsgi
import sys
+
+
+import werkzeug.contrib.fixers
+etiquette_flask.site.wsgi_app = werkzeug.contrib.fixers.ProxyFix(etiquette_flask.site.wsgi_app)
+
if len(sys.argv) == 2:
port = int(sys.argv[1]) |
ed0c44ad01a1b88b0e6109a629455ae44ff91011 | office365/sharepoint/actions/download_file.py | office365/sharepoint/actions/download_file.py | from office365.runtime.http.http_method import HttpMethod
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
class DownloadFileQuery(ServiceOperationQuery):
def __init__(self, web, file_url, file_object):
"""
A download file content query
:type file_url: str
:type web: office365.sharepoint.webs.web.Web
:type file_object: typing.IO
"""
def _construct_download_query(request):
request.method = HttpMethod.Get
self.context.after_execute(_process_response)
def _process_response(response):
"""
:type response: RequestOptions
"""
file_object.write(response.content)
super(DownloadFileQuery, self).__init__(web, r"getFileByServerRelativeUrl('{0}')/\$value".format(file_url))
self.context.before_execute(_construct_download_query)
| from office365.runtime.http.http_method import HttpMethod
from office365.runtime.odata.odata_path_parser import ODataPathParser
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
class DownloadFileQuery(ServiceOperationQuery):
def __init__(self, web, file_url, file_object):
"""
A download file content query
:type file_url: str
:type web: office365.sharepoint.webs.web.Web
:type file_object: typing.IO
"""
def _construct_download_query(request):
request.method = HttpMethod.Get
self.context.after_execute(_process_response)
def _process_response(response):
"""
:type response: RequestOptions
"""
file_object.write(response.content)
# Sharepoint Endpoint bug: https://github.com/SharePoint/sp-dev-docs/issues/2630
file_url = ODataPathParser.encode_method_value(file_url)
super(DownloadFileQuery, self).__init__(web, r"getFileByServerRelativePath(decodedurl={0})/$value".format(file_url))
self.context.before_execute(_construct_download_query)
| Support correctly weird characters in filenames when downloading | Support correctly weird characters in filenames when downloading
This commit add support for the following:
- Correctly encoded oData parameter sent to the endpoint.
- Support for # and % in filenames by using a newer 365 endpoint.
Summary:
Current implementation was injecting an URL directly quoted to
the endpoint, instead of encoding as an oData value. This was
solved by using the encode_method_value method. This fixes
issues when the file contains weird characters, like slashes
and single quotes.
The getFileServerByUrl endpoint does not support some characters
in filenames, like # and %. A newer endpoint
(getFileByServerRelativePath) is used instead, which allows to
download files with those characters.
| Python | mit | vgrem/Office365-REST-Python-Client | ---
+++
@@ -1,4 +1,5 @@
from office365.runtime.http.http_method import HttpMethod
+from office365.runtime.odata.odata_path_parser import ODataPathParser
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
@@ -23,5 +24,9 @@
"""
file_object.write(response.content)
- super(DownloadFileQuery, self).__init__(web, r"getFileByServerRelativeUrl('{0}')/\$value".format(file_url))
+ # Sharepoint Endpoint bug: https://github.com/SharePoint/sp-dev-docs/issues/2630
+ file_url = ODataPathParser.encode_method_value(file_url)
+
+ super(DownloadFileQuery, self).__init__(web, r"getFileByServerRelativePath(decodedurl={0})/$value".format(file_url))
+
self.context.before_execute(_construct_download_query) |
a2b4b53635ab1188e95efd68f64104a469e7ff66 | scheduler/executor.py | scheduler/executor.py | import threading
import subprocess
class TestExecutor(threading.Thread):
"""
The general thread to perform the tests executions
"""
def __init__(self, run_id, test_name, queue):
super().__init__()
self.run_id = run_id
self.test_name = test_name
self.queue = queue
# __init __()
def run(self):
"""
Execute the command to perform the test execution. The return
code is enqueued so the scheduler can determine if the run has
completed
"""
with open(
"runs/static/runs/autotests/runs/{}.txt".format(
self.run_id), "w") as f:
CMD = "python3 -m unittest -v autotests/tests/{}.py 2>&1".format(
self.test_name)
return_code = subprocess.call(CMD, stdout=f, shell=True)
self.queue.put((self.run_id, return_code))
# run()
| import threading
import subprocess
import os
class TestExecutor(threading.Thread):
"""
The general thread to perform the tests executions
"""
def __init__(self, run_id, test_name, queue):
super().__init__()
self.run_id = run_id
self.test_name = test_name
self.queue = queue
# __init __()
def run(self):
"""
Execute the command to perform the test execution. The return
code is enqueued so the scheduler can determine if the run has
completed
"""
filename = "runs/static/runs/logs/{}.txt".format(self.run_id)
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
CMD = "python3 -m unittest -v autotests/tests/{}.py 2>&1".format(
self.test_name)
return_code = subprocess.call(CMD, stdout=f, shell=True)
self.queue.put((self.run_id, return_code))
# run()
| Fix bug related to creating the log directory | Fix bug related to creating the log directory
| Python | mit | jfelipefilho/test-manager,jfelipefilho/test-manager,jfelipefilho/test-manager | ---
+++
@@ -1,5 +1,6 @@
import threading
import subprocess
+import os
class TestExecutor(threading.Thread):
@@ -20,10 +21,9 @@
code is enqueued so the scheduler can determine if the run has
completed
"""
- with open(
- "runs/static/runs/autotests/runs/{}.txt".format(
- self.run_id), "w") as f:
-
+ filename = "runs/static/runs/logs/{}.txt".format(self.run_id)
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
+ with open(filename, "w") as f:
CMD = "python3 -m unittest -v autotests/tests/{}.py 2>&1".format(
self.test_name)
|
327428de0267de773a850daa9d376891fe02308f | splitword.py | splitword.py | #!/usr/bin/env python3
# encoding: utf-8
# Splits a word into multiple parts
def split_word(word):
if len(word) < 2:
raise Exception(
"You obviously need at least two letters to split a word")
split_indexes = list(range(1, len(word)))
for i in split_indexes:
first_part = word[:i]
second_part = word[i:]
yield (first_part, second_part)
| #!/usr/bin/env python3
# encoding: utf-8
# Splits a word into multiple parts
def split_word(word):
split_indexes = list(range(0, len(word)))
for i in split_indexes:
first_part = word[:i]
second_part = word[i:]
yield (first_part, second_part)
| Allow splitting to zero-length parts | Allow splitting to zero-length parts
| Python | unlicense | andyn/kapunaattori | ---
+++
@@ -4,10 +4,7 @@
# Splits a word into multiple parts
def split_word(word):
- if len(word) < 2:
- raise Exception(
- "You obviously need at least two letters to split a word")
- split_indexes = list(range(1, len(word)))
+ split_indexes = list(range(0, len(word)))
for i in split_indexes:
first_part = word[:i]
second_part = word[i:] |
0887e200f31edd8d61e0dd1d3fefae7e828c9269 | mindbender/maya/plugins/validate_single_assembly.py | mindbender/maya/plugins/validate_single_assembly.py | import pyblish.api
class ValidateMindbenderSingleAssembly(pyblish.api.InstancePlugin):
"""Each asset must have a single top-level group
The given instance is test-exported, along with construction
history to test whether more than 1 top-level DAG node would
be included in the exported file.
"""
label = "Validate Single Assembly"
order = pyblish.api.ValidatorOrder
hosts = ["maya"]
families = ["mindbender.model", "mindbender.rig"]
def process(self, instance):
from maya import cmds
from mindbender import maya
with maya.maintained_selection():
cmds.select(instance, replace=True)
nodes = cmds.file(
constructionHistory=True,
exportSelected=True,
preview=True,
force=True,
)
assemblies = cmds.ls(nodes, assemblies=True)
if not assemblies:
raise Exception("No assembly found.")
if len(assemblies) != 1:
assemblies = '"%s"' % '", "'.join(assemblies)
raise Exception(
"Multiple assemblies found: %s" % assemblies
)
| import pyblish.api
class SelectAssemblies(pyblish.api.Action):
label = "Select Assemblies"
on = "failed"
def process(self, context, plugin):
from maya import cmds
cmds.select(plugin.assemblies)
class ValidateMindbenderSingleAssembly(pyblish.api.InstancePlugin):
"""Each asset must have a single top-level group
The given instance is test-exported, along with construction
history to test whether more than 1 top-level DAG node would
be included in the exported file.
"""
label = "Validate Single Assembly"
order = pyblish.api.ValidatorOrder
hosts = ["maya"]
families = ["mindbender.model", "mindbender.rig"]
actions = [
pyblish.api.Category("Actions"),
SelectAssemblies,
]
assemblies = []
def process(self, instance):
from maya import cmds
from mindbender import maya
with maya.maintained_selection():
cmds.select(instance, replace=True)
nodes = cmds.file(
constructionHistory=True,
exportSelected=True,
preview=True,
force=True,
)
self.assemblies[:] = cmds.ls(nodes, assemblies=True)
if not self.assemblies:
raise Exception("No assembly found.")
if len(self.assemblies) != 1:
self.assemblies = '"%s"' % '", "'.join(self.assemblies)
raise Exception(
"Multiple assemblies found: %s" % self.assemblies
)
| Add action to select the multiple assemblies. | Add action to select the multiple assemblies.
| Python | mit | getavalon/core,MoonShineVFX/core,MoonShineVFX/core,mindbender-studio/core,mindbender-studio/core,getavalon/core | ---
+++
@@ -1,4 +1,13 @@
import pyblish.api
+
+
+class SelectAssemblies(pyblish.api.Action):
+ label = "Select Assemblies"
+ on = "failed"
+
+ def process(self, context, plugin):
+ from maya import cmds
+ cmds.select(plugin.assemblies)
class ValidateMindbenderSingleAssembly(pyblish.api.InstancePlugin):
@@ -14,6 +23,12 @@
order = pyblish.api.ValidatorOrder
hosts = ["maya"]
families = ["mindbender.model", "mindbender.rig"]
+ actions = [
+ pyblish.api.Category("Actions"),
+ SelectAssemblies,
+ ]
+
+ assemblies = []
def process(self, instance):
from maya import cmds
@@ -28,13 +43,13 @@
force=True,
)
- assemblies = cmds.ls(nodes, assemblies=True)
+ self.assemblies[:] = cmds.ls(nodes, assemblies=True)
- if not assemblies:
+ if not self.assemblies:
raise Exception("No assembly found.")
- if len(assemblies) != 1:
- assemblies = '"%s"' % '", "'.join(assemblies)
+ if len(self.assemblies) != 1:
+ self.assemblies = '"%s"' % '", "'.join(self.assemblies)
raise Exception(
- "Multiple assemblies found: %s" % assemblies
+ "Multiple assemblies found: %s" % self.assemblies
) |
92e96c010b54bf4c9e35d49de492cf9f061f345a | micromodels/models.py | micromodels/models.py | from fields import FieldBase
class Model(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
fields = {}
for name, value in attrs.items():
if isinstance(value, FieldBase):
fields[name] = value
setattr(cls, '_fields', fields)
def __init__(self, data):
"""Create an instance of the model subclass. The constructor should
be passed a dictionary of data to provide values for its fields.
For each field defined on the class (and stored in the _fields
property by the metaclass), a property is created on the instance
which contains the converted value from the source data.
"""
for name, field in self._fields.items():
key = field.source or name
field.populate(data.get(key))
value = field.to_python()
setattr(self, name, value)
self._data = data
| from fields import FieldBase
class Model(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
cls._fields = {}
for name, value in attrs.items():
if isinstance(value, FieldBase):
cls._fields[name] = value
def __init__(self, data):
"""Create an instance of the model subclass. The constructor should
be passed a dictionary of data to provide values for its fields.
For each field defined on the class (and stored in the _fields
property by the metaclass), a property is created on the instance
which contains the converted value from the source data.
"""
for name, field in self._fields.items():
key = field.source or name
field.populate(data.get(key))
value = field.to_python()
setattr(self, name, value)
self._data = data
| Change to make metaclass clearer | Change to make metaclass clearer
| Python | unlicense | j4mie/micromodels | ---
+++
@@ -4,11 +4,10 @@
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
- fields = {}
+ cls._fields = {}
for name, value in attrs.items():
if isinstance(value, FieldBase):
- fields[name] = value
- setattr(cls, '_fields', fields)
+ cls._fields[name] = value
def __init__(self, data):
"""Create an instance of the model subclass. The constructor should |
7a0da88638c3d0fe0f9088c0d9008ff60503fe06 | plotly/plotly/__init__.py | plotly/plotly/__init__.py | """
plotly
======
This module defines functionality that requires interaction between your
local machine and Plotly. Almost all functionality used here will require a
verifiable account (username/api-key pair) and a network connection.
"""
from __future__ import absolute_import
from plotly.plotly.plotly import *
__all__ = ["sign_in", "update_plot_options", "get_plot_options",
"get_credentials", "iplot", "plot", "iplot_mpl", "plot_mpl",
"get_figure", "Stream", "image"]
| """
plotly
======
This module defines functionality that requires interaction between your
local machine and Plotly. Almost all functionality used here will require a
verifiable account (username/api-key pair) and a network connection.
"""
from . plotly import (
sign_in, update_plot_options, get_plot_options, get_credentials, iplot,
plot, iplot_mpl, plot_mpl, get_figure, Stream, image
)
| Remove `import *`. Replace with explicit public interface. | Remove `import *`. Replace with explicit public interface.
| Python | mit | plotly/python-api,ee-in/python-api,plotly/plotly.py,plotly/plotly.py,ee-in/python-api,plotly/plotly.py,ee-in/python-api,plotly/python-api,plotly/python-api | ---
+++
@@ -7,10 +7,7 @@
verifiable account (username/api-key pair) and a network connection.
"""
-from __future__ import absolute_import
-
-from plotly.plotly.plotly import *
-
-__all__ = ["sign_in", "update_plot_options", "get_plot_options",
- "get_credentials", "iplot", "plot", "iplot_mpl", "plot_mpl",
- "get_figure", "Stream", "image"]
+from . plotly import (
+ sign_in, update_plot_options, get_plot_options, get_credentials, iplot,
+ plot, iplot_mpl, plot_mpl, get_figure, Stream, image
+) |
59927047347b7db3f46ab99152d2d99f60039043 | trac/versioncontrol/web_ui/__init__.py | trac/versioncontrol/web_ui/__init__.py | from trac.versioncontrol.web_ui.browser import *
from trac.versioncontrol.web_ui.changeset import *
from trac.versioncontrol.web_ui.log import *
| from trac.versioncontrol.web_ui.browser import *
from trac.versioncontrol.web_ui.changeset import *
from trac.versioncontrol.web_ui.log import *
| Add missing `svn:eol-style : native` prop, which prevented making clean patches against the early 0.9b1 archives (now both the .zip and the .tar.gz have CRLFs for this file) | Add missing `svn:eol-style : native` prop, which prevented making clean patches against the early 0.9b1 archives (now both the .zip and the .tar.gz have CRLFs for this file)
git-svn-id: eda3d06fcef731589ace1b284159cead3416df9b@2214 af82e41b-90c4-0310-8c96-b1721e28e2e2
| Python | bsd-3-clause | jun66j5/trac-ja,walty8/trac,netjunki/trac-Pygit2,jun66j5/trac-ja,jun66j5/trac-ja,walty8/trac,walty8/trac,jun66j5/trac-ja,walty8/trac,netjunki/trac-Pygit2,netjunki/trac-Pygit2 | |
4b379e82dd503afc04569a50c08a7cdd9abfe4b0 | passpie/validators.py | passpie/validators.py | import click
from .history import clone
from . import config
def validate_remote(ctx, param, value):
if value:
try:
remote, branch = value.split('/')
return (remote, branch)
except ValueError:
raise click.BadParameter('remote need to be in format <remote>/<branch>')
def validate_cols(ctx, param, value):
if value:
try:
validated = {c: index for index, c in enumerate(value.split(',')) if c}
for col in ('name', 'login', 'password'):
assert col in validated
return validated
except (AttributeError, ValueError):
raise click.BadParameter('cols need to be in format col1,col2,col3')
except AssertionError as e:
raise click.BadParameter('missing mandatory column: {}'.format(e))
def validate_config(ctx, param, value):
overrides = {k: v for k, v in ctx.params.items() if v}
configuration = {}
configuration.update(config.DEFAULT) # Default configuration
configuration.update(config.read(config.HOMEDIR, '.passpierc')) # Global configuration
if value:
configuration.update(config.read(value)) # Options configuration
configuration.update(overrides) # Command line options
if config.is_repo_url(configuration['path']) is True:
temporary_path = clone(configuration['path'], depth="1")
configuration.update(config.read(temporary_path)) # Read cloned config
configuration['path'] = temporary_path
configuration = config.setup_crypt(configuration)
return configuration
| import click
from .history import clone
from . import config
def validate_remote(ctx, param, value):
if value:
try:
remote, branch = value.split('/')
return (remote, branch)
except ValueError:
raise click.BadParameter('remote need to be in format <remote>/<branch>')
def validate_cols(ctx, param, value):
if value:
try:
validated = {c: index for index, c in enumerate(value.split(',')) if c}
for col in ('name', 'login', 'password'):
assert col in validated
return validated
except (AttributeError, ValueError):
raise click.BadParameter('cols need to be in format col1,col2,col3')
except AssertionError as e:
raise click.BadParameter('missing mandatory column: {}'.format(e))
def validate_config(ctx, param, value):
overrides = {k: v for k, v in ctx.params.items() if v}
configuration = {}
configuration.update(config.DEFAULT) # Default configuration
configuration.update(config.read(config.HOMEDIR, '.passpierc')) # Global configuration
if value:
configuration.update(config.read(value)) # Options configuration
configuration.update(overrides) # Command line options
if config.is_repo_url(configuration['path']) is True:
temporary_path = clone(configuration['path'], depth="1")
configuration['path'] = temporary_path
configuration.update(config.read(configuration['path']))
configuration = config.setup_crypt(configuration)
return configuration
| Fix load config from local db config file | Fix load config from local db config file
| Python | mit | scorphus/passpie,scorphus/passpie,marcwebbie/passpie,marcwebbie/passpie | ---
+++
@@ -37,8 +37,8 @@
if config.is_repo_url(configuration['path']) is True:
temporary_path = clone(configuration['path'], depth="1")
- configuration.update(config.read(temporary_path)) # Read cloned config
configuration['path'] = temporary_path
+ configuration.update(config.read(configuration['path']))
configuration = config.setup_crypt(configuration)
return configuration |
15941639134d4360753607bd488d3c80d15ca825 | second/blog/models.py | second/blog/models.py | from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title | from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey('blog.Post', related_name='comments')
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.text | Add comments model to blog | Add comments model to blog
| Python | mit | ugaliguy/Django-Tutorial-Projects,ugaliguy/Django-Tutorial-Projects | ---
+++
@@ -18,3 +18,17 @@
def __str__(self):
return self.title
+
+class Comment(models.Model):
+ post = models.ForeignKey('blog.Post', related_name='comments')
+ author = models.CharField(max_length=200)
+ text = models.TextField()
+ created_date = models.DateTimeField(default=timezone.now)
+ approved_comment = models.BooleanField(default=False)
+
+ def approve(self):
+ self.approved_comment = True
+ self.save()
+
+ def __str__(self):
+ return self.text |
b5a71f2142c16b8523da483a6879578522cfd9bb | semesterpage/forms.py | semesterpage/forms.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from dal import autocomplete
from .models import Course, Options
class OptionsForm(forms.ModelForm):
"""
A form solely used for autocompleting Courses in the admin,
using django-autocomplete-light,
"""
self_chosen_courses = forms.ModelMultipleChoiceField(
label=_('Skriv inn dine fag'),
queryset=Course.objects.all(),
widget=autocomplete.ModelSelect2Multiple(
url='semesterpage-course-autocomplete',
attrs = {
'data-placeholder': _('Tast inn fagkode eller fagnavn'),
# Only trigger autocompletion after 3 characters have been typed
'data-minimum-input-length': 3,
},
)
)
def __init__(self, *args, **kwargs):
super(OptionsForm, self).__init__(*args, **kwargs)
self.fields['self_chosen_courses'].help_text = _(
'Tast inn fagkode eller fagnavn for å legge til et nytt fag\
på hjemmesiden din.'
)
class Meta:
model = Options
# The fields are further restricted in .admin.py
fields = ('__all__')
| from django import forms
from django.utils.translation import ugettext_lazy as _
from dal import autocomplete
from .models import Course, Options
class OptionsForm(forms.ModelForm):
"""
A form solely used for autocompleting Courses in the admin,
using django-autocomplete-light,
"""
self_chosen_courses = forms.ModelMultipleChoiceField(
label=_('Skriv inn fagene du tar nå'),
queryset=Course.objects.all(),
widget=autocomplete.ModelSelect2Multiple(
url='semesterpage-course-autocomplete',
attrs = {
'data-placeholder': _('Tast inn fagkode eller fagnavn'),
# Only trigger autocompletion after 3 characters have been typed
'data-minimum-input-length': 3,
},
)
)
def __init__(self, *args, **kwargs):
super(OptionsForm, self).__init__(*args, **kwargs)
self.fields['self_chosen_courses'].help_text = _(
'Tast inn fagkode eller fagnavn for å legge til et nytt fag\
på hjemmesiden din.'
)
class Meta:
model = Options
# The fields are further restricted in .admin.py
fields = ('__all__')
| Clarify that self_chosen_courses == enrolled | Clarify that self_chosen_courses == enrolled
Fixes #75.
| Python | mit | afriestad/WikiLinks,afriestad/WikiLinks,afriestad/WikiLinks | ---
+++
@@ -12,7 +12,7 @@
"""
self_chosen_courses = forms.ModelMultipleChoiceField(
- label=_('Skriv inn dine fag'),
+ label=_('Skriv inn fagene du tar nå'),
queryset=Course.objects.all(),
widget=autocomplete.ModelSelect2Multiple(
url='semesterpage-course-autocomplete', |
5f688e5a99c2e4ec476f28306c2cca375934bba7 | nvidia_commands_layer.py | nvidia_commands_layer.py | #!/usr/bin/env python3.5
import subprocess
class NvidiaCommandsLayerException(Exception):
pass
class NvidiaCommandsLayer(object):
@staticmethod
def set_fan_percentage(
value: int
) -> None:
if value < 0 or value > 100:
raise NvidiaCommandsLayerException('Cannot set a value outside 0 - 100')
result = subprocess.run(
[
'nvidia-settings',
'-a',
'"[gpu:0]/GPUFanControlState=1"',
'-a',
'"[fan:0]/GPUTargetFanSpeed={}"'.format(value)
],
stdout=subprocess.PIPE
)
if result.returncode != 0:
raise NvidiaCommandsLayerException('Could not set the fan speed')
@staticmethod
def read_temperature(
) -> int:
result = subprocess.run(
[
'nvidia-smi',
'--query-gpu=temperature.gpu',
'--format=csv,noheader,nounits'
],
stdout=subprocess.PIPE
)
if result.returncode == 0:
# the result is a string with a '\n' at the end, convert it to a decimal
return int(result.stdout[:-1])
else:
raise NvidiaCommandsLayerException('Could not read the temperature')
| #!/usr/bin/env python3
import subprocess
class NvidiaCommandsLayerException(Exception):
pass
class NvidiaCommandsLayer(object):
@staticmethod
def set_fan_percentage(
value: int
) -> None:
if value < 0 or value > 100:
raise NvidiaCommandsLayerException('Cannot set a value outside 0 - 100')
result = subprocess.run(
'nvidia-settings '
'-a "[gpu:0]/GPUFanControlState=1" '
'-a "[fan:0]/GPUTargetFanSpeed={}"'.format(value),
stdout=subprocess.PIPE,
shell=True
)
if result.returncode != 0:
raise NvidiaCommandsLayerException('Could not set the fan speed')
@staticmethod
def read_temperature(
) -> int:
result = subprocess.run(
[
'nvidia-smi',
'--query-gpu=temperature.gpu',
'--format=csv,noheader,nounits'
],
stdout=subprocess.PIPE
)
if result.returncode == 0:
# the result is a string with a '\n' at the end, convert it to a decimal
return int(result.stdout[:-1])
else:
raise NvidiaCommandsLayerException('Could not read the temperature')
| Fix script not working from bash | Fix script not working from bash
| Python | mit | radu-nedelcu/nvidia-fan-controller,radu-nedelcu/nvidia-fan-controller | ---
+++
@@ -1,4 +1,4 @@
-#!/usr/bin/env python3.5
+#!/usr/bin/env python3
import subprocess
@@ -16,14 +16,11 @@
raise NvidiaCommandsLayerException('Cannot set a value outside 0 - 100')
result = subprocess.run(
- [
- 'nvidia-settings',
- '-a',
- '"[gpu:0]/GPUFanControlState=1"',
- '-a',
- '"[fan:0]/GPUTargetFanSpeed={}"'.format(value)
- ],
- stdout=subprocess.PIPE
+ 'nvidia-settings '
+ '-a "[gpu:0]/GPUFanControlState=1" '
+ '-a "[fan:0]/GPUTargetFanSpeed={}"'.format(value),
+ stdout=subprocess.PIPE,
+ shell=True
)
if result.returncode != 0: |
17bb4f62d13838623ac097ef2f2feb88d95f8539 | opbeat_pyramid/tweens.py | opbeat_pyramid/tweens.py | import venusian
class tween_config(object):
""" A decorator which allows developers to annotate tween factories. """
venusian = venusian
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, wrapped_tween_factory):
def do_the_thing(context, name, obj):
module_name = wrapped_tween_factory.__module__
callable_name = wrapped_tween_factory.__name__
factory_string = module_name + '.' + callable_name
context.config.with_package(info.module).add_tween(
factory_string,
*self.args,
**self.kwargs,
)
info = self.venusian.attach(
wrapped_tween_factory,
do_the_thing,
category='opbeat_pyramid',
)
return wrapped_tween_factory
| import venusian
class tween_config(object):
""" A decorator which allows developers to annotate tween factories. """
venusian = venusian
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, wrapped_tween_factory):
def do_the_thing(context, name, obj):
module_name = wrapped_tween_factory.__module__
callable_name = wrapped_tween_factory.__name__
factory_string = module_name + '.' + callable_name
context.config.with_package(info.module).add_tween(
factory_string,
*self.args,
**self.kwargs
)
info = self.venusian.attach(
wrapped_tween_factory,
do_the_thing,
category='opbeat_pyramid',
)
return wrapped_tween_factory
| Fix issue in Python 2 | Fix issue in Python 2
| Python | mit | britco/opbeat_pyramid,monokrome/opbeat_pyramid | ---
+++
@@ -19,7 +19,7 @@
context.config.with_package(info.module).add_tween(
factory_string,
*self.args,
- **self.kwargs,
+ **self.kwargs
)
info = self.venusian.attach( |
cdb8756ead6a61a3fbb3001050091506e16481e5 | lexicon/__init__.py | lexicon/__init__.py | from attribute_dict import AttributeDict
from alias_dict import AliasDict
__version__ = "0.1.2"
class Lexicon(AttributeDict, AliasDict):
def __init__(self, *args, **kwargs):
# Need to avoid combining AliasDict's initial attribute write on
# self.aliases, with AttributeDict's __setattr__. Doing so results in
# an infinite loop. Instead, just skip straight to dict() for both
# explicitly (i.e. we override AliasDict.__init__ instead of extending
# it.)
# NOTE: could tickle AttributeDict.__init__ instead, in case it ever
# grows one.
dict.__init__(self, *args, **kwargs)
dict.__setattr__(self, 'aliases', {})
def __getattr__(self, key):
# Intercept deepcopy/etc driven access to self.aliases when not
# actually set. (Only a problem for us, due to abovementioned combo of
# Alias and Attribute Dicts, so not solvable in a parent alone.)
if key == 'aliases' and key not in self.__dict__:
self.__dict__[key] = {}
return super(Lexicon, self).__getattr__(key)
| from .attribute_dict import AttributeDict
from .alias_dict import AliasDict
__version__ = "0.1.2"
class Lexicon(AttributeDict, AliasDict):
def __init__(self, *args, **kwargs):
# Need to avoid combining AliasDict's initial attribute write on
# self.aliases, with AttributeDict's __setattr__. Doing so results in
# an infinite loop. Instead, just skip straight to dict() for both
# explicitly (i.e. we override AliasDict.__init__ instead of extending
# it.)
# NOTE: could tickle AttributeDict.__init__ instead, in case it ever
# grows one.
dict.__init__(self, *args, **kwargs)
dict.__setattr__(self, 'aliases', {})
def __getattr__(self, key):
# Intercept deepcopy/etc driven access to self.aliases when not
# actually set. (Only a problem for us, due to abovementioned combo of
# Alias and Attribute Dicts, so not solvable in a parent alone.)
if key == 'aliases' and key not in self.__dict__:
self.__dict__[key] = {}
return super(Lexicon, self).__getattr__(key)
| Use explicit relative imports for Python3 Compat | Use explicit relative imports for Python3 Compat
| Python | bsd-2-clause | mindw/lexicon,bitprophet/lexicon | ---
+++
@@ -1,5 +1,5 @@
-from attribute_dict import AttributeDict
-from alias_dict import AliasDict
+from .attribute_dict import AttributeDict
+from .alias_dict import AliasDict
__version__ = "0.1.2" |
1e9fb28b1263bb543191d3c44ba39d8311ad7cae | quantecon/__init__.py | quantecon/__init__.py | """
Import the main names to top level.
"""
from . import models as models
from .compute_fp import compute_fixed_point
from .discrete_rv import DiscreteRV
from .ecdf import ECDF
from .estspec import smooth, periodogram, ar_periodogram
from .graph_tools import DiGraph
from .gridtools import cartesian, mlinspace
from .kalman import Kalman
from .lae import LAE
from .arma import ARMA
from .lqcontrol import LQ
from .lqnash import nnash
from .lss import LinearStateSpace
from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati
from .quadsums import var_quadratic_sum, m_quadratic_sum
#->Propose Delete From Top Level
from .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen #Promote to keep current examples working
from .markov import mc_compute_stationary, mc_sample_path #Imports that Should be Deprecated with markov package
#<-
from .rank_nullspace import rank_est, nullspace
from .robustlq import RBLQ
from . import quad as quad
from .util import searchsorted
#Add Version Attribute
from .version import version as __version__
| """
Import the main names to top level.
"""
from .compute_fp import compute_fixed_point
from .discrete_rv import DiscreteRV
from .ecdf import ECDF
from .estspec import smooth, periodogram, ar_periodogram
from .graph_tools import DiGraph
from .gridtools import cartesian, mlinspace
from .kalman import Kalman
from .lae import LAE
from .arma import ARMA
from .lqcontrol import LQ
from .lqnash import nnash
from .lss import LinearStateSpace
from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati
from .quadsums import var_quadratic_sum, m_quadratic_sum
#->Propose Delete From Top Level
from .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen #Promote to keep current examples working
from .markov import mc_compute_stationary, mc_sample_path #Imports that Should be Deprecated with markov package
#<-
from .rank_nullspace import rank_est, nullspace
from .robustlq import RBLQ
from . import quad as quad
from .util import searchsorted
#Add Version Attribute
from .version import version as __version__
| Remove models/ subpackage from api due to migration to QuantEcon.applications | Remove models/ subpackage from api due to migration to QuantEcon.applications
| Python | bsd-3-clause | QuantEcon/QuantEcon.py,oyamad/QuantEcon.py,QuantEcon/QuantEcon.py,oyamad/QuantEcon.py | ---
+++
@@ -2,7 +2,6 @@
Import the main names to top level.
"""
-from . import models as models
from .compute_fp import compute_fixed_point
from .discrete_rv import DiscreteRV
from .ecdf import ECDF |
ff9fc6e6036ea99af4db6a5760d05a33cf7336e1 | solidity/python/constants/PrintLn2ScalingFactors.py | solidity/python/constants/PrintLn2ScalingFactors.py | import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__),'..'))
from decimal import Decimal
from decimal import getcontext
from FormulaSolidityPort import fixedLog2
MIN_PRECISION = 32
MAX_PRECISION = 127
getcontext().prec = MAX_PRECISION
ln2 = Decimal(2).ln()
fixedLog2MaxInput = ((1<<(256-MAX_PRECISION))-1)<<MAX_PRECISION
fixedLog2MaxOutput = fixedLog2(fixedLog2MaxInput,MAX_PRECISION)
FLOOR_LN2_EXPONENT = int((((1<<256)-1)/(fixedLog2MaxOutput*ln2)).ln()/ln2)
FLOOR_LN2_MANTISSA = int(2**FLOOR_LN2_EXPONENT*ln2)
CEILING_LN2_MANTISSA = int(ln2*(1<<MIN_PRECISION)+1)
print ' uint256 constant CEILING_LN2_MANTISSA = 0x{:x};'.format(CEILING_LN2_MANTISSA)
print ' uint256 constant FLOOR_LN2_MANTISSA = 0x{:x};'.format(FLOOR_LN2_MANTISSA )
print ' uint8 constant FLOOR_LN2_EXPONENT = {:d};' .format(FLOOR_LN2_EXPONENT )
| from decimal import Decimal
from decimal import getcontext
from decimal import ROUND_FLOOR
from decimal import ROUND_CEILING
MIN_PRECISION = 32
MAX_PRECISION = 127
def ln(n):
return Decimal(n).ln()
def log2(n):
return ln(n)/ln(2)
def floor(d):
return int(d.to_integral_exact(rounding=ROUND_FLOOR))
def ceiling(d):
return int(d.to_integral_exact(rounding=ROUND_CEILING))
getcontext().prec = MAX_PRECISION
maxVal = floor(log2(2**(256-MAX_PRECISION)-1)*2**MAX_PRECISION)-1
FLOOR_LN2_EXPONENT = floor(log2((2**256-1)/(maxVal*ln(2))))
FLOOR_LN2_MANTISSA = floor(2**FLOOR_LN2_EXPONENT*ln(2))
CEILING_LN2_MANTISSA = ceiling(2**MIN_PRECISION*ln(2))
print ' uint256 constant CEILING_LN2_MANTISSA = 0x{:x};'.format(CEILING_LN2_MANTISSA)
print ' uint256 constant FLOOR_LN2_MANTISSA = 0x{:x};'.format(FLOOR_LN2_MANTISSA )
print ' uint8 constant FLOOR_LN2_EXPONENT = {:d};' .format(FLOOR_LN2_EXPONENT )
| Make this constant-generating script independent of the solidity emulation module. | Make this constant-generating script independent of the solidity emulation module.
| Python | apache-2.0 | enjin/contracts | ---
+++
@@ -1,28 +1,38 @@
-import os
-import sys
-sys.path.append(os.path.join(os.path.dirname(__file__),'..'))
-
-
from decimal import Decimal
from decimal import getcontext
-from FormulaSolidityPort import fixedLog2
+from decimal import ROUND_FLOOR
+from decimal import ROUND_CEILING
MIN_PRECISION = 32
MAX_PRECISION = 127
-getcontext().prec = MAX_PRECISION
-ln2 = Decimal(2).ln()
+def ln(n):
+ return Decimal(n).ln()
-fixedLog2MaxInput = ((1<<(256-MAX_PRECISION))-1)<<MAX_PRECISION
-fixedLog2MaxOutput = fixedLog2(fixedLog2MaxInput,MAX_PRECISION)
+def log2(n):
+ return ln(n)/ln(2)
-FLOOR_LN2_EXPONENT = int((((1<<256)-1)/(fixedLog2MaxOutput*ln2)).ln()/ln2)
-FLOOR_LN2_MANTISSA = int(2**FLOOR_LN2_EXPONENT*ln2)
-CEILING_LN2_MANTISSA = int(ln2*(1<<MIN_PRECISION)+1)
+def floor(d):
+ return int(d.to_integral_exact(rounding=ROUND_FLOOR))
+
+
+def ceiling(d):
+ return int(d.to_integral_exact(rounding=ROUND_CEILING))
+
+
+getcontext().prec = MAX_PRECISION
+
+
+maxVal = floor(log2(2**(256-MAX_PRECISION)-1)*2**MAX_PRECISION)-1
+
+
+FLOOR_LN2_EXPONENT = floor(log2((2**256-1)/(maxVal*ln(2))))
+FLOOR_LN2_MANTISSA = floor(2**FLOOR_LN2_EXPONENT*ln(2))
+CEILING_LN2_MANTISSA = ceiling(2**MIN_PRECISION*ln(2))
print ' uint256 constant CEILING_LN2_MANTISSA = 0x{:x};'.format(CEILING_LN2_MANTISSA) |
6e4fcfeb6da8f4d61731ec2cb77c14b09fe35d31 | aurorawatchuk/snapshot.py | aurorawatchuk/snapshot.py | import aurorawatchuk as aw
class AuroraWatchUK(object):
"""Take a snapshot of the AuroraWatch UK status.
This class mimics the behaviour of the aurorawatchuk.AuroraWatchUK class but its fields are evaluated just once,
at the time first requested. Thus the values it returns are snapshots of the status. This is useful
when the information may be required multiple times as it avoids the possibility that the status level
could change between uses. If the information is not required then no network traffic is generated."""
def __init__(self, *args, **kwargs):
object.__setattr__(self, '_awuk', aw.AuroraWatchUK(*args, **kwargs))
object.__setattr__(self, '_fields', {})
def __getattr__(self, item):
if item[0] != '_':
# Cache this item
if item not in self._fields:
self._fields[item] = getattr(self._awuk, item)
return self._fields[item]
def __setattr__(self, key, value):
if key[0] == '_':
raise AttributeError
else:
return object.__setattr__(self, key, value)
def __delattr__(self, item):
if item[0] == '_':
raise AttributeError
else:
return object.__delattr__(self, item)
| from aurorawatchuk import AuroraWatchUK
__author__ = 'Steve Marple'
__version__ = '0.0.8'
__license__ = 'MIT'
class AuroraWatchUK_SS(object):
"""Take a snapshot of the AuroraWatch UK status.
This class mimics the behaviour of the :class:`.aurorawatchuk.AuroraWatchUK` class but its fields are evaluated
just once and cached, at the time first requested. Thus the values it returns are snapshots of the ``status``,
``activity`` and ``description`` fields. This is useful when the information may be required multiple times as
it avoids the possibility that the value could change between uses. If the information is not required then
no network traffic is generated.
For documentation see :class:`.aurorawatchuk.AuroraWatchUK`."""
def __init__(self, *args, **kwargs):
object.__setattr__(self, '_awuk', AuroraWatchUK(*args, **kwargs))
object.__setattr__(self, '_fields', {})
def __getattr__(self, item):
if item[0] != '_':
# Cache this item
if item not in self._fields:
self._fields[item] = getattr(self._awuk, item)
return self._fields[item]
def __setattr__(self, key, value):
if key[0] == '_':
raise AttributeError
else:
return object.__setattr__(self, key, value)
def __delattr__(self, item):
if item[0] == '_':
raise AttributeError
else:
return object.__delattr__(self, item)
| Rename class to AuroraWatchUK_SS and add documentation | Rename class to AuroraWatchUK_SS and add documentation
| Python | mit | stevemarple/python-aurorawatchuk | ---
+++
@@ -1,15 +1,24 @@
-import aurorawatchuk as aw
+from aurorawatchuk import AuroraWatchUK
-class AuroraWatchUK(object):
+__author__ = 'Steve Marple'
+__version__ = '0.0.8'
+__license__ = 'MIT'
+
+
+class AuroraWatchUK_SS(object):
"""Take a snapshot of the AuroraWatch UK status.
- This class mimics the behaviour of the aurorawatchuk.AuroraWatchUK class but its fields are evaluated just once,
- at the time first requested. Thus the values it returns are snapshots of the status. This is useful
- when the information may be required multiple times as it avoids the possibility that the status level
- could change between uses. If the information is not required then no network traffic is generated."""
+ This class mimics the behaviour of the :class:`.aurorawatchuk.AuroraWatchUK` class but its fields are evaluated
+ just once and cached, at the time first requested. Thus the values it returns are snapshots of the ``status``,
+ ``activity`` and ``description`` fields. This is useful when the information may be required multiple times as
+ it avoids the possibility that the value could change between uses. If the information is not required then
+ no network traffic is generated.
+
+ For documentation see :class:`.aurorawatchuk.AuroraWatchUK`."""
+
def __init__(self, *args, **kwargs):
- object.__setattr__(self, '_awuk', aw.AuroraWatchUK(*args, **kwargs))
+ object.__setattr__(self, '_awuk', AuroraWatchUK(*args, **kwargs))
object.__setattr__(self, '_fields', {})
def __getattr__(self, item):
@@ -30,4 +39,3 @@
raise AttributeError
else:
return object.__delattr__(self, item)
- |
17d9c84b01a6b9adc264164041d4c226355a6943 | loadimpact/utils.py | loadimpact/utils.py | # coding=utf-8
__all__ = ['UTC']
from datetime import timedelta, tzinfo
_ZERO = timedelta(0)
def is_dict_different(d1, d2, epsilon=0.00000000001):
s1 = set(d1.keys())
s2 = set(d2.keys())
intersect = s1.intersection(s2)
added = s1 - intersect
removed = s2 - intersect
changed = []
for o in intersect:
if isinstance(s2, float) and abs(d2[o] - d1[o]) > epsilon:
changed.append(o)
elif d2[o] != d1[o]:
changed.append(o)
return (0 < len(added) or 0 < len(removed) or 0 < len(set(changed)))
class UTC(tzinfo):
def utcoffset(self, dt):
return _ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return _ZERO
| # coding=utf-8
__all__ = ['UTC']
from datetime import timedelta, tzinfo
_ZERO = timedelta(0)
def is_dict_different(d1, d2, epsilon=0.00000000001):
s1 = set(d1.keys())
s2 = set(d2.keys())
intersect = s1.intersection(s2)
added = s1 - intersect
removed = s2 - intersect
changed = []
for o in intersect:
if isinstance(d2[o], float):
if abs(d2[o] - d1[o]) > epsilon:
changed.append(o)
elif d2[o] != d1[o]:
changed.append(o)
return (0 < len(added) or 0 < len(removed) or 0 < len(set(changed)))
class UTC(tzinfo):
def utcoffset(self, dt):
return _ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return _ZERO
| Fix float diff comparison in dict differ function. | Fix float diff comparison in dict differ function.
| Python | apache-2.0 | loadimpact/loadimpact-sdk-python | ---
+++
@@ -16,8 +16,9 @@
removed = s2 - intersect
changed = []
for o in intersect:
- if isinstance(s2, float) and abs(d2[o] - d1[o]) > epsilon:
- changed.append(o)
+ if isinstance(d2[o], float):
+ if abs(d2[o] - d1[o]) > epsilon:
+ changed.append(o)
elif d2[o] != d1[o]:
changed.append(o)
return (0 < len(added) or 0 < len(removed) or 0 < len(set(changed))) |
1cdf0cd00cbc7006194d07770b3b804dd661500e | t_ai_player.py | t_ai_player.py | #!/usr/bin/env python
import unittest
import pdb
import gui
import human_player
import rules
import game
#import profile
from ai_player import *
class AIPlayerTest(unittest.TestCase):
def setUp(self):
# TODO
player1 = AIPlayer("Blomp")
player2 = human_player.HumanPlayer("Kubba")
r = rules.Rules(13, "standard")
self.game = game.Game(r, player1, player2)
self.gui = None
'''
self.s = ABState()
self.s.set_state(my_game.current_state)
'''
def test_find_one_move(self):
p = AIPlayer("Deep thunk")
pdb.set_trace()
p.prompt_for_action(self.game, self.gui)
ma = p.get_action(self.game, self.gui)
self.assertEquals(ma, gui.MoveAction(6,6))
if __name__ == "__main__":
unittest.main()
| #!/usr/bin/env python
import unittest
import pdb
import gui
import human_player
import rules
import game
#import profile
from ai_player import *
class AIPlayerTest(unittest.TestCase):
def setUp(self):
# TODO
player1 = AIPlayer("Blomp")
player2 = human_player.HumanPlayer("Kubba")
r = rules.Rules(5, "standard")
self.game = game.Game(r, player1, player2)
self.gui = None
'''
self.s = ABState()
self.s.set_state(my_game.current_state)
'''
def test_find_one_move(self):
p = AIPlayer("Deep thunk")
pdb.set_trace()
p.prompt_for_action(self.game, self.gui)
ma = p.get_action(self.game, self.gui)
self.assertEquals(ma, gui.MoveAction.create_from_tuple(2,2))
if __name__ == "__main__":
unittest.main()
| Change the test board size to make it run faster | Change the test board size to make it run faster
| Python | mit | cropleyb/pentai,cropleyb/pentai,cropleyb/pentai | ---
+++
@@ -17,7 +17,7 @@
# TODO
player1 = AIPlayer("Blomp")
player2 = human_player.HumanPlayer("Kubba")
- r = rules.Rules(13, "standard")
+ r = rules.Rules(5, "standard")
self.game = game.Game(r, player1, player2)
self.gui = None
'''
@@ -30,7 +30,7 @@
pdb.set_trace()
p.prompt_for_action(self.game, self.gui)
ma = p.get_action(self.game, self.gui)
- self.assertEquals(ma, gui.MoveAction(6,6))
+ self.assertEquals(ma, gui.MoveAction.create_from_tuple(2,2))
if __name__ == "__main__":
unittest.main() |
0469ba1f4f1d907013c328bc2834905dd391dba8 | simple/bing_images.py | simple/bing_images.py | import requests
def get_latest_header_images(idx=0, num=5):
resp = requests.get("http://www.bing.com/HPImageArchive.aspx?format=js&n={0}&idx={1}".format(num, idx)).json()
if resp is None:
return {}
return {
"images": [
{"url": "http://bing.com" + item["url"], "copyright": item["copyright"]} for item in resp["images"]
]
}
def download_to(url, path):
req = requests.get(url, stream=True)
with open(path, "wb") as fd:
for chunk in req.iter_content():
fd.write(chunk) | import requests
def get_latest_header_images(idx=0, num=5):
resp = requests.get("https://www.bing.com/HPImageArchive.aspx?format=js&n={0}&idx={1}".format(num, idx)).json()
if resp is None:
return {}
return {
"images": [
{"url": "https://bing.com" + item["url"], "copyright": item["copyright"]} for item in resp["images"]
]
}
def download_to(url, path):
req = requests.get(url, stream=True)
with open(path, "wb") as fd:
for chunk in req.iter_content():
fd.write(chunk)
| Change url protocol for more secure access | Change url protocol for more secure access | Python | mit | orf/simple,orf/simple,orf/simple | ---
+++
@@ -2,14 +2,14 @@
def get_latest_header_images(idx=0, num=5):
- resp = requests.get("http://www.bing.com/HPImageArchive.aspx?format=js&n={0}&idx={1}".format(num, idx)).json()
+ resp = requests.get("https://www.bing.com/HPImageArchive.aspx?format=js&n={0}&idx={1}".format(num, idx)).json()
if resp is None:
return {}
return {
"images": [
- {"url": "http://bing.com" + item["url"], "copyright": item["copyright"]} for item in resp["images"]
+ {"url": "https://bing.com" + item["url"], "copyright": item["copyright"]} for item in resp["images"]
]
}
|
2dec3e5810ef9ba532eaa735d0eac149c240aa2f | pyxrf/api.py | pyxrf/api.py | # from .model.fileio import (stitch_fitted_results, spec_to_hdf, create_movie,
# combine_data_to_recon, h5file_for_recon, export_to_view)
# from .model.load_data_from_db import make_hdf, make_hdf_stitched, export1d
# from .model.command_tools import fit_pixel_data_and_save, pyxrf_batch
import logging
logger = logging.getLogger()
try:
from .model.load_data_from_db import db, db_analysis
except ImportError:
db = None
db_analysis = None
logger.error('databroker is not available.')
| from .model.fileio import (stitch_fitted_results, spec_to_hdf, create_movie, # noqa: F401
combine_data_to_recon, h5file_for_recon, export_to_view, # noqa: F401
make_hdf_stitched) # noqa: F401
from .model.load_data_from_db import make_hdf, export1d # noqa: F401
from .model.command_tools import fit_pixel_data_and_save, pyxrf_batch # noqa: F401
# Note: the statement '# noqa: F401' is telling flake8 to ignore violation F401 at the given line
# Violation F401 - the package is imported but unused
import logging
logger = logging.getLogger()
try:
from .model.load_data_from_db import db, db_analysis
except ImportError:
db = None
db_analysis = None
logger.error('databroker is not available.')
| Set flake8 to ignore F401 violations | Set flake8 to ignore F401 violations
| Python | bsd-3-clause | NSLS-II/PyXRF,NSLS-II-HXN/PyXRF,NSLS-II-HXN/PyXRF | ---
+++
@@ -1,7 +1,11 @@
-# from .model.fileio import (stitch_fitted_results, spec_to_hdf, create_movie,
-# combine_data_to_recon, h5file_for_recon, export_to_view)
-# from .model.load_data_from_db import make_hdf, make_hdf_stitched, export1d
-# from .model.command_tools import fit_pixel_data_and_save, pyxrf_batch
+from .model.fileio import (stitch_fitted_results, spec_to_hdf, create_movie, # noqa: F401
+ combine_data_to_recon, h5file_for_recon, export_to_view, # noqa: F401
+ make_hdf_stitched) # noqa: F401
+from .model.load_data_from_db import make_hdf, export1d # noqa: F401
+from .model.command_tools import fit_pixel_data_and_save, pyxrf_batch # noqa: F401
+
+# Note: the statement '# noqa: F401' is telling flake8 to ignore violation F401 at the given line
+# Violation F401 - the package is imported but unused
import logging
logger = logging.getLogger() |
dcb8678b8f460ce1b5d5d86e14d567a3bcbaa0d1 | riak/util.py | riak/util.py | import collections
def quacks_like_dict(object):
"""Check if object is dict-like"""
return isinstance(object, collections.Mapping)
def deep_merge(a, b):
"""Merge two deep dicts non-destructively
Uses a stack to avoid maximum recursion depth exceptions
>>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
>>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
>>> c = merge(a, b)
>>> from pprint import pprint; pprint(c)
{'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}}
"""
assert quacks_like_dict(a), quacks_like_dict(b)
dst = a.copy()
stack = [(dst, b)]
while stack:
current_dst, current_src = stack.pop()
for key in current_src:
if key not in current_dst:
current_dst[key] = current_src[key]
else:
if quacks_like_dict(current_src[key]) and quacks_like_dict(current_dst[key]) :
stack.append((current_dst[key], current_src[key]))
else:
current_dst[key] = current_src[key]
return dst
| try:
from collections import Mapping
except ImportError:
# compatibility with Python 2.5
Mapping = dict
def quacks_like_dict(object):
"""Check if object is dict-like"""
return isinstance(object, Mapping)
def deep_merge(a, b):
"""Merge two deep dicts non-destructively
Uses a stack to avoid maximum recursion depth exceptions
>>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
>>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
>>> c = merge(a, b)
>>> from pprint import pprint; pprint(c)
{'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}}
"""
assert quacks_like_dict(a), quacks_like_dict(b)
dst = a.copy()
stack = [(dst, b)]
while stack:
current_dst, current_src = stack.pop()
for key in current_src:
if key not in current_dst:
current_dst[key] = current_src[key]
else:
if quacks_like_dict(current_src[key]) and quacks_like_dict(current_dst[key]) :
stack.append((current_dst[key], current_src[key]))
else:
current_dst[key] = current_src[key]
return dst
| Adjust for compatibility with Python 2.5 | Adjust for compatibility with Python 2.5
| Python | apache-2.0 | basho/riak-python-client,bmess/riak-python-client,GabrielNicolasAvellaneda/riak-python-client,basho/riak-python-client,bmess/riak-python-client,GabrielNicolasAvellaneda/riak-python-client,basho/riak-python-client | ---
+++
@@ -1,8 +1,12 @@
-import collections
+try:
+ from collections import Mapping
+except ImportError:
+ # compatibility with Python 2.5
+ Mapping = dict
def quacks_like_dict(object):
"""Check if object is dict-like"""
- return isinstance(object, collections.Mapping)
+ return isinstance(object, Mapping)
def deep_merge(a, b):
"""Merge two deep dicts non-destructively |
96855ef5baee62f63887d942854c065ad6943f87 | micropress/forms.py | micropress/forms.py | from django import forms
from micropress.models import Article, Section, Press
class ArticleForm(forms.ModelForm):
section = forms.ModelChoiceField(Section.objects.all(), empty_label=None)
class Meta:
model = Article
fields = ('title', 'slug', 'byline', 'section', 'body', 'markup_type')
class CreatePressForm(forms.ModelForm):
class Meta:
model = Press
exclude = ('content_type', 'object_id', 'realm')
| from django import forms
from micropress.models import Article, Section, Press
class ArticleForm(forms.ModelForm):
section = forms.ModelChoiceField(Section.objects.all(), empty_label=None)
class Meta:
model = Article
fields = ('title', 'slug', 'byline', 'section', 'body', 'markup_type')
def clean(self):
cleaned_data = self.cleaned_data
slug = cleaned_data.get('slug', '')
press = self.instance.press
if Article.objects.filter(press=press, slug=slug).exists():
raise forms.ValidationError(
"Article with slug '{0}' already exists.".format(slug))
return cleaned_data
class CreatePressForm(forms.ModelForm):
class Meta:
model = Press
exclude = ('content_type', 'object_id', 'realm')
| Validate that Article.slug and press are unique_together. | Validate that Article.slug and press are unique_together.
| Python | mit | jbradberry/django-micro-press,jbradberry/django-micro-press | ---
+++
@@ -9,6 +9,15 @@
model = Article
fields = ('title', 'slug', 'byline', 'section', 'body', 'markup_type')
+ def clean(self):
+ cleaned_data = self.cleaned_data
+ slug = cleaned_data.get('slug', '')
+ press = self.instance.press
+ if Article.objects.filter(press=press, slug=slug).exists():
+ raise forms.ValidationError(
+ "Article with slug '{0}' already exists.".format(slug))
+ return cleaned_data
+
class CreatePressForm(forms.ModelForm):
class Meta: |
9c34cdd6f82f84a54bedc505ef0ad4b9df40ef6a | tldr/config.py | tldr/config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from os import path
import sys
import yaml
def get_config():
"""Get the configurations from .tldrrc and return it as a dict."""
config_path = path.join(path.expanduser('~'), '.tldrrc')
if not path.exists(config_path):
sys.exit("Can't find config file at: {0}. You may use `tldr init` "
"to init the config file.".format(config_path))
with open(config_path) as f:
try:
config = yaml.safe_load(f)
except yaml.scanner.ScannerError:
sys.exit("The config file is not a valid YAML file.")
supported_colors = ['black', 'red', 'green', 'yellow', 'blue',
'magenta', 'cyan', 'white']
if not set(config['colors'].values()).issubset(set(supported_colors)):
sys.exit("Unsupported colors in config file: {0}".format(
' '.join(set(config['colors'].values()) - set(supported_colors))))
if not path.exists(config['repo_directory']):
sys.exit("Can't find the tldr repo, check the `repo_direcotry` "
"setting in config file.")
return config
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from os import path
import sys
import yaml
def get_config():
"""Get the configurations from .tldrrc and return it as a dict."""
config_path = path.join(path.expanduser('~'), '.tldrrc')
if not path.exists(config_path):
sys.exit("Can't find config file at: {0}. You may use `tldr init` "
"to init the config file.".format(config_path))
with open(config_path) as f:
try:
config = yaml.safe_load(f)
except yaml.scanner.ScannerError:
sys.exit("The config file is not a valid YAML file.")
supported_colors = ['black', 'red', 'green', 'yellow', 'blue',
'magenta', 'cyan', 'white']
if not set(config['colors'].values()).issubset(set(supported_colors)):
sys.exit("Unsupported colors in config file: {0}.".format(
', '.join(set(config['colors'].values()) - set(supported_colors))))
if not path.exists(config['repo_directory']):
sys.exit("Can't find the tldr repo, check the `repo_direcotry` "
"setting in config file.")
return config
| Improve error output when detect unsupported color | Improve error output when detect unsupported color
| Python | mit | lord63/tldr.py | ---
+++
@@ -25,8 +25,8 @@
supported_colors = ['black', 'red', 'green', 'yellow', 'blue',
'magenta', 'cyan', 'white']
if not set(config['colors'].values()).issubset(set(supported_colors)):
- sys.exit("Unsupported colors in config file: {0}".format(
- ' '.join(set(config['colors'].values()) - set(supported_colors))))
+ sys.exit("Unsupported colors in config file: {0}.".format(
+ ', '.join(set(config['colors'].values()) - set(supported_colors))))
if not path.exists(config['repo_directory']):
sys.exit("Can't find the tldr repo, check the `repo_direcotry` "
"setting in config file.") |
31a8d7377d46abef6eec6f7eb5b154f948c3388a | spam/ansiInventory.py | spam/ansiInventory.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
AnsibleInventory:
INTRO:
USAGE:
"""
import os
import ansible.inventory
class AnsibleInventory(object):
'''
Ansible Inventory wrapper class.
'''
def __init__(self, inventory_filename):
'''
Initialize Inventory
'''
if not os.path.exists(inventory_filename):
print "Provide a valid inventory filename"
return
self.inventory = ansible.inventory.InventoryParser(inventory_filename)
def get_hosts(self, group=None):
'''
Get the hosts
'''
hostlist = []
for group in self.inventory.groups:
groupdict = {}
groupdict['group'] = group
groupdict['hostlist'] = []
groupobj = self.inventory.groups.get(group)
for host in groupobj.get_hosts():
groupdict['hostlist'].append(host.name)
hostlist.append(groupdict)
return hostlist
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
AnsibleInventory:
INTRO:
USAGE:
"""
import os
import ansible.inventory
class AnsibleInventory(object):
'''
Ansible Inventory wrapper class.
'''
def __init__(self, inventory_filename):
'''
Initialize Inventory
'''
self.inventory = None
if not os.path.exists(inventory_filename):
print "Provide a valid inventory filename"
return
self.inventory = ansible.inventory.InventoryParser(inventory_filename)
def get_hosts(self, group=None):
'''
Get the hosts
'''
hostlist = []
if group:
groupobj = self.inventory.groups.get(group)
groupdict = {}
groupdict['hostlist'] = []
for host in groupobj.get_hosts():
groupdict['hostlist'].append(host.name)
hostlist.append(groupdict)
else:
for group in self.inventory.groups:
groupdict = {}
groupdict['group'] = group
groupdict['hostlist'] = []
groupobj = self.inventory.groups.get(group)
for host in groupobj.get_hosts():
groupdict['hostlist'].append(host.name)
hostlist.append(groupdict)
return hostlist
| Fix get_host() to return host list | Fix get_host() to return host list
| Python | apache-2.0 | bdastur/spam,bdastur/spam | ---
+++
@@ -22,6 +22,7 @@
'''
Initialize Inventory
'''
+ self.inventory = None
if not os.path.exists(inventory_filename):
print "Provide a valid inventory filename"
return
@@ -33,14 +34,23 @@
Get the hosts
'''
hostlist = []
- for group in self.inventory.groups:
+
+ if group:
+ groupobj = self.inventory.groups.get(group)
groupdict = {}
- groupdict['group'] = group
groupdict['hostlist'] = []
- groupobj = self.inventory.groups.get(group)
for host in groupobj.get_hosts():
groupdict['hostlist'].append(host.name)
hostlist.append(groupdict)
+ else:
+ for group in self.inventory.groups:
+ groupdict = {}
+ groupdict['group'] = group
+ groupdict['hostlist'] = []
+ groupobj = self.inventory.groups.get(group)
+ for host in groupobj.get_hosts():
+ groupdict['hostlist'].append(host.name)
+ hostlist.append(groupdict)
return hostlist
|
25121b9bdceda0b0a252e2bdec0e76a4eb733a4c | dotsecrets/textsub.py | dotsecrets/textsub.py | # Original algorithm by Xavier Defrang.
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
# This implementation by alane@sourceforge.net.
import re
import UserDict
class Textsub(UserDict.UserDict):
def __init__(self, dict=None):
self.re = None
self.regex = None
UserDict.UserDict.__init__(self, dict)
def compile(self):
if len(self.data) > 0:
tmp = "(%s)" % "|".join(map(re.escape,
self.data.keys()))
if self.re != tmp:
self.re = tmp
self.regex = re.compile(self.re)
def __call__(self, match):
return self.data[match.string[match.start():match.end()]]
def sub(self, s):
if len(self.data) == 0:
return s
return self.regex.sub(self, s)
| # Original algorithm by Xavier Defrang.
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
# This implementation by alane@sourceforge.net.
import re
try:
from UserDict import UserDict
except ImportError:
from collections import UserDict
class Textsub(UserDict):
def __init__(self, dict=None):
self.re = None
self.regex = None
UserDict.__init__(self, dict)
def compile(self):
if len(self.data) > 0:
tmp = "(%s)" % "|".join(map(re.escape,
self.data.keys()))
if self.re != tmp:
self.re = tmp
self.regex = re.compile(self.re)
def __call__(self, match):
return self.data[match.string[match.start():match.end()]]
def sub(self, s):
if len(self.data) == 0:
return s
return self.regex.sub(self, s)
| Make UserDict usage compatible with Python3 | Make UserDict usage compatible with Python3
| Python | bsd-3-clause | oohlaf/dotsecrets | ---
+++
@@ -3,14 +3,18 @@
# This implementation by alane@sourceforge.net.
import re
-import UserDict
+
+try:
+ from UserDict import UserDict
+except ImportError:
+ from collections import UserDict
-class Textsub(UserDict.UserDict):
+class Textsub(UserDict):
def __init__(self, dict=None):
self.re = None
self.regex = None
- UserDict.UserDict.__init__(self, dict)
+ UserDict.__init__(self, dict)
def compile(self):
if len(self.data) > 0: |
4196131899df6183a612e33427986cff052b2044 | addons/project_issue/migrations/8.0.1.0/post-migration.py | addons/project_issue/migrations/8.0.1.0/post-migration.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, a suite of business apps
# This module Copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import SUPERUSER_UID as uid
from openerp.openupgrade import openupgrade, openupgrade_80
@openupgrade.migrate
def migrate(cr, version):
openupgrade.map_values(
cr,
openupgrade.get_legacy_name('priority'),
'priority',
[('5', '0'), ('4', '0'), ('3', '1'), ('2', '2'), ('1', '2')],
table='project_issue', write='sql')
openupgrade_80.set_message_last_post(cr, uid, ['project.issue'])
openupgrade.load_data(
cr, 'project_issue', 'migrations/8.0.1.0/noupdate_changes.xml')
| # -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, a suite of business apps
# This module Copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import SUPERUSER_ID as uid
from openerp.openupgrade import openupgrade, openupgrade_80
@openupgrade.migrate
def migrate(cr, version):
openupgrade.map_values(
cr,
openupgrade.get_legacy_name('priority'),
'priority',
[('5', '0'), ('4', '0'), ('3', '1'), ('2', '2'), ('1', '2')],
table='project_issue', write='sql')
openupgrade_80.set_message_last_post(cr, uid, ['project.issue'])
openupgrade.load_data(
cr, 'project_issue', 'migrations/8.0.1.0/noupdate_changes.xml')
| Fix import SUPERUSER_ID in project_issue migration scripts | Fix import SUPERUSER_ID in project_issue migration scripts
Found error:
2014-07-18 17:04:11,710 8772 ERROR v8mig openerp.modules.migration: module project_issue: Unable to load post-migration file project_issue/migrations/8.0.1.0/post-migration.py
Traceback (most recent call last):
File "/home/dr/work/openupg/OpenUpgrade/openerp/modules/migration.py", line 167, in migrate_module
mod = imp.load_module(name, fp, pathname, ('.py', 'r', imp.PY_SOURCE))
File "/home/dr/work/openupg/OpenUpgrade/addons/project_issue/migrations/8.0.1.0/post-migration.py", line 22, in <module>
from openerp import SUPERUSER_UID as uid
ImportError: cannot import name SUPERUSER_UID | Python | agpl-3.0 | 0k/OpenUpgrade,blaggacao/OpenUpgrade,0k/OpenUpgrade,csrocha/OpenUpgrade,0k/OpenUpgrade,grap/OpenUpgrade,0k/OpenUpgrade,mvaled/OpenUpgrade,Endika/OpenUpgrade,Endika/OpenUpgrade,damdam-s/OpenUpgrade,csrocha/OpenUpgrade,blaggacao/OpenUpgrade,bwrsandman/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,grap/OpenUpgrade,hifly/OpenUpgrade,hifly/OpenUpgrade,blaggacao/OpenUpgrade,bwrsandman/OpenUpgrade,mvaled/OpenUpgrade,OpenUpgrade/OpenUpgrade,damdam-s/OpenUpgrade,csrocha/OpenUpgrade,damdam-s/OpenUpgrade,grap/OpenUpgrade,sebalix/OpenUpgrade,grap/OpenUpgrade,OpenUpgrade/OpenUpgrade,OpenUpgrade/OpenUpgrade,mvaled/OpenUpgrade,Endika/OpenUpgrade,csrocha/OpenUpgrade,0k/OpenUpgrade,0k/OpenUpgrade,grap/OpenUpgrade,OpenUpgrade/OpenUpgrade,bwrsandman/OpenUpgrade,bwrsandman/OpenUpgrade,mvaled/OpenUpgrade,OpenUpgrade/OpenUpgrade,blaggacao/OpenUpgrade,pedrobaeza/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,damdam-s/OpenUpgrade,pedrobaeza/OpenUpgrade,kirca/OpenUpgrade,hifly/OpenUpgrade,OpenUpgrade/OpenUpgrade,hifly/OpenUpgrade,mvaled/OpenUpgrade,bwrsandman/OpenUpgrade,blaggacao/OpenUpgrade,csrocha/OpenUpgrade,damdam-s/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,damdam-s/OpenUpgrade,pedrobaeza/OpenUpgrade,Endika/OpenUpgrade,kirca/OpenUpgrade,mvaled/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,pedrobaeza/OpenUpgrade,damdam-s/OpenUpgrade,Endika/OpenUpgrade,hifly/OpenUpgrade,bwrsandman/OpenUpgrade,Endika/OpenUpgrade,csrocha/OpenUpgrade,sebalix/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,blaggacao/OpenUpgrade,grap/OpenUpgrade,OpenUpgrade/OpenUpgrade,grap/OpenUpgrade,kirca/OpenUpgrade,csrocha/OpenUpgrade,kirca/OpenUpgrade,sebalix/OpenUpgrade,mvaled/OpenUpgrade,sebalix/OpenUpgrade,pedrobaeza/OpenUpgrade,kirca/OpenUpgrade,blaggacao/OpenUpgrade,sebalix/OpenUpgrade,sebalix/OpenUpgrade,pedrobaeza/OpenUpgrade,hifly/OpenUpgrade,sebalix/OpenUpgrade,bwrsandman/OpenUpgrade,Endika/OpenUpgrade,hifly/OpenUpgrade,kirca/OpenUpgrade,pedrobaeza/OpenUpgrade,kirca/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade | ---
+++
@@ -19,7 +19,7 @@
#
##############################################################################
-from openerp import SUPERUSER_UID as uid
+from openerp import SUPERUSER_ID as uid
from openerp.openupgrade import openupgrade, openupgrade_80
|
40ac5bc5f8c3f68c0c5b2b6debe19b487893d6f5 | ecal_users.py | ecal_users.py | from google.appengine.ext import db
import uuid
class EmailUser(db.Model):
# the email address that the user sends events to:
email_address = db.StringProperty(default=str(uuid.uuid4()))
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.DateTimeProperty(auto_now_add=True)
| from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 10 digits. Since
there are 62 choices per digit, this gives:
62 ** 10 = 8.39299366 x 10 ** 17
possible results. When there are a million accounts active,
we need:
10 ** 6 x 10 ** 6 = 10 ** 12
possible results to have a one-in-a-million chance of a
collision, so this seems like a safe number.
"""
chars = string.letters + string.digits
return ''.join([ random.choice(chars) for i in range(10) ])
class EmailUser(db.Model):
# the email address that the user sends events to:
email_address = db.StringProperty(default=make_address())
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.DateTimeProperty(auto_now_add=True)
| Use a slightly friendlier string than UUID for email addresses. | Use a slightly friendlier string than UUID for email addresses.
| Python | mit | eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot | ---
+++
@@ -1,9 +1,26 @@
from google.appengine.ext import db
-import uuid
+import random
+import string
+def make_address():
+ """
+ Returns a random alphanumeric string of 10 digits. Since
+ there are 62 choices per digit, this gives:
+ 62 ** 10 = 8.39299366 x 10 ** 17
+
+ possible results. When there are a million accounts active,
+ we need:
+ 10 ** 6 x 10 ** 6 = 10 ** 12
+
+ possible results to have a one-in-a-million chance of a
+ collision, so this seems like a safe number.
+ """
+ chars = string.letters + string.digits
+ return ''.join([ random.choice(chars) for i in range(10) ])
+
class EmailUser(db.Model):
# the email address that the user sends events to:
- email_address = db.StringProperty(default=str(uuid.uuid4()))
+ email_address = db.StringProperty(default=make_address())
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.DateTimeProperty(auto_now_add=True) |
9310be1429109f5324502f7e66318e23f5ea489d | test/test_terminate_handler.py | test/test_terminate_handler.py | import uuid
from handler_fixture import StationHandlerTestCase
from groundstation.transfer.request_handlers import handle_fetchobject
from groundstation.transfer.response_handlers import handle_terminate
class TestHandlerTerminate(StationHandlerTestCase):
def test_handle_terminate(self):
# Write an object into the station
oid = self.station.station.write("butts lol")
self.station.payload = oid
self.station.id = uuid.uuid1()
self.assertEqual(len(self.station.station.registry.contents), 0)
self.station.station.register_request(self.station)
self.assertEqual(len(self.station.station.registry.contents), 1)
handle_fetchobject(self.station)
term = self.station.stream.pop()
handle_terminate(term)
self.assertEqual(len(self.station.station.registry.contents), 0)
| import uuid
from handler_fixture import StationHandlerTestCase
from groundstation.transfer.request_handlers import handle_fetchobject
from groundstation.transfer.response_handlers import handle_terminate
class TestHandlerTerminate(StationHandlerTestCase):
def test_handle_terminate(self):
# Write an object into the station
oid = self.station.station.write("butts lol")
self.station.payload = oid
self.station.id = uuid.uuid1()
self.assertEqual(len(self.station.station.registry.contents), 0)
self.station.station.register_request(self.station)
self.assertEqual(len(self.station.station.registry.contents), 1)
handle_fetchobject(self.station)
ret = [0]
def _teardown():
ret[0] += 1
self.station.teardown = _teardown
term = self.station.stream.pop()
handle_terminate(term)
self.assertEqual(len(self.station.station.registry.contents), 0)
self.assertEqual(ret[0], 1)
| Test that teardown methods are actually called | Test that teardown methods are actually called
| Python | mit | richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation | ---
+++
@@ -18,8 +18,14 @@
self.assertEqual(len(self.station.station.registry.contents), 1)
handle_fetchobject(self.station)
+ ret = [0]
+
+ def _teardown():
+ ret[0] += 1
+ self.station.teardown = _teardown
term = self.station.stream.pop()
handle_terminate(term)
self.assertEqual(len(self.station.station.registry.contents), 0)
+ self.assertEqual(ret[0], 1) |
0b99bf43e02c22f0aa136ca02717521b1f4f2414 | salt/runner.py | salt/runner.py | '''
Execute salt convenience routines
'''
# Import python modules
import sys
# Import salt modules
import salt.loader
class Runner(object):
'''
Execute the salt runner interface
'''
def __init__(self, opts):
self.opts = opts
self.functions = salt.loader.runner(opts)
def _verify_fun(self):
'''
Verify an environmental issues
'''
if not self.opts['fun']:
err = 'Must pass a runner function'
sys.stderr.write('%s\n' % err)
sys.exit(1)
if not self.functions.has_key(self.opts['fun']):
err = 'Passed function is unavailable'
sys.stderr.write('%s\n' % err)
sys.exit(1)
def run(self):
'''
Execuete the runner sequence
'''
self._verify_fun()
self.functions[self.opts['fun']](*self.opts['arg'])
| '''
Execute salt convenience routines
'''
# Import python modules
import sys
# Import salt modules
import salt.loader
class Runner(object):
'''
Execute the salt runner interface
'''
def __init__(self, opts):
self.opts = opts
self.functions = salt.loader.runner(opts)
def _verify_fun(self):
'''
Verify an environmental issues
'''
if not self.opts['fun']:
err = 'Must pass a runner function'
sys.stderr.write('%s\n' % err)
sys.exit(1)
if not self.functions.has_key(self.opts['fun']):
err = 'Passed function is unavailable'
sys.stderr.write('%s\n' % err)
sys.exit(1)
def _print_docs(self):
'''
Print out the documentation!
'''
for fun in sorted(self.functions):
if fun.startswith(self.opts['fun']):
print fun + ':'
print self.functions[fun].__doc__
print ''
def run(self):
'''
Execuete the runner sequence
'''
if self.opts['doc']:
self._print_docs()
else:
self._verify_fun()
self.functions[self.opts['fun']](*self.opts['arg'])
| Add doc printing for salt-run | Add doc printing for salt-run
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -29,9 +29,22 @@
sys.stderr.write('%s\n' % err)
sys.exit(1)
+ def _print_docs(self):
+ '''
+ Print out the documentation!
+ '''
+ for fun in sorted(self.functions):
+ if fun.startswith(self.opts['fun']):
+ print fun + ':'
+ print self.functions[fun].__doc__
+ print ''
+
def run(self):
'''
Execuete the runner sequence
'''
- self._verify_fun()
- self.functions[self.opts['fun']](*self.opts['arg'])
+ if self.opts['doc']:
+ self._print_docs()
+ else:
+ self._verify_fun()
+ self.functions[self.opts['fun']](*self.opts['arg']) |
33fd4bba1f2c44e871051862db8071fadb0e9825 | core-plugins/shared/1/dss/reporting-plugins/shared_create_metaproject/shared_create_metaproject.py | core-plugins/shared/1/dss/reporting-plugins/shared_create_metaproject/shared_create_metaproject.py | # -*- coding: utf-8 -*-
# Ingestion service: create a metaproject (tag) with user-defined name in given space
def process(transaction, parameters, tableBuilder):
"""Create a project with user-defined name in given space.
"""
# Prepare the return table
tableBuilder.addHeader("success")
tableBuilder.addHeader("message")
# Add a row for the results
row = tableBuilder.addRow()
# Retrieve parameters from client
metaprojectCode = parameters.get("metaprojectCode")
username = parameters.get("userName")
# Try retrieving the metaproject (tag)
metaproject = transaction.getMetaproject(metaprojectCode, username)
if metaproject is None:
# Create the metaproject (tag)
metaproject = transaction.createNewMetaproject(metaprojectCode,
"Test",
username)
# Check that creation was succcessful
if metaproject is None:
success = "false"
message = "Could not create metaproject " + metaprojectCode + "."
else:
success = "true"
message = "Tag " + metaprojectCode + " successfully created."
else:
success = "false"
message = "Tag " + metaprojectCode + " exists already."
# Add the results to current row
row.setCell("success", success)
row.setCell("message", message)
| # -*- coding: utf-8 -*-
# Ingestion service: create a metaproject (tag) with user-defined name in given space
def process(transaction, parameters, tableBuilder):
"""Create a project with user-defined name in given space.
"""
# Prepare the return table
tableBuilder.addHeader("success")
tableBuilder.addHeader("message")
# Add a row for the results
row = tableBuilder.addRow()
# Retrieve parameters from client
username = parameters.get("userName")
metaprojectCode = parameters.get("metaprojectCode")
metaprojectDescr = parameters.get("metaprojectDescr")
if metaprojectDescr is None:
metaprojectDescr = ""
# Try retrieving the metaproject (tag)
metaproject = transaction.getMetaproject(metaprojectCode, username)
if metaproject is None:
# Create the metaproject (tag)
metaproject = transaction.createNewMetaproject(metaprojectCode,
metaprojectDescr,
username)
# Check that creation was succcessful
if metaproject is None:
success = "false"
message = "Could not create metaproject " + metaprojectCode + "."
else:
success = "true"
message = "Tag " + metaprojectCode + " successfully created."
else:
success = "false"
message = "Tag " + metaprojectCode + " exists already."
# Add the results to current row
row.setCell("success", success)
row.setCell("message", message)
| Create metaproject with user-provided description. | Create metaproject with user-provided description.
| Python | apache-2.0 | aarpon/obit_shared_core_technology,aarpon/obit_shared_core_technology,aarpon/obit_shared_core_technology | ---
+++
@@ -14,8 +14,11 @@
row = tableBuilder.addRow()
# Retrieve parameters from client
+ username = parameters.get("userName")
metaprojectCode = parameters.get("metaprojectCode")
- username = parameters.get("userName")
+ metaprojectDescr = parameters.get("metaprojectDescr")
+ if metaprojectDescr is None:
+ metaprojectDescr = ""
# Try retrieving the metaproject (tag)
metaproject = transaction.getMetaproject(metaprojectCode, username)
@@ -24,7 +27,7 @@
# Create the metaproject (tag)
metaproject = transaction.createNewMetaproject(metaprojectCode,
- "Test",
+ metaprojectDescr,
username)
# Check that creation was succcessful |
b345c00b41ade2e12449566f7cb013a7bb8d078f | democracy/migrations/0032_add_language_code_to_comment.py | democracy/migrations/0032_add_language_code_to_comment.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2016-12-16 15:03
from __future__ import unicode_literals
from django.db import migrations, models
from democracy.models import SectionComment
def forwards_func(apps, schema_editor):
for comment in SectionComment.objects.all():
comment._detect_lang()
comment.save()
def backwards_func(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('democracy', '0031_remove_untranslated_fields'),
]
operations = [
migrations.AlterModelOptions(
name='sectionimage',
options={'ordering': ('ordering', 'translations__title'), 'verbose_name': 'section image', 'verbose_name_plural': 'section images'},
),
migrations.AddField(
model_name='sectioncomment',
name='language_code',
field=models.CharField(blank=True, max_length=15, verbose_name='language code'),
),
migrations.RunPython(forwards_func, backwards_func),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2016-12-16 15:03
from __future__ import unicode_literals
from django.db import migrations, models
from democracy.models import SectionComment
def forwards_func(apps, schema_editor):
for comment in SectionComment.objects.all():
comment._detect_lang()
comment.save()
def backwards_func(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('democracy', '0031_remove_untranslated_fields'),
# comment.save() database operations will require a recent user model with all the fields included
('kerrokantasi', '__latest__'),
]
operations = [
migrations.AlterModelOptions(
name='sectionimage',
options={'ordering': ('ordering', 'translations__title'), 'verbose_name': 'section image', 'verbose_name_plural': 'section images'},
),
migrations.AddField(
model_name='sectioncomment',
name='language_code',
field=models.CharField(blank=True, max_length=15, verbose_name='language code'),
),
migrations.RunPython(forwards_func, backwards_func),
]
| Add literal dependency so migration 0031 won't fail if run in the wrong order | Add literal dependency so migration 0031 won't fail if run in the wrong order
| Python | mit | City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi | ---
+++
@@ -21,6 +21,8 @@
dependencies = [
('democracy', '0031_remove_untranslated_fields'),
+ # comment.save() database operations will require a recent user model with all the fields included
+ ('kerrokantasi', '__latest__'),
]
operations = [ |
cb1d4de41a7de1687041244c126c14ed76fd6959 | angular_flask/__init__.py | angular_flask/__init__.py | import os
from flask import Flask
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname('data'))
basedir_img = os.path.abspath(os.path.dirname('angular_flask'))
app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd1\x17\xd54\xe71\x03\xaf\xd8\x04\xe3\xcd\xaa\xf4\x97\x82\x1e"
#app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///' + os.path.join(basedir, 'data/posts.db')
app.config["SQLALCHEMY_DATABASE_URI"] = 'postgresql://admin:111111@localhost:5432/posts'
app.config["DEBUG"] = True
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config['UPLOAD_FOLDER'] = os.path.join(basedir_img, 'angular_flask/static/img')
import angular_flask.core
import angular_flask.models
import angular_flask.controllers
| import os
from flask import Flask
import psycopg2
import urlparse
urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse(os.environ["DATABASE_URL"])
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname('data'))
basedir_img = os.path.abspath(os.path.dirname('angular_flask'))
app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd1\x17\xd54\xe71\x03\xaf\xd8\x04\xe3\xcd\xaa\xf4\x97\x82\x1e"
#app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///' + os.path.join(basedir, 'data/posts.db')
#app.config["SQLALCHEMY_DATABASE_URI"] = 'postgresql://admin:111111@localhost:5432/posts'
app.config["DEBUG"] = True
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config['UPLOAD_FOLDER'] = os.path.join(basedir_img, 'angular_flask/static/img')
import angular_flask.core
import angular_flask.models
import angular_flask.controllers
| Connect to psql on server | Connect to psql on server
| Python | mit | Clarity-89/blog,Clarity-89/blog,Clarity-89/blog | ---
+++
@@ -1,12 +1,25 @@
import os
from flask import Flask
+import psycopg2
+import urlparse
+
+urlparse.uses_netloc.append("postgres")
+url = urlparse.urlparse(os.environ["DATABASE_URL"])
+
+conn = psycopg2.connect(
+ database=url.path[1:],
+ user=url.username,
+ password=url.password,
+ host=url.hostname,
+ port=url.port
+)
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname('data'))
basedir_img = os.path.abspath(os.path.dirname('angular_flask'))
app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd1\x17\xd54\xe71\x03\xaf\xd8\x04\xe3\xcd\xaa\xf4\x97\x82\x1e"
#app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///' + os.path.join(basedir, 'data/posts.db')
-app.config["SQLALCHEMY_DATABASE_URI"] = 'postgresql://admin:111111@localhost:5432/posts'
+#app.config["SQLALCHEMY_DATABASE_URI"] = 'postgresql://admin:111111@localhost:5432/posts'
app.config["DEBUG"] = True
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config['UPLOAD_FOLDER'] = os.path.join(basedir_img, 'angular_flask/static/img') |
17b42f9bcd4168494f529104d3d172cb0310d58a | python2.7libs/CacheManager/define.py | python2.7libs/CacheManager/define.py | # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
## Description
"""
Define file for Cache Manager Tool.
"""
#-------------------------------------------------------------------------------
## Define Cache Nodes to deal with this script.
CACHE_NODES = [
{"name":"file", "parmName":"file"},
{"name":"filecache", "parmName":"file"},
{"name":"alembic", "parmName":"fileName"},
{"name":"alembicarchive", "parmName":"fileName"},
{"name":"dopio", "parmName":"file"},
]
CHILDNODES_EXCEPTION = [
"filecache",
"dopio",
"df_alembic_import",
]
DEBUG_MODE = False
## Define Houdini Environment Varialbes. This will also be used for displaying.
ENV_TYPE = [
'-',
'HIP',
'JOB',
]
## Menu Items.
MENU_HELP = "Help"
MENU_RELOAD = "Reload"
## Listed CHACHE_NODES node has children which should be got rid of as default.
NODES_EXCEPTION = [
"light",
"hlight",
"ambient",
"indirectlight",
"arnold_light",
"cam",
]
#-------------------------------------------------------------------------------
# EOF
#-------------------------------------------------------------------------------
| # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
## Description
"""
Define file for Cache Manager Tool.
"""
#-------------------------------------------------------------------------------
## Define Cache Nodes to deal with this script.
CACHE_NODES = [
{"name":"file", "parmName":"file"},
{"name":"filecache", "parmName":"file"},
{"name":"alembic", "parmName":"fileName"},
{"name":"alembicarchive", "parmName":"fileName"},
{"name":"dopio", "parmName":"file"},
]
CHILDNODES_EXCEPTION = [
"filecache",
"dopio",
"df_alembic_import",
]
DEBUG_MODE = False
## Define Houdini Environment Varialbes. This will also be used for displaying.
ENV_TYPE = [
'-',
'HIP',
'JOB',
]
## Menu Items.
MENU_HELP = "Help"
MENU_RELOAD = "Reload"
## Listed CHACHE_NODES node has children which should be got rid of as default.
NODES_EXCEPTION = [
"light",
"hlight",
"ambient",
"indirectlight",
"arnold_light",
"cam",
"testgeometry_pighead",
"testgeometry_rubbertoy",
"testgeometry_squab",
"testgeometry_ragdoll",
]
#-------------------------------------------------------------------------------
# EOF
#-------------------------------------------------------------------------------
| Add some test geometry which includes file node. | Add some test geometry which includes file node.
| Python | mit | takavfx/Bento | ---
+++
@@ -44,6 +44,10 @@
"indirectlight",
"arnold_light",
"cam",
+ "testgeometry_pighead",
+ "testgeometry_rubbertoy",
+ "testgeometry_squab",
+ "testgeometry_ragdoll",
]
|
423e4cc4b73e7c13d0796069733ee37aaad4c2e4 | taar/recommenders/__init__.py | taar/recommenders/__init__.py | from .collaborative_recommender import CollaborativeRecommender
from .locale_recommender import LocaleRecommender
from .legacy_recommender import LegacyRecommender
from .recommendation_manager import RecommendationManager
__all__ = [
'CollaborativeRecommender',
'LegacyRecommender',
'LocaleRecommender',
'RecommendationManager',
]
| from .collaborative_recommender import CollaborativeRecommender
from .locale_recommender import LocaleRecommender
from .legacy_recommender import LegacyRecommender
from .similarity_recommender import SimilarityRecommender
from .recommendation_manager import RecommendationManager
__all__ = [
'CollaborativeRecommender',
'LegacyRecommender',
'LocaleRecommender',
'SimilarityRecommender',
'RecommendationManager',
]
| Add SimilarityRecommender to init file | Add SimilarityRecommender to init file
| Python | mpl-2.0 | maurodoglio/taar | ---
+++
@@ -1,6 +1,7 @@
from .collaborative_recommender import CollaborativeRecommender
from .locale_recommender import LocaleRecommender
from .legacy_recommender import LegacyRecommender
+from .similarity_recommender import SimilarityRecommender
from .recommendation_manager import RecommendationManager
@@ -8,5 +9,6 @@
'CollaborativeRecommender',
'LegacyRecommender',
'LocaleRecommender',
+ 'SimilarityRecommender',
'RecommendationManager',
] |
bb87078594d3a3fcdda6e26d644bc9a93dda96cd | test_component/tests/test_component_collection.py | test_component/tests/test_component_collection.py | # -*- coding: utf-8 -*-
# Copyright 2013-2017 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo.tests import common
from odoo.addons.test_component.components.components import UserTestComponent
class TestComponentCollection(common.TransactionCase):
at_install = False
post_install = True
def setUp(self):
super(TestComponentCollection, self).setUp()
self.collection = self.env['test.component.collection'].create(
{'name': 'Test'}
)
def tearDown(self):
super(TestComponentCollection, self).tearDown()
def test_component_by_name(self):
work = self.collection.work_on('res.users')
component = work.component_by_name(name='test.user.component')
self.assertEquals(UserTestComponent._name, component._name)
def test_components_usage(self):
work = self.collection.work_on('res.users')
component = work.components(usage='test1')
self.assertEquals(UserTestComponent._name, component._name)
| # -*- coding: utf-8 -*-
# Copyright 2013-2017 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo.tests import common
from odoo.addons.test_component.components.components import UserTestComponent
class TestComponentCollection(common.TransactionCase):
at_install = False
post_install = True
def setUp(self):
super(TestComponentCollection, self).setUp()
self.collection = self.env['test.component.collection'].create(
{'name': 'Test'}
)
def tearDown(self):
super(TestComponentCollection, self).tearDown()
def test_component_by_name(self):
work = self.collection.work_on('res.users')
component = work.component_by_name(name='test.user.component')
self.assertEquals(UserTestComponent._name, component._name)
def test_components_usage(self):
work = self.collection.work_on('res.users')
component = work.component(usage='test1')
self.assertEquals(UserTestComponent._name, component._name)
| Use 2 different methods for single/many lookup | Use 2 different methods for single/many lookup
the 'components' method had 2 different return types depending of the
'multi' argument.
Now we have 'component' or 'many_components' that return a Component
instance or a list of Component instances.
| Python | agpl-3.0 | OCA/connector,OCA/connector | ---
+++
@@ -27,5 +27,5 @@
def test_components_usage(self):
work = self.collection.work_on('res.users')
- component = work.components(usage='test1')
+ component = work.component(usage='test1')
self.assertEquals(UserTestComponent._name, component._name) |
a80f5bad5369ae9a7ae3ab6914d3e9e642062ec3 | odl/contrib/param_opt/test/test_param_opt.py | odl/contrib/param_opt/test/test_param_opt.py | import pytest
import odl
import odl.contrib.fom
import odl.contrib.param_opt
from odl.util.testutils import simple_fixture
space = simple_fixture('space',
[odl.rn(3),
odl.uniform_discr([0, 0], [1, 1], [9, 11]),
odl.uniform_discr(0, 1, 10)])
def test_optimal_parameters(space):
"""Tests if optimal_parameters works for some simple examples."""
fom = odl.contrib.fom.mean_squared_error
mynoise = odl.phantom.white_noise(space)
phantoms = [mynoise]
data = [mynoise]
def reconstruction(data, lam):
"""Perturbs the data by adding lam to it."""
return data + lam
result = odl.contrib.param_opt.optimal_parameters(reconstruction, fom,
phantoms, data, 1)
assert result == pytest.approx(0)
if __name__ == '__main__':
odl.util.test_file(__file__)
| import pytest
import odl
import odl.contrib.fom
import odl.contrib.param_opt
from odl.util.testutils import simple_fixture
space = simple_fixture('space',
[odl.rn(3),
odl.uniform_discr([0, 0], [1, 1], [9, 11]),
odl.uniform_discr(0, 1, 10)])
fom = simple_fixture('fom',
[odl.contrib.fom.mean_squared_error,
odl.contrib.fom.mean_absolute_error])
def test_optimal_parameters_one_parameter(space, fom):
"""Tests if optimal_parameters works for some simple examples."""
# fom = odl.contrib.fom.mean_squared_error
mynoise = odl.phantom.white_noise(space)
phantoms = [mynoise]
data = [mynoise]
def reconstruction(data, lam):
"""Perturbs the data by adding lam to it."""
return data + lam
result = odl.contrib.param_opt.optimal_parameters(reconstruction, fom,
phantoms, data, 1)
assert result == pytest.approx(0, abs=1e-4)
if __name__ == '__main__':
odl.util.test_file(__file__)
| Add fixture for FOM for test_optimal_parameters | TST: Add fixture for FOM for test_optimal_parameters
| Python | mpl-2.0 | odlgroup/odl,odlgroup/odl,kohr-h/odl,kohr-h/odl | ---
+++
@@ -9,9 +9,13 @@
odl.uniform_discr([0, 0], [1, 1], [9, 11]),
odl.uniform_discr(0, 1, 10)])
-def test_optimal_parameters(space):
+fom = simple_fixture('fom',
+ [odl.contrib.fom.mean_squared_error,
+ odl.contrib.fom.mean_absolute_error])
+
+def test_optimal_parameters_one_parameter(space, fom):
"""Tests if optimal_parameters works for some simple examples."""
- fom = odl.contrib.fom.mean_squared_error
+# fom = odl.contrib.fom.mean_squared_error
mynoise = odl.phantom.white_noise(space)
phantoms = [mynoise]
data = [mynoise]
@@ -22,7 +26,7 @@
result = odl.contrib.param_opt.optimal_parameters(reconstruction, fom,
phantoms, data, 1)
- assert result == pytest.approx(0)
+ assert result == pytest.approx(0, abs=1e-4)
if __name__ == '__main__': |
44fe9bc37b05987c4c323d3be56f69c6f5990b82 | enigma.py | enigma.py | import string
class Steckerbrett:
def __init__(self):
pass
class Umkehrwalze:
def __init__(self, wiring):
self.wiring = wiring
def encode(self, letter):
return self.wiring[string.ascii_uppercase.index(letter)]
class Walzen:
def __init__(self, notch, wiring):
assert isinstance(notch, str)
assert isinstance(wiring, str)
assert len(wiring) == len(string.ascii_uppercase)
self.notch = notch
self.wiring = wiring
def encode(self, letter):
return self.wiring[string.ascii_uppercase.index(letter)]
def encode_reverse(self, letter):
return string.ascii_uppercase[self.wiring.index(letter)]
class Enigma:
def __init__(self):
pass
def cipher(self, message):
pass | import string
class Steckerbrett:
def __init__(self):
pass
class Umkehrwalze:
def __init__(self, wiring):
self.wiring = wiring
def encode(self, letter):
return self.wiring[string.ascii_uppercase.index(letter)]
class Walzen:
def __init__(self, notch, wiring):
assert isinstance(notch, str)
assert isinstance(wiring, str)
assert len(wiring) == len(string.ascii_uppercase)
self.notch = notch
self.wiring = wiring
def encode(self, letter):
return self.wiring[string.ascii_uppercase.index(letter)]
def encode_reverse(self, letter):
return string.ascii_uppercase[self.wiring.index(letter)]
class Enigma:
def __init__(self, rotors, reflector):
# Assert that rotors is a tuple and each tuple element is a Walzen
assert isinstance(rotors, tuple)
for index in range(len(rotors)):
assert isinstance(rotors[index], Walzen)
# Assert that reflector is an Umkehrwalze
assert isinstance(reflector, Umkehrwalze)
self.rotors = rotors
self.reflector = reflector
def cipher(self, message):
pass | Initialize the machine assignments and assertions | Initialize the machine assignments and assertions
| Python | mit | ranisalt/enigma | ---
+++
@@ -31,8 +31,17 @@
class Enigma:
- def __init__(self):
- pass
+ def __init__(self, rotors, reflector):
+ # Assert that rotors is a tuple and each tuple element is a Walzen
+ assert isinstance(rotors, tuple)
+ for index in range(len(rotors)):
+ assert isinstance(rotors[index], Walzen)
+
+ # Assert that reflector is an Umkehrwalze
+ assert isinstance(reflector, Umkehrwalze)
+
+ self.rotors = rotors
+ self.reflector = reflector
def cipher(self, message):
pass |
3d8bca4c8f5065342dd2f4c140cc792b2e2d94a1 | remo/remozilla/admin.py | remo/remozilla/admin.py | from django.contrib import admin
from django.utils.encoding import smart_text
from import_export.admin import ExportMixin
from remo.remozilla.models import Bug, Status
def encode_bugzilla_strings(modeladmin, request, queryset):
for obj in queryset:
fields = ['component', 'summary', 'whiteboard', 'status', 'resolution', 'first_comment']
for field in fields:
value = smart_text(getattr(obj, field))
setattr(obj, field, value)
obj.save()
encode_bugzilla_strings.short_description = 'Encode bugzilla strings'
class BugAdmin(ExportMixin, admin.ModelAdmin):
"""Bug Admin."""
list_display = ('__unicode__', 'summary', 'status', 'resolution',
'bug_last_change_time',)
list_filter = ('status', 'resolution', 'council_vote_requested',)
search_fields = ('bug_id', 'summary', 'id',)
actions = [encode_bugzilla_strings]
admin.site.register(Bug, BugAdmin)
admin.site.register(Status)
| from django.contrib import admin
from django.utils.encoding import smart_text
from import_export.admin import ExportMixin
from remo.remozilla.models import Bug, Status
def encode_bugzilla_strings(modeladmin, request, queryset):
for obj in queryset:
kwargs = {}
fields = ['component', 'summary', 'whiteboard', 'status', 'resolution', 'first_comment']
for field in fields:
kwargs[field] = smart_text(getattr(obj, field))
Bug.objects.filter(pk=obj.id).update(**kwargs)
encode_bugzilla_strings.short_description = 'Encode bugzilla strings'
class BugAdmin(ExportMixin, admin.ModelAdmin):
"""Bug Admin."""
list_display = ('__unicode__', 'summary', 'status', 'resolution',
'bug_last_change_time',)
list_filter = ('status', 'resolution', 'council_vote_requested',)
search_fields = ('bug_id', 'summary', 'id',)
actions = [encode_bugzilla_strings]
admin.site.register(Bug, BugAdmin)
admin.site.register(Status)
| Update instead of save when normalizing bug fields. | Update instead of save when normalizing bug fields.
| Python | bsd-3-clause | mozilla/remo,tsmrachel/remo,flamingspaz/remo,tsmrachel/remo,akatsoulas/remo,tsmrachel/remo,mozilla/remo,mozilla/remo,flamingspaz/remo,akatsoulas/remo,akatsoulas/remo,Mte90/remo,akatsoulas/remo,tsmrachel/remo,flamingspaz/remo,mozilla/remo,Mte90/remo,Mte90/remo,flamingspaz/remo,Mte90/remo | ---
+++
@@ -8,11 +8,11 @@
def encode_bugzilla_strings(modeladmin, request, queryset):
for obj in queryset:
+ kwargs = {}
fields = ['component', 'summary', 'whiteboard', 'status', 'resolution', 'first_comment']
for field in fields:
- value = smart_text(getattr(obj, field))
- setattr(obj, field, value)
- obj.save()
+ kwargs[field] = smart_text(getattr(obj, field))
+ Bug.objects.filter(pk=obj.id).update(**kwargs)
encode_bugzilla_strings.short_description = 'Encode bugzilla strings'
|
0f68fdb37f28f01f21ca42d3bf509dc6138fb157 | examples/requirements_check.py | examples/requirements_check.py | """Example of checking the requirements of bibtext and biblatex."""
from __future__ import print_function
import bibpy
import os
def format_requirements_check(required, optional):
s = ""
if required:
s = "required field(s) " + ", ".join(map(str, required))
if optional:
if required:
s += " and "
temp = ["/".join(map(str, opt)) for opt in optional]
s += "optional field(s) " + ", ".join(temp)
return s
def get_path_for(path):
return os.path.join(os.path.dirname(os.path.abspath(__file__)), path)
if __name__ == '__main__':
filename = get_path_for('../tests/data/biblatex_missing_requirements.bib')
entries = bibpy.read_file(filename, format='biblatex').entries
# Collect all results for which a requirements check failed into a list of
# pairs. There is also bibpy.requirements.check for checking individual
# entries
checked = bibpy.requirements.collect(entries, format='biblatex')
print("* Using bibpy.requirements.collect:")
for (entry, (required, optional)) in checked:
if required or optional:
# Either a missing required or optional field for this entry
print("{0}:{1} is missing {2}"
.format(entry.entry_type, entry.entry_key,
format_requirements_check(required, optional)))
# Requirements checks can also be performed on individual entries.
# Use Entry.validate(format) to throw a RequiredFieldError instead of
# returning a bool
entry = entries[2]
print()
print("* {0} for {1}:{2} = {3}".format("entry.valid('biblatex')",
entry.entry_type,
entry.entry_key,
entry.valid('biblatex')))
| Complete example of checking requirements | Complete example of checking requirements
| Python | mit | MisanthropicBit/bibpy,MisanthropicBit/bibpy | ---
+++
@@ -0,0 +1,54 @@
+"""Example of checking the requirements of bibtext and biblatex."""
+
+from __future__ import print_function
+
+import bibpy
+import os
+
+
+def format_requirements_check(required, optional):
+ s = ""
+
+ if required:
+ s = "required field(s) " + ", ".join(map(str, required))
+
+ if optional:
+ if required:
+ s += " and "
+
+ temp = ["/".join(map(str, opt)) for opt in optional]
+ s += "optional field(s) " + ", ".join(temp)
+
+ return s
+
+
+def get_path_for(path):
+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), path)
+
+
+if __name__ == '__main__':
+ filename = get_path_for('../tests/data/biblatex_missing_requirements.bib')
+ entries = bibpy.read_file(filename, format='biblatex').entries
+
+ # Collect all results for which a requirements check failed into a list of
+ # pairs. There is also bibpy.requirements.check for checking individual
+ # entries
+ checked = bibpy.requirements.collect(entries, format='biblatex')
+
+ print("* Using bibpy.requirements.collect:")
+ for (entry, (required, optional)) in checked:
+ if required or optional:
+ # Either a missing required or optional field for this entry
+ print("{0}:{1} is missing {2}"
+ .format(entry.entry_type, entry.entry_key,
+ format_requirements_check(required, optional)))
+
+ # Requirements checks can also be performed on individual entries.
+ # Use Entry.validate(format) to throw a RequiredFieldError instead of
+ # returning a bool
+ entry = entries[2]
+ print()
+ print("* {0} for {1}:{2} = {3}".format("entry.valid('biblatex')",
+ entry.entry_type,
+ entry.entry_key,
+ entry.valid('biblatex'))) | |
d55b4b0cd7e160be687129482ecd72792b5c6d81 | eventkit/tests/settings.py | eventkit/tests/settings.py | """
Test settings for ``eventkit`` app.
"""
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django_nose',
'eventkit',
'eventkit.tests',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'eventkit.tests.urls'
SECRET_KEY = 'secret-key'
STATIC_URL = '/static/'
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' # Default: django.test.runner.DiscoverRunner
TIME_ZONE = 'Australia/Sydney' # Default: America/Chicago
USE_TZ = True # Default: False
# DYNAMIC FIXTURES ############################################################
DDF_FILL_NULLABLE_FIELDS = False
| """
Test settings for ``eventkit`` app.
"""
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django_nose',
'eventkit',
'eventkit.tests',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'eventkit.tests.urls'
SECRET_KEY = 'secret-key'
STATIC_URL = '/static/'
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' # Default: django.test.runner.DiscoverRunner
TIME_ZONE = 'Australia/Sydney' # Default: America/Chicago
USE_TZ = True # Default: False
# DYNAMIC FIXTURES ############################################################
DDF_FILL_NULLABLE_FIELDS = False
| Create test database in memory. | Create test database in memory.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/icekit-events,ic-labs/django-icekit,ic-labs/icekit-events,ic-labs/icekit-events | ---
+++
@@ -5,7 +5,7 @@
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': 'db.sqlite3',
+ 'NAME': ':memory:',
}
}
|
387fd69d034260ceb389c33d0f561967fd902db0 | datagrid_gtk3/tests/utils/test_transformations.py | datagrid_gtk3/tests/utils/test_transformations.py | """Data transformation utilities test cases."""
import unittest
from datagrid_gtk3.utils.transformations import degree_decimal_str_transform
class DegreeDecimalStrTransformTest(unittest.TestCase):
"""Degree decimal string transformation test case."""
def test_no_basestring(self):
"""AssertionError raised when no basestring value is passed."""
self.assertRaises(AssertionError, degree_decimal_str_transform, 0)
self.assertRaises(AssertionError, degree_decimal_str_transform, 1.23)
self.assertRaises(AssertionError, degree_decimal_str_transform, True)
def test_no_digit(self):
"""AssertionError raised when other characters than digits."""
self.assertRaises(AssertionError, degree_decimal_str_transform, '.')
self.assertRaises(AssertionError, degree_decimal_str_transform, '+')
self.assertRaises(AssertionError, degree_decimal_str_transform, '-')
def test_length(self):
"""AssertionError when more characters than expected passed."""
self.assertRaises(
AssertionError, degree_decimal_str_transform, '123456789')
def test_point_insertion(self):
"""Decimal point is inserted in the expected location."""
self.assertEqual(
degree_decimal_str_transform('12345678'),
12.345678,
)
self.assertEqual(
degree_decimal_str_transform('123456'),
0.123456,
)
| """Data transformation utilities test cases."""
import unittest
from datagrid_gtk3.utils.transformations import degree_decimal_str_transform
class DegreeDecimalStrTransformTest(unittest.TestCase):
"""Degree decimal string transformation test case."""
def test_no_basestring(self):
"""AssertionError raised when no basestring value is passed."""
self.assertRaises(AssertionError, degree_decimal_str_transform, 0)
self.assertRaises(AssertionError, degree_decimal_str_transform, 1.23)
self.assertRaises(AssertionError, degree_decimal_str_transform, True)
def test_no_digit(self):
"""AssertionError raised when other characters than digits."""
self.assertRaises(AssertionError, degree_decimal_str_transform, '.')
self.assertRaises(AssertionError, degree_decimal_str_transform, '+')
self.assertRaises(AssertionError, degree_decimal_str_transform, '-')
def test_length(self):
"""AssertionError when more characters than expected passed."""
self.assertRaises(
AssertionError, degree_decimal_str_transform, '123456789')
def test_point_insertion(self):
"""Decimal point is inserted in the expected location."""
self.assertEqual(
degree_decimal_str_transform('12345678'),
'12.345678',
)
self.assertEqual(
degree_decimal_str_transform('123456'),
'0.123456',
)
| Update test results using new return type | Update test results using new return type
| Python | mit | nowsecure/datagrid-gtk3,jcollado/datagrid-gtk3 | ---
+++
@@ -30,9 +30,9 @@
"""Decimal point is inserted in the expected location."""
self.assertEqual(
degree_decimal_str_transform('12345678'),
- 12.345678,
+ '12.345678',
)
self.assertEqual(
degree_decimal_str_transform('123456'),
- 0.123456,
+ '0.123456',
) |
722c3dad6d0a0cc34955ab4a5cfafb90a7cf0e64 | scaffold/twork_app/twork_app/web/action/not_found.py | scaffold/twork_app/twork_app/web/action/not_found.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''NotFoundHandler
'''
from tornado.web import HTTPError
from twork_app.web.action.base import BaseHandler
class NotFoundHandler(BaseHandler):
'''NotFoundHandler, RESTFUL SUPPORTED.
'''
ST_ITEM = 'NOT_FOUND'
def post(self, *args, **kwargs):
raise HTTPError(404)
def delete(self, *args, **kwargs):
raise HTTPError(404)
def get(self, *args, **kwargs):
raise HTTPError(404)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''NotFoundHandler
'''
from tornado.web import HTTPError
from twork_app.web.action.base import BaseHandler
class NotFoundHandler(BaseHandler):
'''NotFoundHandler, RESTFUL SUPPORTED.
'''
ST_ITEM = 'NOT_FOUND'
def post(self, *args, **kwargs):
raise HTTPError(404)
def put(self, *args, **kwargs):
raise HTTPError(404)
def delete(self, *args, **kwargs):
raise HTTPError(404)
def get(self, *args, **kwargs):
raise HTTPError(404)
| Rewrite put method for not found handler | Rewrite put method for not found handler
| Python | apache-2.0 | bufferx/twork,bufferx/twork | ---
+++
@@ -19,6 +19,9 @@
def post(self, *args, **kwargs):
raise HTTPError(404)
+ def put(self, *args, **kwargs):
+ raise HTTPError(404)
+
def delete(self, *args, **kwargs):
raise HTTPError(404)
|
a7946f996d618ad2491f36655f000c513017193c | permamodel/tests/test_package_directories.py | permamodel/tests/test_package_directories.py | """Tests directories set in the permamodel package definition file."""
import os
from nose.tools import assert_true
from .. import (permamodel_directory, data_directory,
examples_directory, tests_directory)
def test_permamodel_directory_is_set():
assert(permamodel_directory is not None)
def test_data_directory_is_set():
assert(data_directory is not None)
def test_examples_directory_is_set():
assert(examples_directory is not None)
def test_tests_directory_is_set():
assert(tests_directory is not None)
def test_permamodel_directory_exists():
assert_true(os.path.isdir(permamodel_directory))
def test_data_directory_exists():
assert_true(os.path.isdir(data_directory))
def test_examples_directory_exists():
assert_true(os.path.isdir(examples_directory))
def test_tests_directory_exists():
assert_true(os.path.isdir(tests_directory))
| """Tests directories set in the permamodel package definition file."""
import os
from .. import data_directory, examples_directory, permamodel_directory, tests_directory
def test_permamodel_directory_is_set():
assert permamodel_directory is not None
def test_data_directory_is_set():
assert data_directory is not None
def test_examples_directory_is_set():
assert examples_directory is not None
def test_tests_directory_is_set():
assert tests_directory is not None
def test_permamodel_directory_exists():
assert os.path.isdir(permamodel_directory)
def test_data_directory_exists():
assert os.path.isdir(data_directory)
def test_examples_directory_exists():
assert os.path.isdir(examples_directory)
def test_tests_directory_exists():
assert os.path.isdir(tests_directory)
| Remove assert_ functions from nose. | Remove assert_ functions from nose.
| Python | mit | permamodel/permamodel,permamodel/permamodel | ---
+++
@@ -1,38 +1,37 @@
"""Tests directories set in the permamodel package definition file."""
import os
-from nose.tools import assert_true
-from .. import (permamodel_directory, data_directory,
- examples_directory, tests_directory)
+
+from .. import data_directory, examples_directory, permamodel_directory, tests_directory
def test_permamodel_directory_is_set():
- assert(permamodel_directory is not None)
+ assert permamodel_directory is not None
def test_data_directory_is_set():
- assert(data_directory is not None)
+ assert data_directory is not None
def test_examples_directory_is_set():
- assert(examples_directory is not None)
+ assert examples_directory is not None
def test_tests_directory_is_set():
- assert(tests_directory is not None)
+ assert tests_directory is not None
def test_permamodel_directory_exists():
- assert_true(os.path.isdir(permamodel_directory))
+ assert os.path.isdir(permamodel_directory)
def test_data_directory_exists():
- assert_true(os.path.isdir(data_directory))
+ assert os.path.isdir(data_directory)
def test_examples_directory_exists():
- assert_true(os.path.isdir(examples_directory))
+ assert os.path.isdir(examples_directory)
def test_tests_directory_exists():
- assert_true(os.path.isdir(tests_directory))
+ assert os.path.isdir(tests_directory) |
8061b8dd4e836e6af16dd93b332f8cea6b55433c | exgrep.py | exgrep.py | #!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
Usage:
exgrep TERM [options] EXCEL_FILE...
Options:
TERM The term to grep for. Can be any valid (python) regular expression.
EXCEL_FILE The list of files to search through
-o Only output the matched part
"""
import re
from docopt import docopt
import xlrd
__author__ = 'peter'
def main():
args = docopt(__doc__)
p = re.compile(args['TERM'], re.UNICODE)
for f in args['EXCEL_FILE']:
workbook = xlrd.open_workbook(f)
sheet = workbook.sheet_by_index(0)
for rownum in range(sheet.nrows):
for v in sheet.row_values(rownum):
s = p.search(str(v))
if s:
if args['-o']:
print(s.group(0))
else:
print(sheet.row_values(rownum))
if __name__ == '__main__':
main() | #!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
Usage:
exgrep TERM [options] EXCEL_FILE...
Options:
TERM The term to grep for. Can be any valid (python) regular expression.
EXCEL_FILE The list of files to search through
-c COL Only search in the column specified by COL.
-o Only output the matched part
"""
import re
from docopt import docopt
import xlrd
__author__ = 'peter'
def main():
args = docopt(__doc__)
p = re.compile(args['TERM'], re.UNICODE)
for f in args['EXCEL_FILE']:
workbook = xlrd.open_workbook(f)
sheet = workbook.sheet_by_index(0)
for rownum in range(sheet.nrows):
for idx, v in enumerate(sheet.row_values(rownum)):
if args['-c'] and idx != int(args['-c']):
continue
s = p.search(str(v))
if s:
if args['-o']:
print(s.group(0))
else:
print(sheet.row_values(rownum))
if __name__ == '__main__':
main() | Add support for only searching specified column | Add support for only searching specified column
| Python | mit | Sakartu/excel-toolkit | ---
+++
@@ -7,6 +7,7 @@
Options:
TERM The term to grep for. Can be any valid (python) regular expression.
EXCEL_FILE The list of files to search through
+-c COL Only search in the column specified by COL.
-o Only output the matched part
"""
import re
@@ -24,7 +25,9 @@
workbook = xlrd.open_workbook(f)
sheet = workbook.sheet_by_index(0)
for rownum in range(sheet.nrows):
- for v in sheet.row_values(rownum):
+ for idx, v in enumerate(sheet.row_values(rownum)):
+ if args['-c'] and idx != int(args['-c']):
+ continue
s = p.search(str(v))
if s:
if args['-o']: |
5d91948e11400253f161be489bb8c9bf13b7ee35 | source/main.py | source/main.py | """updates subreddit css with compiled sass"""
import subprocess
import praw
def css() -> str:
"""compiles sass and returns css"""
res: subprocess.CompletedProcess = subprocess.run(
"sass index.scss --style compressed --quiet", stdout=subprocess.PIPE
)
return res.stdout
def update(reddit: praw.Reddit, style: str) -> None:
"""update subreddit stylesheet"""
sub: praw.models.Subreddit = reddit.subreddit("neoliberal")
sub.wiki("config/stylesheet").update(style)
return
def main() -> None:
"""main function"""
reddit: praw.Reddit = praw.Reddit()
style: str = css()
update(reddit, style)
return
if __name__ == '__main__':
main()
| """updates subreddit css with compiled sass"""
import subprocess
import time
import praw
def css() -> str:
"""compiles sass and returns css"""
res: subprocess.CompletedProcess = subprocess.run(
"sass index.scss --style compressed --quiet", stdout=subprocess.PIPE
)
return res.stdout
def uid() -> str:
"""return date and time"""
return "Subreddit upload on {}".format(time.strftime("%c"))
def update(reddit: praw.Reddit, style: str) -> None:
"""update subreddit stylesheet"""
reddit.subreddit("neoliberal").stylesheet.update(style, reason=uid())
return
def main() -> None:
"""main function"""
reddit: praw.Reddit = praw.Reddit()
style: str = css()
update(reddit, style)
return
if __name__ == '__main__':
main()
| Use direct subreddit stylesheet update function | Use direct subreddit stylesheet update function
Instead of updating the wiki, uses the praw-defined function.
Also adds an UID function for subreddit reason
| Python | mit | neoliberal/css-updater | ---
+++
@@ -1,5 +1,7 @@
"""updates subreddit css with compiled sass"""
import subprocess
+import time
+
import praw
def css() -> str:
@@ -9,10 +11,13 @@
)
return res.stdout
+def uid() -> str:
+ """return date and time"""
+ return "Subreddit upload on {}".format(time.strftime("%c"))
+
def update(reddit: praw.Reddit, style: str) -> None:
"""update subreddit stylesheet"""
- sub: praw.models.Subreddit = reddit.subreddit("neoliberal")
- sub.wiki("config/stylesheet").update(style)
+ reddit.subreddit("neoliberal").stylesheet.update(style, reason=uid())
return
def main() -> None: |
38b2bccc4146226d698f5abd1bed1107fe3bbe68 | canon.py | canon.py | from melopy import *
m = Melopy('canon', 50)
melody = []
for start in ['d4', 'a3', 'b3m', 'f#3m', 'g3', 'd3', 'g3', 'a3']:
if start.endswith('m'):
scale = generate_minor_triad(start[:-1])
else:
scale = generate_major_triad(start)
for note in scale:
melody.append(note)
m.add_melody(melody, 0.2)
m.add_note('e4', 0.2)
m.render() | from melopy import *
m = Melopy('canon', 50)
melody = []
for start in ['d4', 'a3', 'bm3', 'f#m3', 'g3', 'd3', 'g3', 'a3']:
if start.endswith('m'):
scale = m.generate_minor_triad(start[:-1])
else:
scale = m.generate_major_triad(start)
for note in scale:
melody.append(note)
m.add_melody(melody, 0.2)
m.add_note('e4', 0.2)
m.render() | Revert "Added "add_rest(length)" method. Changed iterate and generate functions to be outside of the class." | Revert "Added "add_rest(length)" method. Changed iterate and generate functions to be outside of the class."
This reverts commit 672069e8f8f7ded4537362707378f32cccde1ae6.
| Python | mit | juliowaissman/Melopy,jdan/Melopy | ---
+++
@@ -3,15 +3,15 @@
m = Melopy('canon', 50)
melody = []
-for start in ['d4', 'a3', 'b3m', 'f#3m', 'g3', 'd3', 'g3', 'a3']:
+for start in ['d4', 'a3', 'bm3', 'f#m3', 'g3', 'd3', 'g3', 'a3']:
if start.endswith('m'):
- scale = generate_minor_triad(start[:-1])
+ scale = m.generate_minor_triad(start[:-1])
else:
- scale = generate_major_triad(start)
+ scale = m.generate_major_triad(start)
for note in scale:
melody.append(note)
-
+
m.add_melody(melody, 0.2)
m.add_note('e4', 0.2)
m.render() |
768ba3ef82df95e308c1431d17e7173e4ecd2861 | vumi/blinkenlights/__init__.py | vumi/blinkenlights/__init__.py | """Vumi monitoring and control framework."""
from vumi.blinkenlights.metrics_workers import (MetricTimeBucket,
MetricAggregator,
GraphiteMetricsCollector)
__all__ = ["MetricTimeBucket", "MetricAggregator", "GraphiteMetricsCollector"]
| Add blinkenlights metrics workers to vumi.blinkenlights package namespace (for convenience). | Add blinkenlights metrics workers to vumi.blinkenlights package namespace (for convenience).
| Python | bsd-3-clause | vishwaprakashmishra/xmatrix,TouK/vumi,TouK/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,harrissoerja/vumi,harrissoerja/vumi,harrissoerja/vumi | ---
+++
@@ -0,0 +1,7 @@
+"""Vumi monitoring and control framework."""
+
+from vumi.blinkenlights.metrics_workers import (MetricTimeBucket,
+ MetricAggregator,
+ GraphiteMetricsCollector)
+
+__all__ = ["MetricTimeBucket", "MetricAggregator", "GraphiteMetricsCollector"] | |
6bd7891e0cfcedc1a5d0813b644b5d6bb941045a | gaphor/abc.py | gaphor/abc.py | from __future__ import annotations
import abc
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from gaphor.core.modeling import Element
from gaphor.diagram.diagramtoolbox import ToolboxDefinition
class Service(metaclass=abc.ABCMeta):
"""Base interface for all services in Gaphor."""
@abc.abstractmethod
def shutdown(self) -> None:
"""Shutdown the services, free resources."""
class ActionProvider(metaclass=abc.ABCMeta):
"""An action provider is a special service that provides actions (see
gaphor/action.py)."""
class ModelingLanguage(metaclass=abc.ABCMeta):
"""A model provider is a special service that provides an entrypoint to a
model implementation, such as UML, SysML, RAAML."""
@abc.abstractproperty
def name(self) -> str:
"""Human readable name of the model."""
@abc.abstractproperty
def toolbox_definition(self) -> ToolboxDefinition:
"""Get structure for the toolbox."""
@abc.abstractmethod
def lookup_element(self, name: str) -> type[Element] | None:
"""Look up a model element type (class) by name."""
| from __future__ import annotations
from abc import ABCMeta, abstractmethod
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from gaphor.core.modeling import Element
from gaphor.diagram.diagramtoolbox import ToolboxDefinition
class Service(metaclass=ABCMeta):
"""Base interface for all services in Gaphor."""
@abstractmethod
def shutdown(self) -> None:
"""Shutdown the services, free resources."""
class ActionProvider(metaclass=ABCMeta):
"""An action provider is a special service that provides actions (see
gaphor/action.py)."""
class ModelingLanguage(metaclass=ABCMeta):
"""A model provider is a special service that provides an entrypoint to a
model implementation, such as UML, SysML, RAAML."""
@property
@abstractmethod
def name(self) -> str:
"""Human readable name of the model."""
@property
@abstractmethod
def toolbox_definition(self) -> ToolboxDefinition:
"""Get structure for the toolbox."""
@abstractmethod
def lookup_element(self, name: str) -> type[Element] | None:
"""Look up a model element type (class) by name."""
| Remove use of deprecated abstractproperty | Remove use of deprecated abstractproperty
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor | ---
+++
@@ -1,6 +1,6 @@
from __future__ import annotations
-import abc
+from abc import ABCMeta, abstractmethod
from typing import TYPE_CHECKING
if TYPE_CHECKING:
@@ -8,31 +8,33 @@
from gaphor.diagram.diagramtoolbox import ToolboxDefinition
-class Service(metaclass=abc.ABCMeta):
+class Service(metaclass=ABCMeta):
"""Base interface for all services in Gaphor."""
- @abc.abstractmethod
+ @abstractmethod
def shutdown(self) -> None:
"""Shutdown the services, free resources."""
-class ActionProvider(metaclass=abc.ABCMeta):
+class ActionProvider(metaclass=ABCMeta):
"""An action provider is a special service that provides actions (see
gaphor/action.py)."""
-class ModelingLanguage(metaclass=abc.ABCMeta):
+class ModelingLanguage(metaclass=ABCMeta):
"""A model provider is a special service that provides an entrypoint to a
model implementation, such as UML, SysML, RAAML."""
- @abc.abstractproperty
+ @property
+ @abstractmethod
def name(self) -> str:
"""Human readable name of the model."""
- @abc.abstractproperty
+ @property
+ @abstractmethod
def toolbox_definition(self) -> ToolboxDefinition:
"""Get structure for the toolbox."""
- @abc.abstractmethod
+ @abstractmethod
def lookup_element(self, name: str) -> type[Element] | None:
"""Look up a model element type (class) by name.""" |
880b00a92ac86bb9a5d30392bafb2c019dab7b74 | test/unit/test_api_objects.py | test/unit/test_api_objects.py | """
Test api_objects.py
"""
import unittest
from fmcapi import api_objects
class TestApiObjects(unittest.TestCase):
def test_ip_host_required_for_put(self):
self.assertEqual(api_objects.IPHost.REQUIRED_FOR_PUT, ['id', 'name', 'value'])
| """
Test api_objects.py
"""
import mock
import unittest
from fmcapi import api_objects
class TestApiObjects(unittest.TestCase):
def test_ip_host_required_for_put(self):
self.assertEqual(api_objects.IPHost.REQUIRED_FOR_PUT, ['id', 'name', 'value'])
@mock.patch('fmcapi.api_objects.APIClassTemplate.parse_kwargs')
@mock.patch('fmcapi.api_objects.APIClassTemplate.valid_for_delete')
def test_api_class_template_delete_on_bad_response(self, mock_valid, *_):
"""
If send_to_api returns a None (because the API call failed) then do not process the response and just return the None
"""
mock_valid.return_value = True
mock_fmc = mock.Mock()
mock_fmc.send_to_api.return_value = None
api = api_objects.APIClassTemplate(fmc=mock_fmc)
api.id = 'id'
self.assertIsNone(api.delete())
| Add unit test to test for bad response on api delete | Add unit test to test for bad response on api delete
| Python | bsd-3-clause | daxm/fmcapi,daxm/fmcapi | ---
+++
@@ -1,6 +1,7 @@
"""
Test api_objects.py
"""
+import mock
import unittest
from fmcapi import api_objects
@@ -11,3 +12,16 @@
def test_ip_host_required_for_put(self):
self.assertEqual(api_objects.IPHost.REQUIRED_FOR_PUT, ['id', 'name', 'value'])
+ @mock.patch('fmcapi.api_objects.APIClassTemplate.parse_kwargs')
+ @mock.patch('fmcapi.api_objects.APIClassTemplate.valid_for_delete')
+ def test_api_class_template_delete_on_bad_response(self, mock_valid, *_):
+ """
+ If send_to_api returns a None (because the API call failed) then do not process the response and just return the None
+ """
+ mock_valid.return_value = True
+ mock_fmc = mock.Mock()
+ mock_fmc.send_to_api.return_value = None
+ api = api_objects.APIClassTemplate(fmc=mock_fmc)
+ api.id = 'id'
+ self.assertIsNone(api.delete())
+ |
d6ed0e5925e0793bf4fc84b09e709b3a0d907f58 | lc0525_contiguous_array.py | lc0525_contiguous_array.py | """Leetcode 525. Contiguous Array
Medium
URL: https://leetcode.com/problems/contiguous-array/
Given a binary array, find the maximum length of a contiguous subarray
with equal number of 0 and 1.
Example 1:
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number
of 0 and 1.
Example 2:
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with
equal number of 0 and 1.
Note: The length of the given binary array will not exceed 50,000.
"""
class Solution(object):
def findMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
pass
def main():
pass
if __name__ == '__main__':
main()
| """Leetcode 525. Contiguous Array
Medium
URL: https://leetcode.com/problems/contiguous-array/
Given a binary array, find the maximum length of a contiguous subarray
with equal number of 0 and 1.
Example 1:
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number
of 0 and 1.
Example 2:
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with
equal number of 0 and 1.
Note: The length of the given binary array will not exceed 50,000.
"""
class SolutionDiffsumIdxDict(object):
def findMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
Time complexity: O(n).
Space complexity: O(n).
"""
# Edge case.
if len(nums) <= 1:
return 0
max_len = 0
# Create a dict:diffsum->idx.
diffsum_idx_d = {0: -1}
diffsum = 0
for idx, num in enumerate(nums):
# Get diff by converting 0 to -1 and 1 to 1.
diffsum += 2 * num - 1
# Check if diffsum exists, update max_len.
if diffsum in diffsum_idx_d:
max_len = max(max_len, idx - diffsum_idx_d[diffsum])
else:
diffsum_idx_d[diffsum] = idx
return max_len
def main():
# Output: 2
nums = [0,1]
print SolutionDiffsumIdxDict().findMaxLength(nums)
# Output: 2
nums = [0,1,0]
print SolutionDiffsumIdxDict().findMaxLength(nums)
if __name__ == '__main__':
main()
| Complete diffsum idx dict sol w/ time/space complexity | Complete diffsum idx dict sol w/ time/space complexity
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -22,17 +22,45 @@
"""
-class Solution(object):
+class SolutionDiffsumIdxDict(object):
def findMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
+
+ Time complexity: O(n).
+ Space complexity: O(n).
"""
- pass
+ # Edge case.
+ if len(nums) <= 1:
+ return 0
+
+ max_len = 0
+
+ # Create a dict:diffsum->idx.
+ diffsum_idx_d = {0: -1}
+ diffsum = 0
+ for idx, num in enumerate(nums):
+ # Get diff by converting 0 to -1 and 1 to 1.
+ diffsum += 2 * num - 1
+
+ # Check if diffsum exists, update max_len.
+ if diffsum in diffsum_idx_d:
+ max_len = max(max_len, idx - diffsum_idx_d[diffsum])
+ else:
+ diffsum_idx_d[diffsum] = idx
+
+ return max_len
def main():
- pass
+ # Output: 2
+ nums = [0,1]
+ print SolutionDiffsumIdxDict().findMaxLength(nums)
+
+ # Output: 2
+ nums = [0,1,0]
+ print SolutionDiffsumIdxDict().findMaxLength(nums)
if __name__ == '__main__': |
7b798d923c5a5af37e9f4c2d92881e907f2c0c74 | python/testData/inspections/PyUnresolvedReferencesInspection/ignoredUnresolvedReferenceInUnionType.py | python/testData/inspections/PyUnresolvedReferencesInspection/ignoredUnresolvedReferenceInUnionType.py | class A:
pass
a = A()
print(a.f<caret>oo)
x = A() or None
print(x.foo) | class A:
pass
a = A()
print(a.f<caret>oo)
def func(c):
x = A() if c else None
return x.foo | Use more reliable test data as pointed in IDEA-COMMUNITY-CR-936 | Use more reliable test data as pointed in IDEA-COMMUNITY-CR-936
| Python | apache-2.0 | asedunov/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,caot/intellij-community,diorcety/intellij-community,asedunov/intellij-community,supersven/intellij-community,signed/intellij-community,signed/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,caot/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,samthor/intellij-community,asedunov/intellij-community,retomerz/intellij-community,robovm/robovm-studio,robovm/robovm-studio,hurricup/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,semonte/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,signed/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,fitermay/intellij-community,dslomov/intellij-community,robovm/robovm-studio,ibinti/intellij-community,ibinti/intellij-community,fitermay/intellij-community,allotria/intellij-community,ryano144/intellij-community,diorcety/intellij-community,caot/intellij-community,Distrotech/intellij-community,slisson/intellij-community,slisson/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,samthor/intellij-community,allotria/intellij-community,da1z/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,caot/intellij-community,vladmm/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,xfournet/intellij-community,dslomov/intellij-community,clumsy/intellij-community,amith01994/intellij-community,fitermay/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,da1z/intellij-community,tmpgit/intellij-community,da1z/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,semonte/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,izonder/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,da1z/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,adedayo/intellij-community,retomerz/intellij-community,allotria/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,semonte/intellij-community,petteyg/intellij-community,retomerz/intellij-community,robovm/robovm-studio,fnouama/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,da1z/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,ryano144/intellij-community,supersven/intellij-community,dslomov/intellij-community,caot/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,izonder/intellij-community,robovm/robovm-studio,ibinti/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,caot/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,semonte/intellij-community,fitermay/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,caot/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,holmes/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,apixandru/intellij-community,fitermay/intellij-community,asedunov/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,semonte/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,retomerz/intellij-community,caot/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,ibinti/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,fnouama/intellij-community,fitermay/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,xfournet/intellij-community,clumsy/intellij-community,diorcety/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,diorcety/intellij-community,izonder/intellij-community,ryano144/intellij-community,holmes/intellij-community,samthor/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,signed/intellij-community,fnouama/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,supersven/intellij-community,youdonghai/intellij-community,signed/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,semonte/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,apixandru/intellij-community,fitermay/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,ibinti/intellij-community,ibinti/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,ibinti/intellij-community,fnouama/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,slisson/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,allotria/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,ibinti/intellij-community,hurricup/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,signed/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,retomerz/intellij-community,fnouama/intellij-community,samthor/intellij-community,holmes/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,izonder/intellij-community,akosyakov/intellij-community,allotria/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,allotria/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,jagguli/intellij-community,amith01994/intellij-community,signed/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,kool79/intellij-community,semonte/intellij-community,clumsy/intellij-community,slisson/intellij-community,dslomov/intellij-community,vladmm/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,samthor/intellij-community,FHannes/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,xfournet/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,fitermay/intellij-community,apixandru/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,signed/intellij-community,apixandru/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,FHannes/intellij-community,samthor/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,holmes/intellij-community,fnouama/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,hurricup/intellij-community,vladmm/intellij-community,slisson/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,signed/intellij-community,kdwink/intellij-community,jagguli/intellij-community,petteyg/intellij-community,dslomov/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,adedayo/intellij-community,caot/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,FHannes/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,allotria/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,allotria/intellij-community,izonder/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,signed/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,allotria/intellij-community,blademainer/intellij-community,supersven/intellij-community,adedayo/intellij-community,kool79/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,ibinti/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,semonte/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,slisson/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,xfournet/intellij-community,vladmm/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,semonte/intellij-community,FHannes/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,apixandru/intellij-community,petteyg/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,samthor/intellij-community,caot/intellij-community,gnuhub/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,da1z/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,holmes/intellij-community,allotria/intellij-community,clumsy/intellij-community,hurricup/intellij-community | ---
+++
@@ -4,5 +4,6 @@
a = A()
print(a.f<caret>oo)
-x = A() or None
-print(x.foo)
+def func(c):
+ x = A() if c else None
+ return x.foo |
d0a2f82686158f6610ec5f57f586598be7569c6d | students/psbriant/final_project/clean_data.py | students/psbriant/final_project/clean_data.py | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
print(data["Date Text"].head())
first_date = data["Date Text"].values[0]
# print(first_date)
# datetime.strptime(first_date, "%Y-%m-%d")
# datetime(2012, 3, 10, 0, 0)
data.date = data.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
# print(data.date.head())
data.index = data.date
# print(data)
# print(data.ix[datetime(2012, 8, 19)])
# Remove date column
data = data.drop(["date"], axis=1)
# print(data.columns)
# Determine what values are missing
empty = data.apply(lambda col: pandas.isnull(col))
| """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
print(data["Date Text"].head())
first_date = data["Date Text"].values[0]
# print(first_date)
# datetime.strptime(first_date, "%Y-%m-%d")
# datetime(2012, 3, 10, 0, 0)
# data.date = data.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
# print(data.date.head())
# data.index = data.date
# print(data)
# print(data.ix[datetime(2012, 8, 19)])
# Remove date column
# data = data.drop(["date"], axis=1)
# print(data.columns)
# Determine what values are missing
# empty = data.apply(lambda col: pandas.isnull(col))
| Comment out code to test first_date variable. | Comment out code to test first_date variable.
| Python | unlicense | UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016 | ---
+++
@@ -23,16 +23,16 @@
# datetime.strptime(first_date, "%Y-%m-%d")
# datetime(2012, 3, 10, 0, 0)
-data.date = data.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
+# data.date = data.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
# print(data.date.head())
-data.index = data.date
+# data.index = data.date
# print(data)
# print(data.ix[datetime(2012, 8, 19)])
# Remove date column
-data = data.drop(["date"], axis=1)
+# data = data.drop(["date"], axis=1)
# print(data.columns)
# Determine what values are missing
-empty = data.apply(lambda col: pandas.isnull(col))
+# empty = data.apply(lambda col: pandas.isnull(col)) |
218aab63d87d6537c6705f6228a5f49e61d27f8f | protocols/models.py | protocols/models.py | from datetime import datetime
from django.db import models
class Topic(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
attachment = models.ManyToManyField(Attachment)
def __unicode__(self):
return self.name
class Protocol(models.Model):
date = models.DateField(default=datetime.now)
number = models.CharField(max_length=20, unique=True)
scheduled_time = models.TimeField()
start_time = models.TimeField()
quorum = models.PositiveIntegerField()
absent = models.PositiveIntegerField()
attendents = models.ManyToManyField('members.User', related_name='protocols')
topics = models.ManyToManyField(Topic)
voted_for = models.PositiveIntegerField()
voted_against = models.PositiveIntegerField()
voted_abstain = models.PositiveIntegerField()
information = models.TextField()
attachments = models.ManyToManyField('attachments.Attachment')
def __unicode__(self):
return self.number
| from datetime import datetime
from django.db import models
class Topic(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
attachment = models.ManyToManyField('attachments.Attachment')
def __unicode__(self):
return self.name
class Protocol(models.Model):
date = models.DateField(default=datetime.now)
number = models.CharField(max_length=20, unique=True)
scheduled_time = models.TimeField()
start_time = models.TimeField()
quorum = models.PositiveIntegerField()
absent = models.PositiveIntegerField()
attendents = models.ManyToManyField('members.User', related_name='protocols')
topics = models.ManyToManyField(Topic)
voted_for = models.PositiveIntegerField()
voted_against = models.PositiveIntegerField()
voted_abstain = models.PositiveIntegerField()
information = models.TextField()
attachments = models.ManyToManyField('attachments.Attachment')
def __unicode__(self):
return self.number
| Make migration to fix Topic's attachments | Make migration to fix Topic's attachments
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | ---
+++
@@ -6,7 +6,7 @@
class Topic(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
- attachment = models.ManyToManyField(Attachment)
+ attachment = models.ManyToManyField('attachments.Attachment')
def __unicode__(self):
return self.name |
6cd3e11f6ec84cffc0ea71d15d2e164f499529cf | gidget/util/tumorTypeConfig.py | gidget/util/tumorTypeConfig.py | #!/usr/bin/env python
import os.path as path
import sys
import csv
TUMOR_CONFIG_DIALECT = "tumor-type-config"
csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n')
_relpath_configfile = path.join('config', 'tumorTypesConfig.csv')
_configfile = path.expandvars(path.join('${GIDGET_SOURCE_ROOT}', _relpath_configfile))
print (_configfile)
if not path.exists(_configfile):
# KLUDGE
_configfile = path.join(path.dirname(path.dirname(path.dirname(path.abspath(sys.modules[__name__].__file__)))), _relpath_configfile)
if not path.exists(_configfile):
print("cannot find tumor-type configuration file")
sys.exit(1)
tumorTypeConfig = { }
with open(_configfile) as tsv:
for tumorType in csv.DictReader(tsv, dialect=TUMOR_CONFIG_DIALECT):
tumorTypeConfig[tumorType['name']] = tumorType
| #!/usr/bin/env python
import os.path as path
import sys
import csv
TUMOR_CONFIG_DIALECT = "tumor-type-config"
csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n', skipinitialspace=True)
_relpath_configfile = path.join('config', 'tumorTypesConfig.csv')
_configfile = path.expandvars(path.join('${GIDGET_SOURCE_ROOT}', _relpath_configfile))
print (_configfile)
if not path.exists(_configfile):
# KLUDGE
_configfile = path.join(path.dirname(path.dirname(path.dirname(path.abspath(sys.modules[__name__].__file__)))), _relpath_configfile)
if not path.exists(_configfile):
print("cannot find tumor-type configuration file")
sys.exit(1)
tumorTypeConfig = { }
with open(_configfile) as tsv:
for tumorType in csv.DictReader(tsv, dialect=TUMOR_CONFIG_DIALECT):
tumorTypeConfig[tumorType['name']] = tumorType
| Make sure tumor-type config ignores spaces | Make sure tumor-type config ignores spaces
| Python | mit | cancerregulome/gidget,cancerregulome/gidget,cancerregulome/gidget | ---
+++
@@ -5,7 +5,7 @@
import csv
TUMOR_CONFIG_DIALECT = "tumor-type-config"
-csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n')
+csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n', skipinitialspace=True)
_relpath_configfile = path.join('config', 'tumorTypesConfig.csv')
|
025bd5d3e3d7c80ea7408a6bd9a846c6b36cc88b | test/expression_command/radar_9673664/TestExprHelpExamples.py | test/expression_command/radar_9673664/TestExprHelpExamples.py | """
Test example snippets from the lldb 'help expression' output.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
import lldbutil
class Radar9673644TestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
# Call super's setUp().
TestBase.setUp(self)
# Find the line number to break inside main().
self.main_source = "main.c"
self.line = line_number(self.main_source, '// Set breakpoint here.')
# rdar://problem/9673664
def test_expr_commands(self):
"""The following expression commands should just work."""
self.buildDefault()
self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True)
self.runCmd("run", RUN_SUCCEEDED)
# rdar://problem/9673664 lldb expression evaluation problem
self.expect('expr char c[] = "foo"; c[0]',
substrs = ["'f'"])
# runCmd: expr char c[] = "foo"; c[0]
# output: (char) $0 = 'f'
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
| """
Test example snippets from the lldb 'help expression' output.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
import lldbutil
class Radar9673644TestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
# Call super's setUp().
TestBase.setUp(self)
# Find the line number to break inside main().
self.main_source = "main.c"
self.line = line_number(self.main_source, '// Set breakpoint here.')
@expectedFailureDarwin(15641319)
def test_expr_commands(self):
"""The following expression commands should just work."""
self.buildDefault()
self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True)
self.runCmd("run", RUN_SUCCEEDED)
# rdar://problem/9673664 lldb expression evaluation problem
self.expect('expr char c[] = "foo"; c[0]',
substrs = ["'f'"])
# runCmd: expr char c[] = "foo"; c[0]
# output: (char) $0 = 'f'
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
| Make this test an expected fail on darwin until we can fix this bug. | Make this test an expected fail on darwin until we can fix this bug.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@197087 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb | ---
+++
@@ -19,7 +19,7 @@
self.main_source = "main.c"
self.line = line_number(self.main_source, '// Set breakpoint here.')
- # rdar://problem/9673664
+ @expectedFailureDarwin(15641319)
def test_expr_commands(self):
"""The following expression commands should just work."""
self.buildDefault() |
25064a26fcb674c6cd0165945f5e07cc0b4d2136 | medical_prescription_sale_stock_us/__openerp__.py | medical_prescription_sale_stock_us/__openerp__.py | # -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Medical Prescription Sale Stock - US',
'summary': 'Provides US Locale to Medical Prescription Sale Stock',
'version': '9.0.1.0.0',
'author': "LasLabs, Odoo Community Association (OCA)",
'category': 'Medical',
'depends': [
'medical_base_us',
'medical_prescription_sale_stock',
],
'data': [
'views/procurement_order_view.xml',
],
"website": "https://laslabs.com",
"license": "AGPL-3",
'installable': True,
'auto_install': False,
}
| # -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Medical Prescription Sale Stock - US',
'summary': 'Provides US Locale to Medical Prescription Sale Stock',
'version': '9.0.1.0.0',
'author': "LasLabs, Odoo Community Association (OCA)",
'category': 'Medical',
'depends': [
'medical_base_us',
'medical_prescription_sale_stock',
'medical_prescription_us',
],
'data': [
'views/procurement_order_view.xml',
],
"website": "https://laslabs.com",
"license": "AGPL-3",
'installable': True,
'auto_install': False,
}
| Add dependency * Add dependency on medical_prescription_us to manifest file. This is needed for successful installation. | [FIX] medical_prescription_sale_stock_us: Add dependency
* Add dependency on medical_prescription_us to manifest file. This is needed
for successful installation.
| Python | agpl-3.0 | laslabs/vertical-medical,laslabs/vertical-medical | ---
+++
@@ -12,6 +12,7 @@
'depends': [
'medical_base_us',
'medical_prescription_sale_stock',
+ 'medical_prescription_us',
],
'data': [
'views/procurement_order_view.xml', |
7341cc7a9049d3650cf8512e6ea32fefd4bf3cee | tensorflow_text/python/keras/layers/__init__.py | tensorflow_text/python/keras/layers/__init__.py | # coding=utf-8
# Copyright 2021 TF.Text Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tensorflow Text layers for Keras API."""
from tensorflow.python.util.all_util import remove_undocumented
# pylint: disable=wildcard-import
from tensorflow_text.python.keras.layers.todense import *
# Public symbols in the "tensorflow_text.layers" package.
_allowed_symbols = [
"ToDense",
]
remove_undocumented(__name__, _allowed_symbols)
| # coding=utf-8
# Copyright 2021 TF.Text Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tensorflow Text layers for Keras API."""
from tensorflow.python.util.all_util import remove_undocumented
# pylint: disable=wildcard-import
from tensorflow_text.python.keras.layers.todense import *
from tensorflow_text.python.keras.layers.tokenization_layers import *
# Public symbols in the "tensorflow_text.layers" package.
_allowed_symbols = [
"ToDense",
"UnicodeScriptTokenizer",
"WhitespaceTokenizer",
"WordpieceTokenizer",
]
remove_undocumented(__name__, _allowed_symbols)
| Add missing symbols for tokenization layers | Add missing symbols for tokenization layers
Tokenization layers are now exposed by adding them to the list of allowed symbols.
Cheers | Python | apache-2.0 | tensorflow/text,tensorflow/text,tensorflow/text | ---
+++
@@ -19,10 +19,14 @@
# pylint: disable=wildcard-import
from tensorflow_text.python.keras.layers.todense import *
+from tensorflow_text.python.keras.layers.tokenization_layers import *
# Public symbols in the "tensorflow_text.layers" package.
_allowed_symbols = [
"ToDense",
+ "UnicodeScriptTokenizer",
+ "WhitespaceTokenizer",
+ "WordpieceTokenizer",
]
remove_undocumented(__name__, _allowed_symbols) |
e4cfbe6a60a15041a449fd7717166849136cb48b | stormtracks/settings/default_stormtracks_settings.py | stormtracks/settings/default_stormtracks_settings.py | # *** DON'T MODIFY THIS FILE! ***
#
# Instead copy it to stormtracks_settings.py
#
# Default settings for project
# This will get copied to $HOME/.stormtracks/
# on install.
import os
SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__))
# expandvars expands e.g. $HOME
DATA_DIR = os.path.expandvars('$HOME/stormtracks_data/data')
TMP_DATA_DIR = None
OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks_data/output')
LOGGING_DIR = os.path.expandvars('$HOME/stormtracks_data/logs')
FIGURE_OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks_data/figures')
C20_FULL_DATA_DIR = os.path.join(DATA_DIR, 'c20_full')
C20_GRIB_DATA_DIR = os.path.join(DATA_DIR, 'c20_grib')
C20_MEAN_DATA_DIR = os.path.join(DATA_DIR, 'c20_mean')
IBTRACS_DATA_DIR = os.path.join(DATA_DIR, 'ibtracs')
| # *** DON'T MODIFY THIS FILE! ***
#
# Instead copy it to stormtracks_settings.py
#
# Default settings for project
# This will get copied to $HOME/.stormtracks/
# on install.
import os
SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__))
# expandvars expands e.g. $HOME
DATA_DIR = os.path.expandvars('$HOME/stormtracks_data/data')
OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks_data/output')
LOGGING_DIR = os.path.expandvars('$HOME/stormtracks_data/logs')
FIGURE_OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks_data/figures')
C20_FULL_DATA_DIR = os.path.join(DATA_DIR, 'c20_full')
C20_GRIB_DATA_DIR = os.path.join(DATA_DIR, 'c20_grib')
C20_MEAN_DATA_DIR = os.path.join(DATA_DIR, 'c20_mean')
IBTRACS_DATA_DIR = os.path.join(DATA_DIR, 'ibtracs')
| Remove no longer used setting. | Remove no longer used setting.
| Python | mit | markmuetz/stormtracks,markmuetz/stormtracks | ---
+++
@@ -10,7 +10,6 @@
SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__))
# expandvars expands e.g. $HOME
DATA_DIR = os.path.expandvars('$HOME/stormtracks_data/data')
-TMP_DATA_DIR = None
OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks_data/output')
LOGGING_DIR = os.path.expandvars('$HOME/stormtracks_data/logs')
FIGURE_OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks_data/figures') |
2329886a57a25db56079ff615188b744877f3070 | scot/backend_builtin.py | scot/backend_builtin.py | # Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2013-2016 SCoT Development Team
"""Use internally implemented functions as backend."""
from __future__ import absolute_import
import scipy as sp
from . import backend
from . import datatools, pca, csp
from .var import VAR
from .external.infomax_ import infomax
def generate():
def wrapper_infomax(data, random_state=None):
"""Call Infomax (adapted from MNE) for ICA calculation."""
u = infomax(datatools.cat_trials(data).T, random_state=random_state).T
m = sp.linalg.pinv(u)
return m, u
def wrapper_pca(x, reducedim):
"""Call SCoT's PCA algorithm."""
c, d = pca.pca(datatools.cat_trials(x),
subtract_mean=False, reducedim=reducedim)
y = datatools.dot_special(c.T, x)
return c, d, y
def wrapper_csp(x, cl, reducedim):
c, d = csp.csp(x, cl, numcomp=reducedim)
y = datatools.dot_special(c.T, x)
return c, d, y
return {'ica': wrapper_infomax, 'pca': wrapper_pca, 'csp': wrapper_csp,
'var': VAR}
backend.register('builtin', generate)
| # Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2013-2016 SCoT Development Team
"""Use internally implemented functions as backend."""
from __future__ import absolute_import
import scipy as sp
from . import backend
from . import datatools, pca, csp
from .var import VAR
from .external.infomax_ import infomax
def generate():
def wrapper_infomax(data, random_state=None):
"""Call Infomax (adapted from MNE) for ICA calculation."""
u = infomax(datatools.cat_trials(data).T, extended=True,
random_state=random_state).T
m = sp.linalg.pinv(u)
return m, u
def wrapper_pca(x, reducedim):
"""Call SCoT's PCA algorithm."""
c, d = pca.pca(datatools.cat_trials(x),
subtract_mean=False, reducedim=reducedim)
y = datatools.dot_special(c.T, x)
return c, d, y
def wrapper_csp(x, cl, reducedim):
"""Call SCoT's CSP algorithm."""
c, d = csp.csp(x, cl, numcomp=reducedim)
y = datatools.dot_special(c.T, x)
return c, d, y
return {'ica': wrapper_infomax, 'pca': wrapper_pca, 'csp': wrapper_csp,
'var': VAR}
backend.register('builtin', generate)
| Change ICA default to extended Infomax | Change ICA default to extended Infomax
| Python | mit | mbillingr/SCoT,scot-dev/scot,scot-dev/scot,cle1109/scot,cbrnr/scot,cle1109/scot,mbillingr/SCoT,cbrnr/scot | ---
+++
@@ -16,7 +16,8 @@
def generate():
def wrapper_infomax(data, random_state=None):
"""Call Infomax (adapted from MNE) for ICA calculation."""
- u = infomax(datatools.cat_trials(data).T, random_state=random_state).T
+ u = infomax(datatools.cat_trials(data).T, extended=True,
+ random_state=random_state).T
m = sp.linalg.pinv(u)
return m, u
@@ -28,6 +29,7 @@
return c, d, y
def wrapper_csp(x, cl, reducedim):
+ """Call SCoT's CSP algorithm."""
c, d = csp.csp(x, cl, numcomp=reducedim)
y = datatools.dot_special(c.T, x)
return c, d, y |
e50f4bd135b41fa49a3f4d4972f1d7ee594e4447 | jobs/test_settings.py | jobs/test_settings.py | from decouple import config
from jobs.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test_db',
'USER': 'postgres',
'PASSWORD': '',
'HOST': 'db',
'PORT': 5432,
}
}
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
# 'NAME': 'sqlite3.db', # Or path to database file if using sqlite3.
# 'USER': '', # Not used with sqlite3.
# 'PASSWORD': '', # Not used with sqlite3.
# 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
# 'PORT': '', # Set to empty string for default. Not used with sqlite3.
# }
#}
| from decouple import config
from jobs.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test_db',
'USER': 'postgres',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': 5432,
}
}
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
# 'NAME': 'sqlite3.db', # Or path to database file if using sqlite3.
# 'USER': '', # Not used with sqlite3.
# 'PASSWORD': '', # Not used with sqlite3.
# 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
# 'PORT': '', # Set to empty string for default. Not used with sqlite3.
# }
#}
| Replace db host to localhost | Replace db host to localhost
| Python | mit | misachi/job_match,misachi/job_match,misachi/job_match | ---
+++
@@ -8,7 +8,7 @@
'NAME': 'test_db',
'USER': 'postgres',
'PASSWORD': '',
- 'HOST': 'db',
+ 'HOST': 'localhost',
'PORT': 5432,
}
} |
fdc4f3bfc1c3e3aa6f6243f0e6bf200025a79103 | boto/pyami/scriptbase.py | boto/pyami/scriptbase.py | import os
import sys
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self.ts = get_ts()
if config_file:
boto.config.read(config_file)
def notify(self, subject, body=''):
boto.utils.notify(subject, body)
def mkdir(self, path):
if not os.path.isdir(path):
try:
os.mkdir(path)
except:
boto.log.error('Error creating directory: %s' % path)
def umount(self, path):
if os.path.ismount(path):
self.run('umount %s' % path)
def run(self, command, notify=True, exit_on_error=False, cwd=None):
self.last_command = ShellCommand(command, cwd)
if self.last_command.status != 0:
boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output))
if notify:
self.notify('Error encountered', \
'Error running the following command:\n\t%s\n\nCommand output:\n\t%s' % \
(command, self.last_command.output))
if exit_on_error:
sys.exit(-1)
return self.last_command.status
def main(self):
pass
| import os
import sys
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self.ts = get_ts()
if config_file:
boto.config.read(config_file)
def notify(self, subject, body=''):
boto.utils.notify(subject, body)
def mkdir(self, path):
if not os.path.isdir(path):
try:
os.mkdir(path)
except:
boto.log.error('Error creating directory: %s' % path)
def umount(self, path):
if os.path.ismount(path):
self.run('umount %s' % path)
def run(self, command, notify=True, exit_on_error=False, cwd=None):
self.last_command = ShellCommand(command, cwd=cwd)
if self.last_command.status != 0:
boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output))
if notify:
self.notify('Error encountered', \
'Error running the following command:\n\t%s\n\nCommand output:\n\t%s' % \
(command, self.last_command.output))
if exit_on_error:
sys.exit(-1)
return self.last_command.status
def main(self):
pass
| Add missing argument specification for cwd argument. | Add missing argument specification for cwd argument.
| Python | mit | kouk/boto,jamesls/boto,stevenbrichards/boto,serviceagility/boto,nikhilraog/boto,j-carl/boto,ryansb/boto,acourtney2015/boto,drbild/boto,revmischa/boto,ric03uec/boto,alfredodeza/boto,tpodowd/boto,clouddocx/boto,jindongh/boto,Pretio/boto,kouk/boto,lochiiconnectivity/boto,drbild/boto,zachmullen/boto,pfhayes/boto,podhmo/boto,lochiiconnectivity/boto,appneta/boto,FATruden/boto,dablak/boto,cyclecomputing/boto,dablak/boto,jameslegg/boto,awatts/boto,rjschwei/boto,campenberger/boto,ddzialak/boto,andresriancho/boto,bryx-inc/boto,rosmo/boto,vijaylbais/boto,shipci/boto,jamesls/boto,trademob/boto,yangchaogit/boto,bleib1dj/boto,tpodowd/boto,andresriancho/boto,appneta/boto,weka-io/boto,weebygames/boto,darjus-amzn/boto,rayluo/boto,shaunbrady/boto,elainexmas/boto,alex/boto,khagler/boto,felix-d/boto,s0enke/boto,rjschwei/boto,jotes/boto,Timus1712/boto,zzzirk/boto,nishigori/boto,vishnugonela/boto,garnaat/boto,dimdung/boto,disruptek/boto,Asana/boto,TiVoMaker/boto,jameslegg/boto,disruptek/boto,janslow/boto,israelbenatar/boto,ekalosak/boto,ramitsurana/boto,abridgett/boto,lra/boto,nexusz99/boto,SaranyaKarthikeyan/boto,ocadotechnology/boto,alex/boto,varunarya10/boto | ---
+++
@@ -28,7 +28,7 @@
self.run('umount %s' % path)
def run(self, command, notify=True, exit_on_error=False, cwd=None):
- self.last_command = ShellCommand(command, cwd)
+ self.last_command = ShellCommand(command, cwd=cwd)
if self.last_command.status != 0:
boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output))
if notify: |
906532af9c47072095706fa5a17cae5043ff5f86 | api/__init__.py | api/__init__.py | from api.models import BaseTag
TAGS = {
'fairness': {
'color': '#bcf0ff',
'description': 'Fairness is ideas of justice, rights, and autonomy.',
},
'cheating': {
'color': '#feffbc',
'description': 'Cheating is acting dishonestly or unfairly in order to gain an advantage.',
},
'loyalty': {
'color': '#bcffe2',
'description': 'Loyalty underlies virtues of patriotism and self-sacrifice for the group.',
},
'betrayal': {
'color': '#ffe5bc',
'description': 'Betrayal is disloyalty and the destruction of trust.',
},
'care': {
'color': '#bcc1ff',
'description': 'Care is concern for the well-being of others.',
},
'harm': {
'color': '#ffbcf5',
'description': 'Harm is something that causes someone or something to be hurt, broken, made less valuable or successful, etc.',
},
'authority': {
'color': '#ffb29e',
'description': 'Authority underlies virtues of leadership and followership, including deference to legitimate authority and respect for traditions.',
},
'subversion': {
'color' :'#e7bcff',
'description': 'Subversion is the undermining of the power and authority of an established system or institution.',
},
'sanctity': {
'color': '#d6ffbc',
'description': 'Sanctity underlies notions of striving to live in an elevated, less carnal, more noble way.',
},
'degradation': {
'color': '#ffbcd1',
'description': 'Degradation is the process in which the beauty or quality of something is destroyed or spoiled',
},
'morality': {
'color' : '#c1bfc0',
'description': 'Morality is a particular system of values and principles of conduct.',
},
};
def populate_base_tags(tags):
for tag in tags:
BaseTag.objects.get_or_create(
name=tag,
color=tags[tag]["color"],
description=tags[tag]["description"]
)
print "Base tags created!"
populate_base_tags(TAGS) | Add script to populate Base Tags on app startup | Add script to populate Base Tags on app startup
| Python | mit | haystack/eyebrowse-server,haystack/eyebrowse-server,haystack/eyebrowse-server,haystack/eyebrowse-server,haystack/eyebrowse-server | ---
+++
@@ -0,0 +1,60 @@
+from api.models import BaseTag
+
+TAGS = {
+ 'fairness': {
+ 'color': '#bcf0ff',
+ 'description': 'Fairness is ideas of justice, rights, and autonomy.',
+ },
+ 'cheating': {
+ 'color': '#feffbc',
+ 'description': 'Cheating is acting dishonestly or unfairly in order to gain an advantage.',
+ },
+ 'loyalty': {
+ 'color': '#bcffe2',
+ 'description': 'Loyalty underlies virtues of patriotism and self-sacrifice for the group.',
+ },
+ 'betrayal': {
+ 'color': '#ffe5bc',
+ 'description': 'Betrayal is disloyalty and the destruction of trust.',
+ },
+ 'care': {
+ 'color': '#bcc1ff',
+ 'description': 'Care is concern for the well-being of others.',
+ },
+ 'harm': {
+ 'color': '#ffbcf5',
+ 'description': 'Harm is something that causes someone or something to be hurt, broken, made less valuable or successful, etc.',
+ },
+ 'authority': {
+ 'color': '#ffb29e',
+ 'description': 'Authority underlies virtues of leadership and followership, including deference to legitimate authority and respect for traditions.',
+ },
+ 'subversion': {
+ 'color' :'#e7bcff',
+ 'description': 'Subversion is the undermining of the power and authority of an established system or institution.',
+ },
+ 'sanctity': {
+ 'color': '#d6ffbc',
+ 'description': 'Sanctity underlies notions of striving to live in an elevated, less carnal, more noble way.',
+ },
+ 'degradation': {
+ 'color': '#ffbcd1',
+ 'description': 'Degradation is the process in which the beauty or quality of something is destroyed or spoiled',
+ },
+ 'morality': {
+ 'color' : '#c1bfc0',
+ 'description': 'Morality is a particular system of values and principles of conduct.',
+ },
+};
+
+def populate_base_tags(tags):
+ for tag in tags:
+ BaseTag.objects.get_or_create(
+ name=tag,
+ color=tags[tag]["color"],
+ description=tags[tag]["description"]
+ )
+
+ print "Base tags created!"
+
+populate_base_tags(TAGS) | |
91bf68e26c0fdf7de4209622192f9d57be2d60f8 | feincms/views/cbv/views.py | feincms/views/cbv/views.py | from __future__ import absolute_import, unicode_literals
from django.http import Http404
from feincms import settings
from feincms._internal import get_model
from feincms.module.mixins import ContentView
class Handler(ContentView):
page_model_path = 'page.Page'
context_object_name = 'feincms_page'
@property
def page_model(self):
if not hasattr(self, '_page_model'):
self._page_model = get_model(*self.page_model_path.split('.'))
if self._page_model is None:
raise ImportError(
"Can't import model \"%s\"" % self.page_model_path)
return self._page_model
def get_object(self):
path = None
if self.args:
path = self.args[0]
return self.page_model._default_manager.for_request(
self.request, raise404=True, best_match=True, path=path)
def dispatch(self, request, *args, **kwargs):
try:
return super(Handler, self).dispatch(request, *args, **kwargs)
except Http404 as e:
if settings.FEINCMS_CMS_404_PAGE:
try:
request.original_path_info = request.path_info
request.path_info = settings.FEINCMS_CMS_404_PAGE
response = super(Handler, self).dispatch(
request, *args, **kwargs)
response.status_code = 404
return response
except Http404:
raise e
else:
raise
| from __future__ import absolute_import, unicode_literals
from django.http import Http404
from django.utils.functional import cached_property
from feincms import settings
from feincms._internal import get_model
from feincms.module.mixins import ContentView
class Handler(ContentView):
page_model_path = None
context_object_name = 'feincms_page'
@cached_property
def page_model(self):
model = self.page_model_path or settings.FEINCMS_DEFAULT_PAGE_MODEL
return get_model(*model.split('.'))
def get_object(self):
path = None
if self.args:
path = self.args[0]
return self.page_model._default_manager.for_request(
self.request, raise404=True, best_match=True, path=path)
def dispatch(self, request, *args, **kwargs):
try:
return super(Handler, self).dispatch(request, *args, **kwargs)
except Http404 as e:
if settings.FEINCMS_CMS_404_PAGE:
try:
request.original_path_info = request.path_info
request.path_info = settings.FEINCMS_CMS_404_PAGE
response = super(Handler, self).dispatch(
request, *args, **kwargs)
response.status_code = 404
return response
except Http404:
raise e
else:
raise
| Stop invoking get_model for each request | Stop invoking get_model for each request
| Python | bsd-3-clause | joshuajonah/feincms,mjl/feincms,matthiask/django-content-editor,michaelkuty/feincms,matthiask/django-content-editor,nickburlett/feincms,feincms/feincms,michaelkuty/feincms,mjl/feincms,mjl/feincms,joshuajonah/feincms,joshuajonah/feincms,nickburlett/feincms,matthiask/django-content-editor,joshuajonah/feincms,feincms/feincms,matthiask/feincms2-content,michaelkuty/feincms,matthiask/feincms2-content,nickburlett/feincms,nickburlett/feincms,matthiask/django-content-editor,michaelkuty/feincms,matthiask/feincms2-content,feincms/feincms | ---
+++
@@ -1,6 +1,7 @@
from __future__ import absolute_import, unicode_literals
from django.http import Http404
+from django.utils.functional import cached_property
from feincms import settings
from feincms._internal import get_model
@@ -8,17 +9,13 @@
class Handler(ContentView):
- page_model_path = 'page.Page'
+ page_model_path = None
context_object_name = 'feincms_page'
- @property
+ @cached_property
def page_model(self):
- if not hasattr(self, '_page_model'):
- self._page_model = get_model(*self.page_model_path.split('.'))
- if self._page_model is None:
- raise ImportError(
- "Can't import model \"%s\"" % self.page_model_path)
- return self._page_model
+ model = self.page_model_path or settings.FEINCMS_DEFAULT_PAGE_MODEL
+ return get_model(*model.split('.'))
def get_object(self):
path = None |
be33ae4e800619e0c50ef9dd7ce5e135e2ebb54b | telethon/errors/__init__.py | telethon/errors/__init__.py | import re
from .common import (
ReadCancelledError, InvalidParameterError, TypeNotFoundError,
InvalidChecksumError
)
from .rpc_errors import (
RPCError, InvalidDCError, BadRequestError, UnauthorizedError,
ForbiddenError, NotFoundError, FloodError, ServerError, BadMessageError
)
from .rpc_errors_303 import *
from .rpc_errors_400 import *
from .rpc_errors_401 import *
from .rpc_errors_420 import *
def rpc_message_to_error(code, message):
errors = {
303: rpc_303_errors,
400: rpc_400_errors,
401: rpc_401_errors,
420: rpc_420_errors
}.get(code, None)
if errors is not None:
for msg, cls in errors.items():
m = re.match(msg, message)
if m:
extra = int(m.group(1)) if m.groups() else None
return cls(extra=extra)
elif code == 403:
return ForbiddenError()
elif code == 404:
return NotFoundError()
elif code == 500:
return ServerError()
return RPCError('{} (code {})'.format(message, code))
| import re
from .common import (
ReadCancelledError, InvalidParameterError, TypeNotFoundError,
InvalidChecksumError
)
from .rpc_errors import (
RPCError, InvalidDCError, BadRequestError, UnauthorizedError,
ForbiddenError, NotFoundError, FloodError, ServerError, BadMessageError
)
from .rpc_errors_303 import *
from .rpc_errors_400 import *
from .rpc_errors_401 import *
from .rpc_errors_420 import *
def rpc_message_to_error(code, message):
errors = {
303: rpc_303_errors,
400: rpc_400_errors,
401: rpc_401_errors,
420: rpc_420_errors
}.get(code, None)
if errors is not None:
for msg, cls in errors.items():
m = re.match(msg, message)
if m:
extra = int(m.group(1)) if m.groups() else None
return cls(extra=extra)
elif code == 403:
return ForbiddenError(message)
elif code == 404:
return NotFoundError(message)
elif code == 500:
return ServerError(message)
return RPCError('{} (code {})'.format(message, code))
| Fix rpc_message_to_error failing to construct them | Fix rpc_message_to_error failing to construct them | Python | mit | LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,kyasabu/Telethon,expectocode/Telethon,andr-04/Telethon | ---
+++
@@ -32,12 +32,12 @@
return cls(extra=extra)
elif code == 403:
- return ForbiddenError()
+ return ForbiddenError(message)
elif code == 404:
- return NotFoundError()
+ return NotFoundError(message)
elif code == 500:
- return ServerError()
+ return ServerError(message)
return RPCError('{} (code {})'.format(message, code)) |
f1ba8bf1aeec6579e1830b093485c27bf54ad869 | flashcards/main.py | flashcards/main.py | import click
import os
from flashcards import storage
from flashcards.study import BaseStudySession
from flashcards.commands import sets as sets_commands
from flashcards.commands import cards as cards_commands
@click.group()
def cli():
""" Main entry point of the application """
# Verify that the storage directory is present.
storage.verify_storage_dir_integrity()
pass
@click.command('status')
def status():
"""
Show status of the application.
Displaying the currently selected studyset.
- studyset title
- studyset description
- number of cards
"""
studyset = storage.load_selected_studyset()
data = (studyset.title, len(studyset._cards))
click.echo('Currently using studyset: %s (%s cards)\n' % data)
click.echo('Description: \n%s' % studyset.description)
@click.command('study')
@click.argument('studyset')
def study(studyset):
""" Start a study session on the supplied studyset. """
studyset_path = os.path.join(storage.studyset_storage_path(), studyset)
studyset = storage.load_studyset(studyset_path).load()
studysession = BaseStudySession()
studysession.start(studyset)
# Add the subcommands to this main entry point.
cli.add_command(status)
cli.add_command(study)
cli.add_command(sets_commands.sets_group)
cli.add_command(cards_commands.cards_group)
| import click
import os
from flashcards import storage
from flashcards.study import BaseStudySession
from flashcards.commands import sets as sets_commands
from flashcards.commands import cards as cards_commands
@click.group()
def cli():
""" Main entry point of the application """
# Verify that the storage directory is present.
storage.verify_storage_dir_integrity()
pass
@click.command('status')
def status():
"""
Show status of the application.
Displaying the currently selected studyset.
- studyset title
- studyset description
- number of cards
"""
studyset = storage.load_selected_studyset()
data = (studyset.title, len(studyset))
click.echo('Currently using studyset: %s (%s cards)\n' % data)
click.echo('Description: \n%s' % studyset.description)
@click.command('study')
@click.argument('studyset')
def study(studyset):
""" Start a study session on the supplied studyset. """
studyset_path = os.path.join(storage.studyset_storage_path(), studyset)
studyset = storage.load_studyset(studyset_path).load()
studysession = BaseStudySession()
studysession.start(studyset)
# Add the subcommands to this main entry point.
cli.add_command(status)
cli.add_command(study)
cli.add_command(sets_commands.sets_group)
cli.add_command(cards_commands.cards_group)
| Fix an issue where the `_cards` attribute in StudySet was used. | Fix an issue where the `_cards` attribute in StudySet was used.
| Python | mit | zergov/flashcards,zergov/flashcards | ---
+++
@@ -27,7 +27,7 @@
- number of cards
"""
studyset = storage.load_selected_studyset()
- data = (studyset.title, len(studyset._cards))
+ data = (studyset.title, len(studyset))
click.echo('Currently using studyset: %s (%s cards)\n' % data)
click.echo('Description: \n%s' % studyset.description)
|
b12b1245a5a77f2d9373a4878fe07c01335624f7 | froide/publicbody/forms.py | froide/publicbody/forms.py | from django import forms
from django.utils.translation import ugettext as _
from helper.widgets import EmailInput
class PublicBodyForm(forms.Form):
name = forms.CharField(label=_("Name of Public Body"))
description = forms.CharField(label=_("Short description"), widget=forms.Textarea, required=False)
email = forms.EmailField(widget=EmailInput, label=_("Email Address for Freedom of Information Requests"))
url = forms.URLField(label=_("Homepage URL of Public Body"))
| from django import forms
from django.utils.translation import ugettext as _
from haystack.forms import SearchForm
from helper.widgets import EmailInput
class PublicBodyForm(forms.Form):
name = forms.CharField(label=_("Name of Public Body"))
description = forms.CharField(label=_("Short description"), widget=forms.Textarea, required=False)
email = forms.EmailField(widget=EmailInput, label=_("Email Address for Freedom of Information Requests"))
url = forms.URLField(label=_("Homepage URL of Public Body"))
class TopicSearchForm(SearchForm):
topic = forms.CharField(required=False, widget=forms.HiddenInput)
def search(self):
sqs = super(TopicSearchForm, self).search()
topic = self.cleaned_data['topic']
if topic:
sqs.filter_and(topic_auto=topic)
return sqs
| Add a topic search form (currently not used) | Add a topic search form (currently not used) | Python | mit | stefanw/froide,CodeforHawaii/froide,catcosmo/froide,LilithWittmann/froide,LilithWittmann/froide,ryankanno/froide,okfse/froide,fin/froide,LilithWittmann/froide,CodeforHawaii/froide,LilithWittmann/froide,ryankanno/froide,okfse/froide,fin/froide,stefanw/froide,stefanw/froide,catcosmo/froide,ryankanno/froide,catcosmo/froide,okfse/froide,catcosmo/froide,catcosmo/froide,CodeforHawaii/froide,LilithWittmann/froide,CodeforHawaii/froide,CodeforHawaii/froide,ryankanno/froide,okfse/froide,ryankanno/froide,stefanw/froide,stefanw/froide,okfse/froide,fin/froide,fin/froide | ---
+++
@@ -1,5 +1,7 @@
from django import forms
from django.utils.translation import ugettext as _
+
+from haystack.forms import SearchForm
from helper.widgets import EmailInput
@@ -11,4 +13,13 @@
url = forms.URLField(label=_("Homepage URL of Public Body"))
+class TopicSearchForm(SearchForm):
+ topic = forms.CharField(required=False, widget=forms.HiddenInput)
+ def search(self):
+ sqs = super(TopicSearchForm, self).search()
+ topic = self.cleaned_data['topic']
+ if topic:
+ sqs.filter_and(topic_auto=topic)
+ return sqs
+ |
7b96c39fc54f17cd52e4b54fb74d21ae66e2d3f0 | blockbuster/example_config_files/example_config.py | blockbuster/example_config_files/example_config.py | # General Settings
timerestriction = False
debug_mode = True
log_directory = './logs'
# Email Settings
# emailtype = "Gmail"
emailtype = "Console"
# SMS Settings
# outboundsmstype = "WebService"
outboundsmstype = "Console"
# Twilio Auth Keys
account_sid = "twilio sid here"
auth_token = "auth token here"
# SMS Services Auth
spsms_basic_auth = 'basic auth header here'
spsms_host = 'host here'
spsms_url = 'url here'
# Postgres Connection Details
pg_host = 'localhost'
pg_dbname = 'blockbuster'
pg_user = 'blockbuster'
pg_passwd = 'blockbuster'
# Proxy Details
proxy_user = ''
proxy_pass = ''
proxy_host = ''
proxy_port = 8080
# Testing
test_to_number = ''
test_from_number = ''
# Pushover Keys
pushover_app_token = "pushover_token"
# Email Configuration
smtp_server = 'smtp.gmail.com:587'
mail_username = ''
mail_fromaddr = mail_username
mail_password = ''
mail_monitoring_addr = ''
# API Variables
api_username = "username here"
api_passphrase = "passphrase here"
# New Number
return_number = "+440000111222" | # General Settings
timerestriction = False
debug_mode = True
log_directory = './logs'
# Email Settings
# emailtype = "Gmail"
emailtype = "Console"
# SMS Settings
# outboundsmstype = "WebService"
outboundsmstype = "Console"
# Twilio Auth Keys
account_sid = "twilio sid here"
auth_token = "auth token here"
# SMS Services Auth
spsms_basic_auth = 'basic auth header here'
spsms_host = 'host here'
spsms_url = 'url here'
# Postgres Connection Details
pg_host = 'localhost'
pg_dbname = 'blockbuster'
pg_user = 'blockbuster'
pg_passwd = 'blockbuster'
# Proxy Details
proxy_user = ''
proxy_pass = ''
proxy_host = ''
proxy_port = 8080
# Testing
test_to_number = ''
test_from_number = ''
# Pushover Keys
pushover_app_token = "pushover_token"
# Email Configuration
smtp_server = 'smtp.gmail.com:587'
mail_username = ''
mail_fromaddr = mail_username
mail_password = ''
mail_monitoring_addr = ''
# New Number
return_number = "+440000111222" | Remove API User section from example config file | Remove API User section from example config file
| Python | mit | mattstibbs/blockbuster-server,mattstibbs/blockbuster-server | ---
+++
@@ -46,9 +46,5 @@
mail_password = ''
mail_monitoring_addr = ''
-# API Variables
-api_username = "username here"
-api_passphrase = "passphrase here"
-
# New Number
return_number = "+440000111222" |
9c1c93dc49f1b5986773164a321cdfcb8e383827 | txircd/modules/rfc/cmode_l.py | txircd/modules/rfc/cmode_l.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class LimitMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "LimitMode"
core = True
affectedActions = [ "joinpermission" ]
def hookIRCd(self, ircd):
self.ircd = ircd
def channelModes(self):
return [ ("l", ModeType.Param, self) ]
def actions(self):
return [ ("modeactioncheck-channel-l-joinpermission", 10, self.isModeSet) ]
def isModeSet(self, channel, alsoChannel, user):
if "l" in channel.modes:
return channel.modes["l"]
return None
def checkSet(self, param):
try:
return [ int(param) ]
except ValueError:
return None
def apply(self, actionType, channel, param, alsoChannel, user):
if len(channel.users) >= param:
user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
return False
return None
limitMode = LimitMode() | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class LimitMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "LimitMode"
core = True
affectedActions = [ "joinpermission" ]
def hookIRCd(self, ircd):
self.ircd = ircd
def channelModes(self):
return [ ("l", ModeType.Param, self) ]
def actions(self):
return [ ("modeactioncheck-channel-l-joinpermission", 10, self.isModeSet) ]
def isModeSet(self, channel, alsoChannel, user):
if "l" in channel.modes:
return channel.modes["l"]
return None
def checkSet(self, channel, param):
try:
return [ int(param) ]
except ValueError:
return None
def apply(self, actionType, channel, param, alsoChannel, user):
if len(channel.users) >= param:
user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
return False
return None
limitMode = LimitMode() | Update +l with new checkSet parameter | Update +l with new checkSet parameter
| Python | bsd-3-clause | ElementalAlchemist/txircd,Heufneutje/txircd | ---
+++
@@ -25,7 +25,7 @@
return channel.modes["l"]
return None
- def checkSet(self, param):
+ def checkSet(self, channel, param):
try:
return [ int(param) ]
except ValueError: |
076a129a8468a6c85c8b55a752aca87a60f90d79 | ehrcorral/compressions.py | ehrcorral/compressions.py | from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
from jellyfish import soundex, nysiis, metaphone
from metaphone import doublemetaphone as dmetaphone
def first_letter(name):
"""A simple name compression that returns the first letter of the name.
Args:
name (str): A forename, surname, or other name.
Returns:
(str): The upper case of the first letter of the name
"""
return name[0].upper()
| from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
from jellyfish import soundex, nysiis, metaphone
from metaphone import doublemetaphone as dmetaphone
def first_letter(name):
"""A simple name compression that returns the first letter of the name.
Args:
name (str): A forename, surname, or other name.
Returns:
(str): The upper case of the first letter of the name
"""
return name[0].upper() if name else unicode('')
| Add if/else to first_letter compression to handle empty names | Add if/else to first_letter compression to handle empty names
| Python | isc | nsh87/ehrcorral | ---
+++
@@ -16,4 +16,4 @@
Returns:
(str): The upper case of the first letter of the name
"""
- return name[0].upper()
+ return name[0].upper() if name else unicode('') |
bd7c0a9ac2d357ab635bf2948824256f1e6ddbec | src/carreralib/serial.py | src/carreralib/serial.py | from serial import serial_for_url
from .connection import BufferTooShort, Connection, TimeoutError
class SerialConnection(Connection):
def __init__(self, url, timeout=None):
self.__serial = serial_for_url(url, baudrate=19200, timeout=timeout)
def close(self):
self.__serial.close()
def recv(self, maxlength=None):
buf = bytearray()
while True:
c = self.__serial.read()
if not c:
raise TimeoutError("Timeout waiting for serial data")
elif c == b"$" or c == b"#":
break
elif maxlength is not None and maxlength <= len(buf):
raise BufferTooShort("Buffer too short for data received")
else:
buf.extend(c)
return bytes(buf)
def send(self, buf, offset=0, size=None):
n = len(buf)
if offset < 0:
raise ValueError("offset is negative")
elif n < offset:
raise ValueError("buffer length < offset")
elif size is None:
size = n - offset
elif size < 0:
raise ValueError("size is negative")
elif offset + size > n:
raise ValueError("buffer length < offset + size")
self.__serial.write(b'"')
self.__serial.write(buf[offset : offset + size])
self.__serial.write(b"$")
self.__serial.flush()
@classmethod
def scan(_):
from serial.tools.list_ports import comports
return ((info.device, info.description) for info in comports())
| from serial import serial_for_url
from .connection import BufferTooShort, Connection, TimeoutError
class SerialConnection(Connection):
__serial = None
def __init__(self, url, timeout=None):
self.__serial = serial_for_url(url, baudrate=19200, timeout=timeout)
def close(self):
if self.__serial:
self.__serial.close()
def recv(self, maxlength=None):
buf = bytearray()
while True:
c = self.__serial.read()
if not c:
raise TimeoutError("Timeout waiting for serial data")
elif c == b"$" or c == b"#":
break
elif maxlength is not None and maxlength <= len(buf):
raise BufferTooShort("Buffer too short for data received")
else:
buf.extend(c)
return bytes(buf)
def send(self, buf, offset=0, size=None):
n = len(buf)
if offset < 0:
raise ValueError("offset is negative")
elif n < offset:
raise ValueError("buffer length < offset")
elif size is None:
size = n - offset
elif size < 0:
raise ValueError("size is negative")
elif offset + size > n:
raise ValueError("buffer length < offset + size")
self.__serial.write(b'"')
self.__serial.write(buf[offset : offset + size])
self.__serial.write(b"$")
self.__serial.flush()
@classmethod
def scan(_):
from serial.tools.list_ports import comports
return ((info.device, info.description) for info in comports())
| Fix SerialConnection.close() with invalid device. | Fix SerialConnection.close() with invalid device.
| Python | mit | tkem/carreralib | ---
+++
@@ -4,11 +4,15 @@
class SerialConnection(Connection):
+
+ __serial = None
+
def __init__(self, url, timeout=None):
self.__serial = serial_for_url(url, baudrate=19200, timeout=timeout)
def close(self):
- self.__serial.close()
+ if self.__serial:
+ self.__serial.close()
def recv(self, maxlength=None):
buf = bytearray() |
b8c724cb141f6b0757d38b826b5cfd841284a37e | kuryr_libnetwork/server.py | kuryr_libnetwork/server.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import sys
from oslo_log import log
from six.moves.urllib import parse
from kuryr_libnetwork import app
from kuryr_libnetwork.common import config
from kuryr_libnetwork import controllers
def start():
config.init(sys.argv[1:])
controllers.neutron_client()
controllers.check_for_neutron_ext_support()
controllers.check_for_neutron_ext_tag()
log.setup(config.CONF, 'Kuryr')
kuryr_uri = parse.urlparse(config.CONF.kuryr_uri)
app.run(kuryr_uri.hostname, kuryr_uri.port)
if __name__ == '__main__':
start()
| # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import sys
from oslo_log import log
from six.moves.urllib import parse
from kuryr_libnetwork import app
from kuryr_libnetwork.common import config
from kuryr_libnetwork import controllers
def start():
config.init(sys.argv[1:])
log.setup(config.CONF, 'kuryr')
controllers.neutron_client()
controllers.check_for_neutron_ext_support()
controllers.check_for_neutron_ext_tag()
kuryr_uri = parse.urlparse(config.CONF.kuryr_uri)
app.run(kuryr_uri.hostname, kuryr_uri.port)
if __name__ == '__main__':
start()
| Fix no log in /var/log/kuryr/kuryr.log | Fix no log in /var/log/kuryr/kuryr.log
code misuse "Kuryr" in log.setup, it should be "kuryr".
Change-Id: If36c9e03a01dae710ca12cf340abbb0c5647b47f
Closes-bug: #1617863
| Python | apache-2.0 | celebdor/kuryr-libnetwork,celebdor/kuryr-libnetwork,celebdor/kuryr-libnetwork | ---
+++
@@ -22,11 +22,11 @@
def start():
config.init(sys.argv[1:])
+ log.setup(config.CONF, 'kuryr')
controllers.neutron_client()
controllers.check_for_neutron_ext_support()
controllers.check_for_neutron_ext_tag()
- log.setup(config.CONF, 'Kuryr')
kuryr_uri = parse.urlparse(config.CONF.kuryr_uri)
app.run(kuryr_uri.hostname, kuryr_uri.port)
|
0d59cf159d9c5f6c64c49cc7ef3cef8feaf5452d | templatetags/coltrane.py | templatetags/coltrane.py | from django.db.models import get_model
from django import template
from django.contrib.comments.models import Comment, FreeComment
from coltrane.models import Entry, Link
register = template.Library()
class LatestFeaturedNode(template.Node):
def __init__(self, varname):
self.varname = varname
def render(self, context):
context[self.varname] = Entry.live.latest_featured()
return ''
def do_latest_featured(parser, token):
"""
Retrieves the latest featured Entry and stores it in a specified
context variable.
Syntax::
{% get_latest_featured_entry as [varname] %}
Example::
{% get_latest_featured_entry as latest_featured_entry %}
"""
bits = token.contents.split()
if len(bits) != 3:
raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
if bits[1] != 'as':
raise template.TemplateSyntaxError("first argument to '%s' tag must be 'as'" % bits[0])
return LatestFeaturedNode(bits[2])
register.tag('get_latest_featured_entry', do_latest_featured)
| from django.db.models import get_model
from django import template
from django.contrib.comments.models import Comment, FreeComment
from template_utils.templatetags.generic_content import GenericContentNode
from coltrane.models import Entry, Link
register = template.Library()
class LatestFeaturedNode(GenericContentNode):
def _get_query_set(self):
if self._queryset is not None:
self._queryset = self._queryset.filter(featured__exact=True)
def do_featured_entries(parser, token):
"""
Retrieves the latest ``num`` featured entries and stores them in a
specified context variable.
Syntax::
{% get_featured_entries [num] as [varname] %}
Example::
{% get_featured_entries 5 as featured_entries %}
"""
bits = token.contents.split()
if len(bits) != 4:
raise template.TemplateSyntaxError("'%s' tag takes three arguments" % bits[0])
if bits[2] != 'as':
raise template.TemplateSyntaxError("second argument to '%s' tag must be 'as'" % bits[0])
return LatestFeaturedNode('coltrane.entry', bits[1], bits[3])
def do_featured_entry(parser, token):
"""
Retrieves the latest featured Entry and stores it in a specified
context variable.
Syntax::
{% get_featured_entry as [varname] %}
Example::
{% get_featured_entry as featured_entry %}
"""
bits = token.contents.split()
if len(bits) != 3:
raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
if bits[1] != 'as':
raise template.TemplateSyntaxError("first argument to '%s' tag must be 'as'" % bits[0])
return LatestFeaturedNode('coltrane.entry', 1, bits[2])
register.tag('get_featured_entries', do_featured_entries)
register.tag('get_featured_entry', do_featured_entry)
| Refactor LatestFeaturedNode to use GenericContentNode and accept a configurable number of entries to fetch | Refactor LatestFeaturedNode to use GenericContentNode and accept a configurable number of entries to fetch
git-svn-id: 9770886a22906f523ce26b0ad22db0fc46e41232@54 5f8205a5-902a-0410-8b63-8f478ce83d95
| Python | bsd-3-clause | clones/django-coltrane,mafix/coltrane-blog | ---
+++
@@ -1,33 +1,53 @@
from django.db.models import get_model
from django import template
from django.contrib.comments.models import Comment, FreeComment
+from template_utils.templatetags.generic_content import GenericContentNode
+
from coltrane.models import Entry, Link
register = template.Library()
-class LatestFeaturedNode(template.Node):
- def __init__(self, varname):
- self.varname = varname
-
- def render(self, context):
- context[self.varname] = Entry.live.latest_featured()
- return ''
+class LatestFeaturedNode(GenericContentNode):
+ def _get_query_set(self):
+ if self._queryset is not None:
+ self._queryset = self._queryset.filter(featured__exact=True)
-def do_latest_featured(parser, token):
+def do_featured_entries(parser, token):
+ """
+ Retrieves the latest ``num`` featured entries and stores them in a
+ specified context variable.
+
+ Syntax::
+
+ {% get_featured_entries [num] as [varname] %}
+
+ Example::
+
+ {% get_featured_entries 5 as featured_entries %}
+
+ """
+ bits = token.contents.split()
+ if len(bits) != 4:
+ raise template.TemplateSyntaxError("'%s' tag takes three arguments" % bits[0])
+ if bits[2] != 'as':
+ raise template.TemplateSyntaxError("second argument to '%s' tag must be 'as'" % bits[0])
+ return LatestFeaturedNode('coltrane.entry', bits[1], bits[3])
+
+def do_featured_entry(parser, token):
"""
Retrieves the latest featured Entry and stores it in a specified
context variable.
Syntax::
- {% get_latest_featured_entry as [varname] %}
+ {% get_featured_entry as [varname] %}
Example::
- {% get_latest_featured_entry as latest_featured_entry %}
+ {% get_featured_entry as featured_entry %}
"""
bits = token.contents.split()
@@ -35,6 +55,7 @@
raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
if bits[1] != 'as':
raise template.TemplateSyntaxError("first argument to '%s' tag must be 'as'" % bits[0])
- return LatestFeaturedNode(bits[2])
+ return LatestFeaturedNode('coltrane.entry', 1, bits[2])
-register.tag('get_latest_featured_entry', do_latest_featured)
+register.tag('get_featured_entries', do_featured_entries)
+register.tag('get_featured_entry', do_featured_entry) |
7321ed72469ad4b9eaf7b1feda370472c294fa97 | django_backend_test/noras_menu/forms.py | django_backend_test/noras_menu/forms.py | # -*- encoding: utf-8 -*-
#STDLIB importa
#Core Django Imports
from django import forms
#Third Party apps imports
#Imports local apps
from .models import Menu, MenuItems
| # -*- encoding: utf-8 -*-
#STDLIB importa
from datetime import date
#Core Django Imports
from django import forms
from django.forms.models import inlineformset_factory
#Third Party apps imports
#Imports local apps
from .models import Menu, MenuItems, UserSelectedLunch, Subscribers
class MenuForm(forms.ModelForm):
day = forms.DateField(label='Menu date', input_formats=['%d-%m-%Y'])
class Meta:
model = Menu
fields = '__all__'
MenuItemsFormSet = inlineformset_factory(Menu, MenuItems, fields=('name','menu',))
class MenuSelectForm(forms.ModelForm):
class Meta:
model = UserSelectedLunch
fields = '__all__'
class SubscribersForm(forms.ModelForm):
class Meta:
model = Subscribers
fields = '__all__' | Add ModelForm of Menu, MenuItems and Subscriber | Add ModelForm of Menu, MenuItems and Subscriber
| Python | mit | semorale/backend-test,semorale/backend-test,semorale/backend-test | ---
+++
@@ -1,10 +1,33 @@
# -*- encoding: utf-8 -*-
#STDLIB importa
+from datetime import date
#Core Django Imports
from django import forms
+from django.forms.models import inlineformset_factory
#Third Party apps imports
#Imports local apps
-from .models import Menu, MenuItems
+from .models import Menu, MenuItems, UserSelectedLunch, Subscribers
+
+class MenuForm(forms.ModelForm):
+ day = forms.DateField(label='Menu date', input_formats=['%d-%m-%Y'])
+
+ class Meta:
+ model = Menu
+ fields = '__all__'
+
+MenuItemsFormSet = inlineformset_factory(Menu, MenuItems, fields=('name','menu',))
+
+class MenuSelectForm(forms.ModelForm):
+
+ class Meta:
+ model = UserSelectedLunch
+ fields = '__all__'
+
+class SubscribersForm(forms.ModelForm):
+
+ class Meta:
+ model = Subscribers
+ fields = '__all__' |
e103ac2a6df36d4236640d36da1a92b6da90e7c5 | masters/master.chromium.webrtc/master_builders_cfg.py | masters/master.chromium.webrtc/master_builders_cfg.py | # Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from buildbot.changes.filter import ChangeFilter
from buildbot.schedulers.basic import SingleBranchScheduler
from master.factory import annotator_factory
m_annotator = annotator_factory.AnnotatorFactory()
def Update(c):
c['schedulers'].append(
SingleBranchScheduler(name='chromium_scheduler',
change_filter=ChangeFilter(project='chromium',
branch='master'),
treeStableTimer=60,
builderNames=[
'Win Builder',
'Mac Builder',
'Linux Builder',
]),
)
specs = [
{'name': 'Win Builder', 'category': 'win'},
{'name': 'WinXP Tester', 'category': 'win'},
{'name': 'Win7 Tester', 'category': 'win'},
{'name': 'Win8 Tester', 'category': 'win'},
{'name': 'Win10 Tester', 'category': 'win'},
{'name': 'Mac Builder', 'category': 'mac'},
{'name': 'Mac Tester', 'category': 'mac'},
{'name': 'Linux Builder', 'category': 'linux'},
{'name': 'Linux Tester', 'category': 'linux'},
]
c['builders'].extend([
{
'name': spec['name'],
'factory': m_annotator.BaseFactory('webrtc/chromium'),
'category': spec['category'],
'notify_on_missing': True,
} for spec in specs
])
| # Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from buildbot.changes.filter import ChangeFilter
from buildbot.schedulers.basic import SingleBranchScheduler
from master.factory import annotator_factory
m_annotator = annotator_factory.AnnotatorFactory()
def Update(c):
c['schedulers'].append(
SingleBranchScheduler(name='chromium_scheduler',
change_filter=ChangeFilter(project='chromium',
branch='master'),
treeStableTimer=60,
builderNames=[
'Win Builder',
'Mac Builder',
'Linux Builder',
]),
)
specs = [
{'name': 'Win Builder', 'category': 'win'},
{'name': 'WinXP Tester', 'category': 'win'},
{'name': 'Win7 Tester', 'category': 'win'},
{'name': 'Win8 Tester', 'category': 'win'},
{'name': 'Win10 Tester', 'category': 'win'},
{'name': 'Mac Builder', 'category': 'mac'},
{'name': 'Mac Tester', 'category': 'mac'},
{'name': 'Linux Builder', 'recipe': 'chromium', 'category': 'linux'},
{'name': 'Linux Tester', 'recipe': 'chromium', 'category': 'linux'},
]
c['builders'].extend([
{
'name': spec['name'],
'factory': m_annotator.BaseFactory(spec.get('recipe',
'webrtc/chromium')),
'category': spec['category'],
'notify_on_missing': True,
} for spec in specs
])
| Switch chromium.webrtc Linux builders to chromium recipe. | WebRTC: Switch chromium.webrtc Linux builders to chromium recipe.
With https://codereview.chromium.org/1406253003/ landed this is the
first CL in a series of careful rollout to the new recipe.
BUG=538259
TBR=phajdan.jr@chromium.org
Review URL: https://codereview.chromium.org/1508933002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@297884 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | ---
+++
@@ -29,14 +29,15 @@
{'name': 'Win10 Tester', 'category': 'win'},
{'name': 'Mac Builder', 'category': 'mac'},
{'name': 'Mac Tester', 'category': 'mac'},
- {'name': 'Linux Builder', 'category': 'linux'},
- {'name': 'Linux Tester', 'category': 'linux'},
+ {'name': 'Linux Builder', 'recipe': 'chromium', 'category': 'linux'},
+ {'name': 'Linux Tester', 'recipe': 'chromium', 'category': 'linux'},
]
c['builders'].extend([
{
'name': spec['name'],
- 'factory': m_annotator.BaseFactory('webrtc/chromium'),
+ 'factory': m_annotator.BaseFactory(spec.get('recipe',
+ 'webrtc/chromium')),
'category': spec['category'],
'notify_on_missing': True,
} for spec in specs |
a191172016bd6735c5fbb80e130e931f7312e910 | csunplugged/config/urls.py | csunplugged/config/urls.py | """URL configuration for the Django system.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/dev/topics/http/urls/
"""
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from general import views
urlpatterns = i18n_patterns(
url(r"", include("general.urls", namespace="general")),
url(r"^topics/", include("topics.urls", namespace="topics")),
url(r"^resources/", include("resources.urls", namespace="resources")),
url(r"^admin/", include(admin.site.urls)),
)
urlpatterns += [
url(r"^_ah/health", views.health_check),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
url(r"^__debug__/", include(debug_toolbar.urls)),
]
urlpatterns += i18n_patterns(
url(r"^__dev__/", include("dev.urls", namespace="dev")),
)
| """URL configuration for the Django system.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/dev/topics/http/urls/
"""
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from general import views
urlpatterns = i18n_patterns(
url(r"", include("general.urls", namespace="general")),
url(r"^topics/", include("topics.urls", namespace="topics")),
url(r"^resources/", include("resources.urls", namespace="resources")),
url(r"^admin/", include(admin.site.urls)),
)
urlpatterns += [
url(r"^_ah/health", views.health_check),
]
if settings.DEBUG: # pragma: no cover
import debug_toolbar
urlpatterns += [
url(r"^__debug__/", include(debug_toolbar.urls)),
]
urlpatterns += i18n_patterns(
url(r"^__dev__/", include("dev.urls", namespace="dev")),
)
| Add coverage ignore to debug URLs | Add coverage ignore to debug URLs
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | ---
+++
@@ -21,7 +21,7 @@
url(r"^_ah/health", views.health_check),
]
-if settings.DEBUG:
+if settings.DEBUG: # pragma: no cover
import debug_toolbar
urlpatterns += [
url(r"^__debug__/", include(debug_toolbar.urls)), |
9ea01cb2f253fefb675a0bfafd05a06f8fe2aca2 | eventkit_cloud/tasks/scheduled_tasks.py | eventkit_cloud/tasks/scheduled_tasks.py | # -*- coding: utf-8 -*-
from django.utils import timezone
from celery import Task
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
class PurgeUnpublishedExportsTask(Task):
"""
Purge unpublished export tasks after 48 hours.
"""
name = "Purge Unpublished Exports"
def run(self,):
from eventkit_cloud.jobs.models import Job
time_limit = timezone.now() - timezone.timedelta(hours=48)
expired_jobs = Job.objects.filter(created_at__lt=time_limit, published=False)
count = expired_jobs.count()
logger.debug('Purging {0} unpublished exports.'.format(count))
expired_jobs.delete()
| # -*- coding: utf-8 -*-
from django.utils import timezone
from celery import Task
from celery.utils.log import get_task_logger
from celery.app.registry import TaskRegistry
logger = get_task_logger(__name__)
class PurgeUnpublishedExportsTask(Task):
"""
Purge unpublished export tasks after 48 hours.
"""
name = "Purge Unpublished Exports"
def run(self,):
from eventkit_cloud.jobs.models import Job
time_limit = timezone.now() - timezone.timedelta(hours=48)
expired_jobs = Job.objects.filter(created_at__lt=time_limit, published=False)
count = expired_jobs.count()
logger.debug('Purging {0} unpublished exports.'.format(count))
expired_jobs.delete()
TaskRegistry().register(PurgeUnpublishedExportsTask())
| Install celery beat, register tasks (untested) | Install celery beat, register tasks (untested)
| Python | bsd-3-clause | venicegeo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud,venicegeo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud | ---
+++
@@ -3,6 +3,7 @@
from celery import Task
from celery.utils.log import get_task_logger
+from celery.app.registry import TaskRegistry
logger = get_task_logger(__name__)
@@ -22,3 +23,4 @@
logger.debug('Purging {0} unpublished exports.'.format(count))
expired_jobs.delete()
+TaskRegistry().register(PurgeUnpublishedExportsTask()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.