content
stringlengths
128
6.74k
<commit_msg>Tweak syntax for f.close() concision, add typehints<commit_before>from flare.struc import Structure from typing import List from json import dump, load from flare.util import NumpyEncoder def md_trajectory_to_file(filename, structures: List[Structure]): """ Take a list of structures and write them to a json file. :param filename: :param structures: """ f = open(filename, 'w') dump([s.as_dict() for s in structures], f, cls=NumpyEncoder) f.close() def md_trajectory_from_file(filename): """ Read a list of structures from a json file, formatted as in md_trajectory_to_file. :param filename: """ f = open(filename, 'r') structure_list = load(f) structures = [Structure.from_dict(dictionary) for dictionary in structure_list] return structures <commit_after>from flare.struc import Structure from typing import List from json import dump, load from flare.util import NumpyEncoder def md_trajectory_to_file(filename: str, structures: List[Structure]): """ Take a list of structures and write them to a json file. :param filename: :param structures: """ with open(filename, 'w') as f: dump([s.as_dict() for s in structures], f, cls=NumpyEncoder) def md_trajectory_from_file(filename: str): """ Read a list of structures from a json file, formatted as in md_trajectory_to_file. :param filename: """ with open(filename, 'r') as f: structure_list = load(f) structures = [Structure.from_dict(dictionary) for dictionary in structure_list] return structures
<commit_msg>Use the shorter decorator() method .. because they are same for `HttpClient`. <commit_before>package armeria; import brave.Tracing; import com.linecorp.armeria.client.HttpClient; import com.linecorp.armeria.client.HttpClientBuilder; import com.linecorp.armeria.client.tracing.HttpTracingClient; import com.linecorp.armeria.common.HttpRequest; import com.linecorp.armeria.common.HttpResponse; import com.linecorp.armeria.server.Server; import com.linecorp.armeria.server.ServerBuilder; import com.linecorp.armeria.server.logging.LoggingService; import com.linecorp.armeria.server.tracing.HttpTracingService; public class Frontend { public static void main(String[] args) { Tracing tracing = TracingFactory.create("frontend"); HttpClient backendClient = new HttpClientBuilder("http://localhost:9000/") .decorator( HttpRequest.class, HttpResponse.class, HttpTracingClient.newDecorator(tracing, "backend")) .build(); Server server = new ServerBuilder() .http(8081) .service("/", (ctx, res) -> backendClient.get("/api")) .decorator(HttpTracingService.newDecorator(tracing)) .decorator(LoggingService.newDecorator()) .build(); server.start().join(); } } <commit_after>package armeria; import brave.Tracing; import com.linecorp.armeria.client.HttpClient; import com.linecorp.armeria.client.HttpClientBuilder; import com.linecorp.armeria.client.tracing.HttpTracingClient; import com.linecorp.armeria.server.Server; import com.linecorp.armeria.server.ServerBuilder; import com.linecorp.armeria.server.logging.LoggingService; import com.linecorp.armeria.server.tracing.HttpTracingService; public class Frontend { public static void main(String[] args) { Tracing tracing = TracingFactory.create("frontend"); HttpClient backendClient = new HttpClientBuilder("http://localhost:9000/") .decorator(HttpTracingClient.newDecorator(tracing, "backend")) .build(); Server server = new ServerBuilder() .http(8081) .service("/", (ctx, res) -> backendClient.get("/api")) .decorator(HttpTracingService.newDecorator(tracing)) .decorator(LoggingService.newDecorator()) .build(); server.start().join(); } }
<commit_msg>Add API method for question sets list <commit_before>from django.http import HttpResponse def list_question_sets(request): return HttpResponse('Lol, udachi') <commit_after>import json from django.http import HttpResponse from maps.models import QuestionSet def list_question_sets(request): objects = QuestionSet.objects.all() items = [] for obj in objects: items.append({ 'title': obj.title, 'max_duration': obj.max_duration.seconds, 'creator': { 'full_name': obj.creator.get_full_name() } }) return HttpResponse(json.dumps(items))
<commit_msg>Setup: Add long description read straight from README. <commit_before>"""Cloud browser package.""" from setuptools import setup, find_packages from cloud_browser import __version__ # Base packages. MOD_NAME = "cloud_browser" PKGS = [x for x in find_packages() if x.split('.')[0] == MOD_NAME] setup( name="django-cloud-browser", version=__version__, description="Django Cloud Browser application.", long_description="Browser for cloud datastores (Rackspace, AWS, etc.).", url="https://github.com/ryan-roemer/django-cloud-browser", author="Ryan Roemer", author_email="ryan@loose-bits.com", classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet", "Topic :: Internet :: WWW/HTTP :: Site Management", ], install_requires=[ "distribute", ], packages=PKGS, include_package_data=True, ) <commit_after>"""Cloud browser package.""" from __future__ import with_statement import os from setuptools import setup, find_packages from cloud_browser import __version__ ############################################################################### # Base packages. ############################################################################### MOD_NAME = "cloud_browser" PKGS = [x for x in find_packages() if x.split('.')[0] == MOD_NAME] ############################################################################### # Helpers. ############################################################################### def read_file(name): """Read file name (without extension) to string.""" cur_path = os.path.dirname(__file__) exts = ('txt', 'rst') for ext in exts: path = os.path.join(cur_path, '.'.join((name, ext))) if os.path.exists(path): with open(path, 'rb') as file_obj: return file_obj.read() return '' ############################################################################### # Setup. ############################################################################### setup( name="django-cloud-browser", version=__version__, description="Django Cloud Browser application.", long_description=read_file("README"), url="https://github.com/ryan-roemer/django-cloud-browser", author="Ryan Roemer", author_email="ryan@loose-bits.com", classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet", "Topic :: Internet :: WWW/HTTP :: Site Management", ], install_requires=[ "distribute", ], packages=PKGS, include_package_data=True, )
<commit_msg>Fix licence header in newly added file.<commit_before>/** * Copyright 2013 Mat Booth <mbooth@apache.org> */ package com.gpm.calameo; public class SingleDrm { private String ID; private String SubscriptionID; private String SubscriberLogin; private Publication Book; private String Extras; public SingleDrm() { } public String getId() { return ID; } public String getSubscriptionId() { return SubscriptionID; } public String getSubscriberLogin() { return SubscriberLogin; } public Publication getBook() { return Book; } public String getExtras() { return Extras; } @Override public String toString() { return String.format("{ ID: %s, Subscription ID: %s, Subscriber Login: %s, Book: %s, Extras: %s }", getId(), getSubscriptionId(), getSubscriberLogin(), getBook(), getExtras()); } } <commit_after>/* * Copyright 2013 Mat Booth <mbooth@apache.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gpm.calameo; public class SingleDrm { private String ID; private String SubscriptionID; private String SubscriberLogin; private Publication Book; private String Extras; public SingleDrm() { } public String getId() { return ID; } public String getSubscriptionId() { return SubscriptionID; } public String getSubscriberLogin() { return SubscriberLogin; } public Publication getBook() { return Book; } public String getExtras() { return Extras; } @Override public String toString() { return String.format("{ ID: %s, Subscription ID: %s, Subscriber Login: %s, Book: %s, Extras: %s }", getId(), getSubscriptionId(), getSubscriberLogin(), getBook(), getExtras()); } }
<commit_msg>Add more info to pytest header <commit_before>import sys sys._running_pytest = True from sympy.core.cache import clear_cache def pytest_terminal_summary(terminalreporter): if (terminalreporter.stats.get('error', None) or terminalreporter.stats.get('failed', None)): terminalreporter.write_sep(' ', 'DO *NOT* COMMIT!', red=True, bold=True) def pytest_runtest_teardown(): clear_cache() <commit_after>import sys sys._running_pytest = True from sympy.core.cache import clear_cache def pytest_report_header(config): from sympy.utilities.misc import ARCH s = "architecture: %s\n" % ARCH from sympy.core.cache import USE_CACHE s += "cache: %s\n" % USE_CACHE from sympy.polys.domains import GROUND_TYPES s += "ground types: %s\n" % GROUND_TYPES return s def pytest_terminal_summary(terminalreporter): if (terminalreporter.stats.get('error', None) or terminalreporter.stats.get('failed', None)): terminalreporter.write_sep(' ', 'DO *NOT* COMMIT!', red=True, bold=True) def pytest_runtest_teardown(): clear_cache()
<commit_msg>Fix the request.POST, usage of formset and redirect at the end <commit_before>from django.contrib.auth.decorators import permission_required from django.core.paginator import Paginator from django.shortcuts import render, get_object_or_404 from .forms import ReportForm, CopyFormSet from .models import Report @permission_required('reports.add_report', login_url='members:login') def add_report(request): data = request.POST if request else None report_form = ReportForm(data) if report_form.is_valid(): formset = CopyFormSet(data, instance=request.session.get('report_in_creation', Report())) report = report_form.save() request.session['report_in_creation'] = formset.instance = report if formset.is_valid(): formset.save() del request.session['report_in_creation'] return render(request, 'reports/add.html', locals()) def listing(request, page): reports_list = Report.objects.all() paginator = Paginator(reports_list, 30) reports = paginator.page(page) return render(request, 'reports/listing.html', {"reports": reports}) def show(request, id): report = get_object_or_404(Report, id=id) return render(request, 'reports/show.html', locals()) <commit_after>from django.contrib.auth.decorators import permission_required from django.core.paginator import Paginator from django.shortcuts import render, get_object_or_404, redirect from .forms import ReportForm, CopyFormSet from .models import Report @permission_required('reports.add_report', login_url='members:login') def add_report(request): data = request.POST if request.POST else None report_form = ReportForm(data) formset = CopyFormSet(data, instance=request.session.get('report_in_creation', Report())) if report_form.is_valid(): report = report_form.save() request.session['report_in_creation'] = formset.instance = report if formset.is_valid(): formset.save() del request.session['report_in_creation'] return redirect('/members/profile/') return render(request, 'reports/add.html', locals()) def listing(request, page): reports_list = Report.objects.all() paginator = Paginator(reports_list, 30) reports = paginator.page(page) return render(request, 'reports/listing.html', {"reports": reports}) def show(request, id): report = get_object_or_404(Report, id=id) return render(request, 'reports/show.html', locals())
<commit_msg>Add haskell day 3 maze solve <commit_before>module Main where import Data.List -- • Write a function that looks up a hash table value that uses the Maybe monad. Write a hash that stores other hashes, several levels deep. Use the Maybe monad to retrieve an element for a hash key several levels deep. try :: Eq a => a -> [(a, b)] -> Maybe b try _ [] = Nothing try key ((k, v):t) | key == k = Just v | otherwise = try key t -- • Represent a maze in Haskell. You’ll need a Maze type and a Node type, as well as a function to return a node given its coordinates. The node should have a list of exits to other nodes. type Position = (Int, Int) type Node = (Position, [Position]) type Maze = [Node] locate position maze = find (\(pos, _) -> pos == position) maze <commit_after>module Main where import Data.List -- • Write a function that looks up a hash table value that uses the Maybe monad. Write a hash that stores other hashes, several levels deep. Use the Maybe monad to retrieve an element for a hash key several levels deep. try :: Eq a => a -> [(a, b)] -> Maybe b try _ [] = Nothing try key ((k, v):t) | key == k = Just v | otherwise = try key t -- • Represent a maze in Haskell. You’ll need a Maze type and a Node type, as well as a function to return a node given its coordinates. The node should have a list of exits to other nodes. type Position = (Int, Int) data Node = Node Position [Position] deriving Show type Maze = [Node] locate :: Maze -> Position -> Maybe Node locate maze position = find (\(Node pos _) -> pos == position) maze -- • Use a List monad to solve the maze. exits Nothing = [] exits (Just (Node _ exits)) = exits solve :: Maze -> Position -> Position -> Maybe [Position] solve maze start exit = case tryMoves [start] of [] -> Nothing [path] -> Just(reverse path) where tryMoves path@(pos:_) | pos == exit = return path | otherwise = do exit <- (exits(locate maze pos)) \\ path tryMoves (exit:path) -- let maze = [(Node (0, 0) [(0, 1)]), (Node (0, 1) [(0, 0), (1, 1)]), -- (Node (1, 0) []), (Node (1, 1) [(0, 1)])] -- solve maze (0, 0) (1, 1) -- Just [(0,0),(0,1),(1,1)] -- solve maze (0, 0) (1, 0) -- Nothing
<commit_msg>Include generated static content in package manifest <commit_before>from setuptools import setup, find_packages setup(name='git-auto-deploy', version='0.9', url='https://github.com/olipo186/Git-Auto-Deploy', author='Oliver Poignant', author_email='oliver@poignant.se', packages = find_packages(), package_data={'gitautodeploy': ['data/*', 'wwwroot/*']}, entry_points={ 'console_scripts': [ 'git-auto-deploy = gitautodeploy.__main__:main' ] }, install_requires=[ 'lockfile' ], description = "Deploy your GitHub, GitLab or Bitbucket projects automatically on Git push events or webhooks.", long_description = "GitAutoDeploy consists of a HTTP server that listens for Web hook requests sent from GitHub, GitLab or Bitbucket servers. This application allows you to continuously and automatically deploy you projects each time you push new commits to your repository." ) <commit_after>from setuptools import setup, find_packages import os import sys def package_files(package_path, directory_name): paths = [] directory_path = os.path.join(package_path, directory_name) for (path, directories, filenames) in os.walk(directory_path): relative_path = os.path.relpath(path, package_path) for filename in filenames: if filename[0] == ".": continue paths.append(os.path.join(relative_path, filename)) return paths # Get path to project package_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "gitautodeploy") # Get list of data files wwwroot_files = package_files(package_path, "wwwroot") data_files = package_files(package_path, "data") setup(name='git-auto-deploy', version='0.9.1', url='https://github.com/olipo186/Git-Auto-Deploy', author='Oliver Poignant', author_email='oliver@poignant.se', packages = find_packages(), package_data={'gitautodeploy': data_files + wwwroot_files}, entry_points={ 'console_scripts': [ 'git-auto-deploy = gitautodeploy.__main__:main' ] }, install_requires=[ 'lockfile' ], description = "Deploy your GitHub, GitLab or Bitbucket projects automatically on Git push events or webhooks.", long_description = "GitAutoDeploy consists of a HTTP server that listens for Web hook requests sent from GitHub, GitLab or Bitbucket servers. This application allows you to continuously and automatically deploy you projects each time you push new commits to your repository." )
<commit_msg>Add test for open file <commit_before>import os from cffitsio._cfitsio import ffi, lib def test_create_file(tmpdir): filename = str(tmpdir.join('test.fits')) f = ffi.new('fitsfile **') status = ffi.new('int *') lib.fits_create_file(f, filename, status) assert status[0] == 0 assert os.path.isfile(filename) <commit_after>import os from cffitsio._cfitsio import ffi, lib def test_create_file(tmpdir): filename = str(tmpdir.join('test.fits')) f = ffi.new('fitsfile **') status = ffi.new('int *') lib.fits_create_file(f, filename, status) assert status[0] == 0 assert os.path.isfile(filename) def test_open_file(test_file): f = ffi.new('fitsfile **') status = ffi.new('int *') lib.fits_open_file(f, test_file, 0, status) assert status[0] == 0
<commit_msg>Use a filesystem db and add the sites app to fix a test failure. <commit_before>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'formtools', 'tests.wizard.wizardtests', ] SECRET_KEY = 'spam-spam-spam-spam' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'spam-and-eggs' } } MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', ) <commit_after>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/tmp/django-formtools-tests.db', } } INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'formtools', 'tests.wizard.wizardtests', ] SECRET_KEY = 'spam-spam-spam-spam' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'spam-and-eggs' } } MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', )
<commit_msg>Update the argument normalization test Needs to make sure it unpacks the right number of return values. Also since we are changing the input array, it is good to add a check to make sure it is still of the expected type. <commit_before> import pytest import numpy as np import dask.array as da import dask.array.utils as dau import dask_ndfourier._utils @pytest.mark.parametrize( "a, s, n, axis", [ (da.ones((3, 4), chunks=(3, 4)), da.ones((2,), chunks=(2,)), -1, -1), ] ) def test_norm_args(a, s, n, axis): s2, n2, axis2 = dask_ndfourier._utils._norm_args(a, s, n=n, axis=axis) assert isinstance(s2, da.Array) <commit_after> import pytest import numpy as np import dask.array as da import dask.array.utils as dau import dask_ndfourier._utils @pytest.mark.parametrize( "a, s, n, axis", [ (da.ones((3, 4), chunks=(3, 4)), da.ones((2,), chunks=(2,)), -1, -1), ] ) def test_norm_args(a, s, n, axis): a2, s2, n2, axis2 = dask_ndfourier._utils._norm_args(a, s, n=n, axis=axis) assert isinstance(a2, da.Array) assert isinstance(s2, da.Array)
<commit_msg>Fix tests for Python 3 <commit_before>from __future__ import unicode_literals import pytest import types from rakuten_ws.webservice import RakutenWebService from rakuten_ws.base import RakutenAPIResponse @pytest.mark.online def test_response(credentials): ws = RakutenWebService(**credentials) response = ws.ichiba.item.search(keyword="Naruto") assert isinstance(response, RakutenAPIResponse) @pytest.mark.online def test_single_item(credentials): ws = RakutenWebService(**credentials) response = ws.ichiba.item.search(keyword="Naruto") item = response['Items'][0] assert item['itemName'] == 'NARUTO THE BEST (期間生産限定盤) [ (アニメーション) ]' # noqa @pytest.mark.online def test_item_pages(credentials): ws = RakutenWebService(**credentials) response = ws.ichiba.item.search(keyword="Naruto") items = response.pages() # search should also allow to retrieve all the available responses # within a generator assert isinstance(items, types.GeneratorType) # The iteration should switch to the next page assert items.next()['page'] == 1 assert items.next()['page'] == 2 <commit_after>from __future__ import unicode_literals import pytest import types from rakuten_ws.webservice import RakutenWebService from rakuten_ws.base import RakutenAPIResponse @pytest.mark.online def test_response(credentials): ws = RakutenWebService(**credentials) response = ws.ichiba.item.search(keyword="Naruto") assert isinstance(response, RakutenAPIResponse) @pytest.mark.online def test_single_item(credentials): ws = RakutenWebService(**credentials) response = ws.ichiba.item.search(keyword="Naruto") item = response['Items'][0] assert item['itemName'] == 'NARUTO THE BEST (期間生産限定盤) [ (アニメーション) ]' # noqa @pytest.mark.online def test_item_pages(credentials): ws = RakutenWebService(**credentials) response = ws.ichiba.item.search(keyword="Naruto") items = response.pages() # search should also allow to retrieve all the available responses # within a generator assert isinstance(items, types.GeneratorType) # The iteration should switch to the next page assert next(items)['page'] == 1 assert next(items)['page'] == 2
<commit_msg>Test for presence of analytics in minified JS Minifying the JS shortens variable names wherever their scope makes it possible. This means that `GOVUK.analytics.trackPageView` gets shortened to something like `e.t.trackPageView`, and not in a predicatable way. Because the `trackPageView` method could be used by indeterminable other scripts the compiler can't minify it, so testing for just the presence of its name is safe. <commit_before>from nose.tools import assert_equal, assert_true from ...helpers import BaseApplicationTest class TestApplication(BaseApplicationTest): def setup(self): super(TestApplication, self).setup() def test_analytics_code_should_be_in_javascript(self): res = self.client.get('/static/javascripts/application.js') assert_equal(200, res.status_code) assert_true( 'GOVUK.analytics.trackPageview' in res.get_data(as_text=True)) <commit_after>from nose.tools import assert_equal, assert_true from ...helpers import BaseApplicationTest class TestApplication(BaseApplicationTest): def setup(self): super(TestApplication, self).setup() def test_analytics_code_should_be_in_javascript(self): res = self.client.get('/static/javascripts/application.js') assert_equal(200, res.status_code) assert_true( 'trackPageview' in res.get_data(as_text=True))
<commit_msg>Migrate to PlaceholderExpansion from PlaceholderAPI <commit_before>package com.github.games647.fastlogin.bukkit; import java.util.List; import me.clip.placeholderapi.PlaceholderAPI; import me.clip.placeholderapi.PlaceholderHook; import org.bukkit.entity.Player; import org.bukkit.metadata.MetadataValue; public class PremiumPlaceholder extends PlaceholderHook { private final FastLoginBukkit plugin; public PremiumPlaceholder(FastLoginBukkit plugin) { this.plugin = plugin; } @Override public String onPlaceholderRequest(Player player, String variable) { if (player != null && "fastlogin_status".contains(variable)) { List<MetadataValue> metadata = player.getMetadata(plugin.getName()); if (metadata == null) { return "unknown"; } if (metadata.isEmpty()) { return "cracked"; } else { return "premium"; } } return ""; } public static void register(FastLoginBukkit plugin) { PlaceholderAPI.registerPlaceholderHook(plugin, new PremiumPlaceholder(plugin)); } } <commit_after>package com.github.games647.fastlogin.bukkit; import java.util.stream.Collectors; import me.clip.placeholderapi.PlaceholderAPI; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import org.bukkit.entity.Player; public class PremiumPlaceholder extends PlaceholderExpansion { private static final String PLACEHOLDER_VARIABLE = "fastlogin_status"; private final FastLoginBukkit plugin; public PremiumPlaceholder(FastLoginBukkit plugin) { this.plugin = plugin; } public static void register(FastLoginBukkit plugin) { PremiumPlaceholder placeholderHook = new PremiumPlaceholder(plugin); PlaceholderAPI.registerPlaceholderHook(PLACEHOLDER_VARIABLE, placeholderHook); } @Override public String onPlaceholderRequest(Player player, String variable) { if (player != null && PLACEHOLDER_VARIABLE.equals(variable)) { return plugin.getStatus(player.getUniqueId()).name(); } return ""; } @Override public String getIdentifier() { return PLACEHOLDER_VARIABLE; } @Override public String getPlugin() { return plugin.getName(); } @Override public String getAuthor() { return plugin.getDescription().getAuthors().stream().collect(Collectors.joining(", ")); } @Override public String getVersion() { return plugin.getName(); } }
<commit_msg>Fix circular dependency problem with django apps It looks like translation is importing *all other* django apps in the project when it is used from treemap. This means that it will load apps that depend on treemap when it is not finished import treemap. So while it appears that treemap/otm1_migrator/otm_comments have sane, non-circular dependencies on each other, the translation app is causing the circle. I'm pretty sure this is actually a django pattern. Django enjoys including dynamic apps that walk through installed apps and do magic stuff. To compensate, they provide this alternative, string-based import strategy that dynamic apps adhere to. <commit_before>from __future__ import print_function from __future__ import unicode_literals from __future__ import division from threadedcomments.models import ThreadedComment from django.contrib.gis.db import models from treemap.instance import Instance class EnhancedThreadedComment(ThreadedComment): """ This class wraps the ThreadedComment model with moderation specific fields """ # If the comment should be hidden in the default filter view for moderation is_archived = models.BooleanField(default=False) # We could retrieve this through the GenericForeignKey on ThreadedComment, # but it makes things simpler to record instance here. instance = models.ForeignKey(Instance) def save(self, *args, **kwargs): if hasattr(self.content_object, 'instance'): self.instance = self.content_object.instance super(EnhancedThreadedComment, self).save(*args, **kwargs) <commit_after>from __future__ import print_function from __future__ import unicode_literals from __future__ import division from threadedcomments.models import ThreadedComment from django.contrib.gis.db import models class EnhancedThreadedComment(ThreadedComment): """ This class wraps the ThreadedComment model with moderation specific fields """ # If the comment should be hidden in the default filter view for moderation is_archived = models.BooleanField(default=False) # We could retrieve this through the GenericForeignKey on ThreadedComment, # but it makes things simpler to record instance here. instance = models.ForeignKey('treemap.Instance') def save(self, *args, **kwargs): if hasattr(self.content_object, 'instance'): self.instance = self.content_object.instance super(EnhancedThreadedComment, self).save(*args, **kwargs)
<commit_msg>Add extra test cases for blank identifiers <commit_before>package main import "fmt" func a() error { fmt.Println("this function returns an error") return nil } func b() (int, error) { fmt.Println("this function returns an int and an error") return 0, nil } func main() { // Single error return _ = a() a() // Return another value and an error _, _ = b() b() // Method with a single error return x := t{} _ = x.a() x.a() // Method call on a struct member y := u{x} _ = y.t.a() y.t.a() m1 := map[string]func() error{"a": a} _ = m1["a"]() m1["a"]() } <commit_after>package main import "fmt" func a() error { fmt.Println("this function returns an error") return nil } func b() (int, error) { fmt.Println("this function returns an int and an error") return 0, nil } func main() { // Single error return _ = a() a() // Return another value and an error _, _ = b() b() // Method with a single error return x := t{} _ = x.a() x.a() // Method call on a struct member y := u{x} _ = y.t.a() y.t.a() m1 := map[string]func() error{"a": a} _ = m1["a"]() m1["a"]() // Additional cases for assigning errors to blank identifier z, _ := b() _, w := a(), 5 }
<commit_msg>Mark package as OS independent <commit_before>from setuptools import setup, find_packages import os def readfile(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read() setup( name="imagesort", version="0.2.0", packages=find_packages(), install_requires=[ 'ExifRead>=1.4.0', ], include_package_data=True, author="Børge Lanes", author_email="borge.lanes@gmail.com", description=('Organize image files by date taken'), long_description=readfile("README.rst"), license="MIT", keywords="media", url="https://github.com/leinz/imagesort", entry_points={ 'console_scripts': [ 'imagesort = imagesort.imagesort:main', ] }, classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Multimedia', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], ) <commit_after>from setuptools import setup, find_packages import os def readfile(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read() setup( name="imagesort", version="0.2.0", packages=find_packages(), install_requires=[ 'ExifRead>=1.4.0', ], include_package_data=True, author="Børge Lanes", author_email="borge.lanes@gmail.com", description=('Organize image files by date taken'), long_description=readfile("README.rst"), license="MIT", keywords="media", url="https://github.com/leinz/imagesort", entry_points={ 'console_scripts': [ 'imagesort = imagesort.imagesort:main', ] }, classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Multimedia', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], )
<commit_msg>Add flake8 to installation dependencies <commit_before>import os from setuptools import find_packages from setuptools import setup import sys sys.path.insert(0, os.path.abspath('lib')) exec(open('lib/ansiblereview/version.py').read()) setup( name='ansible-review', version=__version__, description=('reviews ansible playbooks, roles and inventory and suggests improvements'), keywords='ansible, code review', author='Will Thames', author_email='will@thames.id.au', url='https://github.com/willthames/ansible-review', package_dir={'': 'lib'}, packages=find_packages('lib'), zip_safe=False, install_requires=['ansible-lint>=3.0.0', 'pyyaml', 'appdirs', 'unidiff'], scripts=['bin/ansible-review'], classifiers=[ 'License :: OSI Approved :: MIT License', ], test_suite="test" ) <commit_after>import os from setuptools import find_packages from setuptools import setup import sys sys.path.insert(0, os.path.abspath('lib')) exec(open('lib/ansiblereview/version.py').read()) setup( name='ansible-review', version=__version__, description=('reviews ansible playbooks, roles and inventory and suggests improvements'), keywords='ansible, code review', author='Will Thames', author_email='will@thames.id.au', url='https://github.com/willthames/ansible-review', package_dir={'': 'lib'}, packages=find_packages('lib'), zip_safe=False, install_requires=['ansible-lint>=3.0.0', 'pyyaml', 'appdirs', 'unidiff', 'flake8'], scripts=['bin/ansible-review'], classifiers=[ 'License :: OSI Approved :: MIT License', ], test_suite="test" )
<commit_msg>Enable reindexing with v2 reindexer <commit_before>from django.core.management import BaseCommand, CommandError from corehq.pillows.case import get_couch_case_reindexer, get_sql_case_reindexer from corehq.pillows.xform import get_couch_form_reindexer, get_sql_form_reindexer class Command(BaseCommand): args = 'index' help = 'Reindex a pillowtop index' def handle(self, index, *args, **options): reindex_fns = { 'case': get_couch_case_reindexer, 'form': get_couch_form_reindexer, 'sql-case': get_sql_case_reindexer, 'sql-form': get_sql_form_reindexer, } if index not in reindex_fns: raise CommandError('Supported indices to reindex are: {}'.format(','.join(reindex_fns.keys()))) reindexer = reindex_fns[index]() reindexer.reindex() <commit_after>from django.core.management import BaseCommand, CommandError from corehq.pillows.case import get_couch_case_reindexer, get_sql_case_reindexer from corehq.pillows.case_search import get_couch_case_search_reindexer from corehq.pillows.xform import get_couch_form_reindexer, get_sql_form_reindexer class Command(BaseCommand): args = 'index' help = 'Reindex a pillowtop index' def handle(self, index, *args, **options): reindex_fns = { 'case': get_couch_case_reindexer, 'form': get_couch_form_reindexer, 'sql-case': get_sql_case_reindexer, 'sql-form': get_sql_form_reindexer, 'case-search': get_couch_case_search_reindexer } if index not in reindex_fns: raise CommandError('Supported indices to reindex are: {}'.format(','.join(reindex_fns.keys()))) reindexer = reindex_fns[index]() reindexer.reindex()
<commit_msg>Add kwarg to load function to distinguish from full install The load function is used for a full install and thus always adds general configuration lines to the loader file, but we don't want that for plugin installation. <commit_before>from __future__ import print_function import os import sys import pkg_resources def load(plugins=()): try: version = pkg_resources.get_distribution("virtualfish").version commands = ["set -g VIRTUALFISH_VERSION {}".format(version)] except pkg_resources.DistributionNotFound: commands = [] base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) commands += [ "set -g VIRTUALFISH_PYTHON_EXEC {}".format(sys.executable), "source {}".format(os.path.join(base_path, "virtual.fish")), ] for plugin in plugins: path = os.path.join(base_path, plugin + ".fish") if os.path.exists(path): commands.append("source {}".format(path)) else: raise ValueError("Plugin does not exist: " + plugin) commands.append("emit virtualfish_did_setup_plugins") return commands <commit_after>from __future__ import print_function import os import sys import pkg_resources def load(plugins=(), full_install=True): try: version = pkg_resources.get_distribution("virtualfish").version commands = ["set -g VIRTUALFISH_VERSION {}".format(version)] except pkg_resources.DistributionNotFound: commands = [] base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if full_install: commands += [ "set -g VIRTUALFISH_PYTHON_EXEC {}".format(sys.executable), "source {}".format(os.path.join(base_path, "virtual.fish")), ] else: commands = [] for plugin in plugins: path = os.path.join(base_path, plugin + ".fish") if os.path.exists(path): commands.append("source {}".format(path)) else: raise ValueError("Plugin does not exist: " + plugin) if full_install: commands.append("emit virtualfish_did_setup_plugins") return commands
<commit_msg>Fix memcache hosts setting from env Before this fix if one had set OS env vars for both CLUSTER_SERVERS and MEMCACHE_HOSTS the value of later would override the former and the graphite web application fails to show any metrics. <commit_before>import os from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') if os.getenv("MEMCACHE_HOSTS"): CLUSTER_SERVERS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now()) <commit_after>import os from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') if os.getenv("MEMCACHE_HOSTS"): MEMCACHE_HOSTS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now())
<commit_msg>Add guard for parallel kwarg on 32-bit Windows <commit_before> from hypothesis import given from hypothesis.strategies import integers from numba import jit import numpy as np @jit(nopython=True, parallel=True) def get(n): return np.ones((n,1), dtype=np.float64) @given(integers(min_value=10, max_value=100000)) def test_all_ones(x): """ We found one of the scaling tests failing on OS X with numba 0.35, but it passed on other platforms, and passed consistently with numba 0.36. The issue appears to be the same as numba#2609 https://github.com/numba/numba/issues/2609 so we've taken the minimal repro from that issue and are using it as a unit-test here. """ result = get(x) expected = np.ones((x, 1), dtype=np.float64) assert np.allclose(expected, result) if __name__ == '__main__': import pytest pytest.main([__file__]) <commit_after> import sys from hypothesis import given from hypothesis.strategies import integers from numba import jit import numpy as np # Parallel not supported on 32-bit Windows parallel = not (sys.platform == 'win32') @jit(nopython=True, parallel=True) def get(n): return np.ones((n,1), dtype=np.float64) @given(integers(min_value=10, max_value=100000)) def test_all_ones(x): """ We found one of the scaling tests failing on OS X with numba 0.35, but it passed on other platforms, and passed consistently with numba 0.36. The issue appears to be the same as numba#2609 https://github.com/numba/numba/issues/2609 so we've taken the minimal repro from that issue and are using it as a unit-test here. """ result = get(x) expected = np.ones((x, 1), dtype=np.float64) assert np.allclose(expected, result) if __name__ == '__main__': import pytest pytest.main([__file__])
<commit_msg>Set root view depending on what views are enabled <commit_before>"""Root URL routing""" from django.conf.urls.defaults import patterns from django.conf.urls.static import static from django.views.generic import TemplateView from kitchen.dashboard import api import kitchen.settings as settings urlpatterns = patterns('', (r'^$', 'kitchen.dashboard.views.list'), (r'^virt/$', 'kitchen.dashboard.views.virt'), (r'^graph/$', 'kitchen.dashboard.views.graph'), (r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'), (r'^api/nodes/(?P<name>\w+)$', api.get_node), (r'^api/nodes', api.get_nodes), (r'^api/roles', api.get_roles), (r'^404', TemplateView.as_view(template_name="404.html")), ) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) <commit_after>"""Root URL routing""" from django.conf.urls.defaults import patterns from django.conf.urls.static import static from django.views.generic import TemplateView from kitchen.dashboard import api import kitchen.settings as settings if settings.SHOW_LIST_VIEW: root_view = 'kitchen.dashboard.views.list' elif settings.SHOW_VIRT_VIEW: root_view = 'kitchen.dashboard.views.virt' elif settings.SHOW_GRAPH_VIEW: root_view = 'kitchen.dashboard.views.graph' else: raise Exception("No views enabled! Please edit settings.py.") urlpatterns = patterns('', (r'^$', root_view), (r'^virt/$', 'kitchen.dashboard.views.virt'), (r'^graph/$', 'kitchen.dashboard.views.graph'), (r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'), (r'^api/nodes/(?P<name>\w+)$', api.get_node), (r'^api/nodes', api.get_nodes), (r'^api/roles', api.get_roles), (r'^404', TemplateView.as_view(template_name="404.html")), ) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
<commit_msg>Fix encoding error when printing messages Some messages that will be printed will contain utf-8 chars, e.g. Pokestops in European locations.<commit_before> import struct from math import cos, asin, sqrt def distance(lat1, lon1, lat2, lon2): p = 0.017453292519943295 a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2 return 12742 * asin(sqrt(a)) * 1000 def i2f(int): return struct.unpack('<d', struct.pack('<Q', int))[0] def print_green(message): print('\033[92m' + message + '\033[0m'); def print_yellow(message): print('\033[93m' + message + '\033[0m'); def print_red(message): print('\033[91m' + message + '\033[0m'); <commit_after> import struct from math import cos, asin, sqrt def distance(lat1, lon1, lat2, lon2): p = 0.017453292519943295 a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2 return 12742 * asin(sqrt(a)) * 1000 def i2f(int): return struct.unpack('<d', struct.pack('<Q', int))[0] def print_green(message): print(u'\033[92m' + message.decode('utf-8') + '\033[0m'); def print_yellow(message): print(u'\033[93m' + message.decode('utf-8') + '\033[0m'); def print_red(message): print(u'\033[91m' + message.decode('utf-8') + '\033[0m');
<commit_msg>Add pillar data to default renderer <commit_before>''' The default rendering engine, process yaml with the jinja2 templating engine This renderer will take a yaml file with the jinja2 template and render it to a high data format for salt states. ''' # Import Python Modules import os # Import thirt party modules import yaml try: yaml.Loader = yaml.CLoader yaml.Dumper = yaml.CDumper except: pass # Import Salt libs from salt.utils.jinja import get_template def render(template_file, env='', sls=''): ''' Render the data passing the functions and grains into the rendering system ''' if not os.path.isfile(template_file): return {} passthrough = {} passthrough['salt'] = __salt__ passthrough['grains'] = __grains__ passthrough['env'] = env passthrough['sls'] = sls template = get_template(template_file, __opts__, env) yaml_data = template.render(**passthrough) return yaml.safe_load(yaml_data) <commit_after>''' The default rendering engine, process yaml with the jinja2 templating engine This renderer will take a yaml file with the jinja2 template and render it to a high data format for salt states. ''' # Import Python Modules import os # Import thirt party modules import yaml try: yaml.Loader = yaml.CLoader yaml.Dumper = yaml.CDumper except: pass # Import Salt libs from salt.utils.jinja import get_template def render(template_file, env='', sls=''): ''' Render the data passing the functions and grains into the rendering system ''' if not os.path.isfile(template_file): return {} passthrough = {} passthrough['salt'] = __salt__ passthrough['grains'] = __grains__ passthrough['pillar'] = __pillar__ passthrough['env'] = env passthrough['sls'] = sls template = get_template(template_file, __opts__, env) yaml_data = template.render(**passthrough) return yaml.safe_load(yaml_data)
<commit_msg>UsbDk: Introduce USB target raw device accessor Signed-off-by: Dmitry Fleytman <f50f56ffad4b379c2a89812e98b14900ef87e9ea@redhat.com> <commit_before> class CWdfUsbInterface; class CWdfUsbTarget { public: CWdfUsbTarget(); ~CWdfUsbTarget(); NTSTATUS Create(WDFDEVICE Device); void DeviceDescriptor(USB_DEVICE_DESCRIPTOR &Descriptor); NTSTATUS ConfigurationDescriptor(UCHAR Index, PUSB_CONFIGURATION_DESCRIPTOR Descriptor, PULONG TotalLength); NTSTATUS SetInterfaceAltSetting(UCHAR InterfaceIdx, UCHAR AltSettingIdx); private: WDFDEVICE m_Device = WDF_NO_HANDLE; WDFUSBDEVICE m_UsbDevice = WDF_NO_HANDLE; CObjHolder<CWdfUsbInterface> m_Interfaces; UCHAR m_NumInterfaces = 0; CWdfUsbTarget(const CWdfUsbTarget&) = delete; CWdfUsbTarget& operator= (const CWdfUsbTarget&) = delete; }; <commit_after> class CWdfUsbInterface; class CWdfUsbTarget { public: CWdfUsbTarget(); ~CWdfUsbTarget(); NTSTATUS Create(WDFDEVICE Device); void DeviceDescriptor(USB_DEVICE_DESCRIPTOR &Descriptor); NTSTATUS ConfigurationDescriptor(UCHAR Index, PUSB_CONFIGURATION_DESCRIPTOR Descriptor, PULONG TotalLength); NTSTATUS SetInterfaceAltSetting(UCHAR InterfaceIdx, UCHAR AltSettingIdx); operator WDFUSBDEVICE () const { return m_UsbDevice; } private: WDFDEVICE m_Device = WDF_NO_HANDLE; WDFUSBDEVICE m_UsbDevice = WDF_NO_HANDLE; CObjHolder<CWdfUsbInterface> m_Interfaces; UCHAR m_NumInterfaces = 0; CWdfUsbTarget(const CWdfUsbTarget&) = delete; CWdfUsbTarget& operator= (const CWdfUsbTarget&) = delete; };
<commit_msg>Add error if latest is passed to deploy. Also check if the path exist before meaking the symlink. <commit_before>from fabric.api import run, env, roles from fabric.contrib.project import rsync_project import sys sys.path.append("source") import conf env.roledefs = { 'web': ['bokeh.pydata.org'] } env.user = "bokeh" @roles('web') def deploy(v=None): if v is None: v = conf.version # make a backup of the old directory run("rm -rf /www/bokeh/en/%s.bak" % v) run("mkdir -p /www/bokeh/en/%s" % v) run("cp -ar /www/bokeh/en/%s /www/bokeh/en/%s.bak" % (v, v)) rsync_project( local_dir="_build/html/", remote_dir="/www/bokeh/en/%s" % v, delete=True ) # set permissions run("chmod -R g+w /www/bokeh/en/%s" % v) @roles('web') def latest(v=None): if v is None: raise RuntimeError("You need to specify version number: fab latest:x.x.x") # switch the current symlink to new docs run("rm /www/bokeh/en/latest") run("ln -s /www/bokeh/en/%s /www/bokeh/en/latest" % v) <commit_after>from fabric.api import run, env, roles from fabric.contrib.files import exists from fabric.contrib.project import rsync_project import sys sys.path.append("source") import conf env.roledefs = { 'web': ['bokeh.pydata.org'] } env.user = "bokeh" @roles('web') def deploy(v=None): if v is None: v = conf.version elif v == "latest": raise RuntimeError("You can not pass 'latest' as fab argument. Use " "fab latest:x.x.x instead.") # make a backup of the old directory run("rm -rf /www/bokeh/en/%s.bak" % v) run("mkdir -p /www/bokeh/en/%s" % v) run("cp -ar /www/bokeh/en/%s /www/bokeh/en/%s.bak" % (v, v)) rsync_project( local_dir="_build/html/", remote_dir="/www/bokeh/en/%s" % v, delete=True ) # set permissions run("chmod -R g+w /www/bokeh/en/%s" % v) @roles('web') def latest(v=None): if v is None: raise RuntimeError("You need to specify a version number: fab latest:x.x.x") if exists("/www/bokeh/en/%s" % v): # switch the current symlink to new docs run("rm /www/bokeh/en/latest") run("ln -s /www/bokeh/en/%s /www/bokeh/en/latest" % v) else: raise RuntimeError("We did not detect a %s docs version, please use " "fab deploy:%s first." % v)
<commit_msg>Set parameters of serial class to match with kilt <commit_before>import time import serial # configure the serial connections (the parameters differs on the # device you are connecting to) class Bumper(object): def __init__(self): try: self.ser = serial.Serial( port="/dev/ttyS0", baudrate=9600, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_TWO, bytesize=serial.SEVENBITS ) except Exception: print("Bad initialisation! Check the configuration of " "the serial port!") exit() self.ser.open() self.ser.isOpen() def loop(self): input=1 while 1 : # get keyboard input input = raw_input(">> ") # Python 3 users # input = input(">> ") if input == "exit": self.ser.close() exit() else: # send the character to the device # (note that I happend a \r\n carriage return and line feed to # the characters - this is requested by my device) self.ser.write(input + "\r\n") out = "" # let's wait one second before reading output (let's give # device time to answer) time.sleep(1) while self.ser.inWaiting() > 0: out += self.ser.read(1) if out != "": print ">> " + out def main(): b = Bumper() b.loop() if __name__ == "__main__": main() <commit_after>import time import serial # configure the serial connections (the parameters differs on the # device you are connecting to) class Bumper(object): def __init__(self): try: self.ser = serial.Serial( port="/dev/ttyS0", baudrate=38400, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS ) except Exception: print("Bad initialisation! Check the configuration of " "the serial port!") exit() self.ser.open() self.ser.isOpen() def loop(self): input=1 while 1 : # get keyboard input input = raw_input(">> ") # Python 3 users # input = input(">> ") if input == "exit": self.ser.close() exit() else: # send the character to the device # (note that I happend a \r\n carriage return and line feed to # the characters - this is requested by my device) self.ser.write(input + "\r\n") out = "" # let's wait one second before reading output (let's give # device time to answer) time.sleep(1) while self.ser.inWaiting() > 0: out += self.ser.read(1) if out != "": print ">> " + out def main(): b = Bumper() b.loop() if __name__ == "__main__": main()
<commit_msg>Add simple UI for first example <commit_before>package org.kikermo.blepotcontroller.activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.SeekBar; import android.widget.TextView; import org.kikermo.blepotcontroller.R; public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener { private TextView value; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); value = (TextView) findViewById(R.id.value); ((SeekBar)findViewById(R.id.pot)).setOnSeekBarChangeListener(this); } @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } } <commit_after>package org.kikermo.blepotcontroller.activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.SeekBar; import android.widget.TextView; import org.kikermo.blepotcontroller.R; public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener { private TextView value; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); value = (TextView) findViewById(R.id.value); ((SeekBar) findViewById(R.id.pot)).setOnSeekBarChangeListener(this); } @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { value.setText(i + "%"); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }
<commit_msg>Print better output on acceptance test assertion failure <commit_before>package helper import ( "encoding/json" "testing" ) // Asserts that the request did not return an error. // Optionally perform some checks only if the request did not fail func AssertRequestOk(t *testing.T, response interface{}, err error, check_fn func()) { if err != nil { response_json, _ := json.MarshalIndent(response, "", " ") t.Fatalf("Failed to perform request, because %#v. Response:\n%s", err, response_json) } else { if check_fn != nil { check_fn() } } } // Asserts that the request _did_ return an error. // Optionally perform some checks only if the request failed func AssertRequestFail(t *testing.T, response interface{}, err error, check_fn func()) { if err == nil { response_json, _ := json.MarshalIndent(response, "", " ") t.Fatalf("Request succeeded unexpectedly. Response:\n%s", response_json) } else { if check_fn != nil { check_fn() } } } <commit_after>package helper import ( "encoding/json" "testing" ) // Asserts that the request did not return an error. // Optionally perform some checks only if the request did not fail func AssertRequestOk(t *testing.T, response interface{}, err error, check_fn func()) { if err != nil { response_json, _ := json.MarshalIndent(response, "", " ") errorPayload, _ := json.MarshalIndent(err, "", " ") t.Fatalf("Failed to perform request, because %s. Response:\n%s", errorPayload, response_json) } else { if check_fn != nil { check_fn() } } } // Asserts that the request _did_ return an error. // Optionally perform some checks only if the request failed func AssertRequestFail(t *testing.T, response interface{}, err error, check_fn func()) { if err == nil { response_json, _ := json.MarshalIndent(response, "", " ") t.Fatalf("Request succeeded unexpectedly. Response:\n%s", response_json) } else { if check_fn != nil { check_fn() } } }
<commit_msg>Add AJAX call sample using axios <commit_before>import * as Vue from "vue"; import Component from "vue-class-component"; @Component({ name: "Hello", }) export default class Hello extends Vue { msg: string = "Welcome to Your Vue.js App"; // created (): void { // axios // .get('/api/hello') // .then((res) => { // this.msg = res.data.message // }) // .catch((ex) => console.log(ex)) // } } <commit_after>import * as Vue from "vue"; import Component from "vue-class-component"; import axios from "axios"; @Component({ name: "Hello", }) export default class Hello extends Vue { msg: string = "Welcome to Your Vue.js App"; created (): void { axios .get("/api/hello") .then((res) => { this.msg = res.data.message; }) .catch((ex) => console.log(ex)) } }
<commit_msg>Include the eval'd node type in the async return <commit_before>from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from ocradmin.ocrtasks.models import OcrTask from ocradmin.plugins.manager import ModuleManager import logging logger = logging.getLogger(__name__) import simplejson import tasks def query(request): """ Query plugin info. This returns a list of available OCR engines and an URL that can be queries when one of them is selected. """ stages=request.GET.getlist("stage") return HttpResponse( ModuleManager.get_json(*stages), mimetype="application/json") def runscript(request): """ Execute a script (sent as JSON). """ evalnode = request.POST.get("node", "") jsondata = request.POST.get("script", simplejson.dumps({"arse":"spaz"})) script = simplejson.loads(jsondata) async = OcrTask.run_celery_task("run.script", evalnode, script, untracked=True, asyncronous=True, queue="interactive") out = dict(task_id=async.task_id, status=async.status, results=async.result) return HttpResponse(simplejson.dumps(out), mimetype="application/json") <commit_after>from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from ocradmin.ocrtasks.models import OcrTask from ocradmin.plugins.manager import ModuleManager import logging logger = logging.getLogger(__name__) import simplejson import tasks def query(request): """ Query plugin info. This returns a list of available OCR engines and an URL that can be queries when one of them is selected. """ stages=request.GET.getlist("stage") return HttpResponse( ModuleManager.get_json(*stages), mimetype="application/json") def runscript(request): """ Execute a script (sent as JSON). """ evalnode = request.POST.get("node", "") jsondata = request.POST.get("script", simplejson.dumps({"arse":"spaz"})) script = simplejson.loads(jsondata) async = OcrTask.run_celery_task("run.script", evalnode, script, untracked=True, asyncronous=True, queue="interactive") out = dict( node=evalnode, task_id=async.task_id, status=async.status, results=async.result ) return HttpResponse(simplejson.dumps(out), mimetype="application/json")
<commit_msg>Add an instance profile for container instances <commit_before>from troposphere import ( Parameter, Ref, ) from troposphere.ecs import ( Cluster, ) from .template import template container_instance_type = Ref(template.add_parameter(Parameter( "ContainerInstanceType", Description="The container instance type", Type="String", Default="t2.micro", AllowedValues=["t2.micro", "t2.small", "t2.medium"] ))) template.add_mapping("ECSRegionMap", { "eu-west-1": {"AMI": "ami-4e6ffe3d"}, "us-east-1": {"AMI": "ami-8f7687e2"}, "us-west-2": {"AMI": "ami-84b44de4"}, }) # ECS cluster cluster = Cluster( "Cluster", template=template, ) <commit_after>from troposphere import ( iam, Parameter, Ref, ) from troposphere.ecs import ( Cluster, ) from .template import template container_instance_type = Ref(template.add_parameter(Parameter( "ContainerInstanceType", Description="The container instance type", Type="String", Default="t2.micro", AllowedValues=["t2.micro", "t2.small", "t2.medium"] ))) template.add_mapping("ECSRegionMap", { "eu-west-1": {"AMI": "ami-4e6ffe3d"}, "us-east-1": {"AMI": "ami-8f7687e2"}, "us-west-2": {"AMI": "ami-84b44de4"}, }) # ECS cluster cluster = Cluster( "Cluster", template=template, ) # ECS container role container_instance_role = iam.Role( "ContainerInstanceRole", template=template, AssumeRolePolicyDocument=dict(Statement=[dict( Effect="Allow", Principal=dict(Service=["ec2.amazonaws.com"]), Action=["sts:AssumeRole"], )]), Path="/", Policies=[ ] ) # ECS container instance profile container_instance_profile = iam.InstanceProfile( "ContainerInstanceProfile", template=template, Path="/", Roles=[Ref(container_instance_role)], )
<commit_msg>Update sample spring security config Disabling csrf: See https://docs.spring.io/spring-security/site/docs/5.3.0.RELEASE/reference/html5/#csrf-when > Our recommendation is to use CSRF protection for any request that could be processed by a browser > by normal users. If you are only creating a service that is used by non-browser clients, > you will likely want to disable CSRF protection. When CSRF is not explicitly disable, OSB endpoint with PUT/POST http methods get rejected Using noop password encoder See https://github.com/spring-cloud/spring-cloud-open-service-broker/issues/80#issuecomment-390252132 <commit_before>package com.example.servicebroker; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @EnableWebSecurity public class ExampleSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/v2/**").hasRole("ADMIN") .and() .httpBasic(); } @Bean public InMemoryUserDetailsManager userDetailsService() { return new InMemoryUserDetailsManager(adminUser()); } private UserDetails adminUser() { return User .withUsername("admin") .password("supersecret") .roles("ADMIN") .build(); } } <commit_after>package com.example.servicebroker; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @EnableWebSecurity public class ExampleSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/v2/**").hasRole("ADMIN") .and() .httpBasic(); } @Bean public InMemoryUserDetailsManager userDetailsService() { return new InMemoryUserDetailsManager(adminUser()); } private UserDetails adminUser() { return User .withUsername("admin") .password("{noop}supersecret") .roles("ADMIN") .build(); } }
<commit_msg>Change GroupSerializer to display attributes as strings <commit_before>from rest_framework import serializers from sigma_core.models.group import Group class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group <commit_after>from rest_framework import serializers from sigma_core.models.group import Group class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group visibility = serializers.SerializerMethodField() membership_policy = serializers.SerializerMethodField() validation_policy = serializers.SerializerMethodField() type = serializers.SerializerMethodField() def get_visibility(self, obj): return obj.get_visibility_display() def get_membership_policy(self, obj): return obj.get_membership_policy_display() def get_validation_policy(self, obj): return obj.get_validation_policy_display() def get_type(self, obj): return obj.get_type_display()
<commit_msg>Create a context even if we aren't using it just at the moment <commit_before>package com.oreilly.rdf.tenuki.jaxrs; import javax.ws.rs.GET; import javax.ws.rs.Path; import com.sun.jersey.api.view.Viewable; @Path("/") public class UIResource { @GET public Viewable landingPage() { return new Viewable("/templates/test.vm"); } } <commit_after>package com.oreilly.rdf.tenuki.jaxrs; import javax.ws.rs.GET; import javax.ws.rs.Path; import org.apache.velocity.VelocityContext; import org.apache.velocity.context.Context; import com.sun.jersey.api.view.Viewable; @Path("/") public class UIResource { @GET public Viewable landingPage() { Context c = new VelocityContext(); return new Viewable("/templates/test.vm", c); } }
<commit_msg>Update changesNotifier to only call underlying Notifier if repos is non-empty <commit_before>// Copyright 2015, David Howden // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "log" "sort" "time" ) type Notifier interface { Notify(map[string]time.Time) error } type logNotifier struct{} func (logNotifier) Notify(repos map[string]time.Time) error { keys := make([]string, 0, len(repos)) for k := range repos { keys = append(keys, k) } sort.Sort(sort.StringSlice(keys)) for _, k := range keys { log.Printf("%v\t: %v", k, repos[k]) } return nil } type changesNotifier struct { Notifier last map[string]time.Time } func (d changesNotifier) Notify(repos map[string]time.Time) error { changes := make(map[string]time.Time) for k, v := range repos { if d.last[k] != v { changes[k] = v d.last[k] = v } } return d.Notifier.Notify(changes) } <commit_after>// Copyright 2015, David Howden // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "log" "sort" "time" ) type Notifier interface { Notify(map[string]time.Time) error } type logNotifier struct{} func (logNotifier) Notify(repos map[string]time.Time) error { keys := make([]string, 0, len(repos)) for k := range repos { keys = append(keys, k) } sort.Sort(sort.StringSlice(keys)) for _, k := range keys { log.Printf("%v\t: %v", k, repos[k]) } return nil } type changesNotifier struct { Notifier last map[string]time.Time } func (d changesNotifier) Notify(repos map[string]time.Time) error { changes := make(map[string]time.Time) for k, v := range repos { if d.last[k] != v { changes[k] = v d.last[k] = v } } if len(changes) == 0 { return nil } return d.Notifier.Notify(changes) }
<commit_msg>Return empty at the right place <commit_before>package de.stephanlindauer.criticalmaps.vo.chat; import com.squareup.okhttp.internal.Util; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Date; import de.stephanlindauer.criticalmaps.utils.AeSimpleSHA1; import de.stephanlindauer.criticalmaps.interfaces.IChatMessage; public class OutgoingChatMessage implements IChatMessage { private final Date timestamp; private final String urlEncodedMessage; private final String identifier; private final String message; public OutgoingChatMessage(String message) { this.message = message; this.urlEncodedMessage = urlEncodeMessage(message); this.timestamp = new Date(); this.identifier = AeSimpleSHA1.SHA1(message + Math.random()); } public Date getTimestamp() { return timestamp; } public String getUrlEncodedMessage() { return urlEncodedMessage; } public String getMessage() { return message; } public String getIdentifier() { return identifier; } private String urlEncodeMessage(String messageToEncode) { try { return URLEncoder.encode(messageToEncode, Util.UTF_8.name()); } catch (UnsupportedEncodingException e) { } return ""; } } <commit_after>package de.stephanlindauer.criticalmaps.vo.chat; import com.squareup.okhttp.internal.Util; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Date; import de.stephanlindauer.criticalmaps.utils.AeSimpleSHA1; import de.stephanlindauer.criticalmaps.interfaces.IChatMessage; public class OutgoingChatMessage implements IChatMessage { private final Date timestamp; private final String urlEncodedMessage; private final String identifier; private final String message; public OutgoingChatMessage(String message) { this.message = message; this.urlEncodedMessage = urlEncodeMessage(message); this.timestamp = new Date(); this.identifier = AeSimpleSHA1.SHA1(message + Math.random()); } public Date getTimestamp() { return timestamp; } public String getUrlEncodedMessage() { return urlEncodedMessage; } public String getMessage() { return message; } public String getIdentifier() { return identifier; } private String urlEncodeMessage(String messageToEncode) { try { return URLEncoder.encode(messageToEncode, Util.UTF_8.name()); } catch (UnsupportedEncodingException e) { return ""; } } }
<commit_msg>kernel: Add alignment for 'vfork' task resource <commit_before>/** * @file res_vfork.c * @brief Task resource for vfork * @date May 16, 2014 * @author Anton Bondarev */ #include <stddef.h> #include <setjmp.h> #include <kernel/task.h> #include <kernel/task/resource.h> #include <kernel/task/resource/task_vfork.h> TASK_RESOURCE_DEF(task_vfork_desc, struct task_vfork); static void task_vfork_init(const struct task *task, void *vfork_buff) { task_vfork_end((struct task *)task); } static int task_vfork_inherit(const struct task *task, const struct task *parent) { return 0; } static size_t task_vfork_offset; static const struct task_resource_desc task_vfork_desc = { .init = task_vfork_init, .inherit = task_vfork_inherit, .resource_size = sizeof(struct task_vfork), .resource_offset = &task_vfork_offset }; struct task_vfork *task_resource_vfork(const struct task *task) { assert(task != NULL); return (void *)task->resources + task_vfork_offset; } <commit_after>/** * @file res_vfork.c * @brief Task resource for vfork * @date May 16, 2014 * @author Anton Bondarev */ #include <stddef.h> #include <setjmp.h> #include <util/binalign.h> #include <kernel/task.h> #include <kernel/task/resource.h> #include <kernel/task/resource/task_vfork.h> TASK_RESOURCE_DEF(task_vfork_desc, struct task_vfork); static void task_vfork_init(const struct task *task, void *vfork_buff) { task_vfork_end((struct task *)task); } static int task_vfork_inherit(const struct task *task, const struct task *parent) { return 0; } static size_t task_vfork_offset; static const struct task_resource_desc task_vfork_desc = { .init = task_vfork_init, .inherit = task_vfork_inherit, .resource_size = sizeof(struct task_vfork), .resource_offset = &task_vfork_offset, }; struct task_vfork *task_resource_vfork(const struct task *task) { size_t offset; assert(task != NULL); offset = (size_t)((void *)task->resources + task_vfork_offset); #ifdef PT_REGS_ALIGN return (void *)binalign_bound(offset, PT_REGS_ALIGN); #else return (void *)offset; #endif }
<commit_msg>Apply review suggestion from @raccube <commit_before>import Rails from '@rails/ujs'; import I18n from '../../../legacy/i18n'; export function createListHandler(event: Event): void { const button = event.target as HTMLButtonElement; const input = document.querySelector<HTMLInputElement>('input#new-list-name'); Rails.ajax({ url: '/ajax/create_list', type: 'POST', data: new URLSearchParams({ name: input.value, user: button.dataset.user }).toString(), success: (data) => { if (data.success) { document.querySelector('#lists-list ul.list-group').insertAdjacentHTML('beforeend', data.render); } window['showNotification'](data.message, data.success); }, error: (data, status, xhr) => { console.log(data, status, xhr); window['showNotification'](I18n.translate('frontend.error.message'), false); } }); } export function createListInputHandler(event: KeyboardEvent): void { if (event.which === 13) { event.preventDefault(); document.querySelector<HTMLButtonElement>('button#create-list').click(); } }<commit_after>import Rails from '@rails/ujs'; import I18n from '../../../legacy/i18n'; export function createListHandler(event: Event): void { const button = event.target as HTMLButtonElement; const input = document.querySelector<HTMLInputElement>('input#new-list-name'); Rails.ajax({ url: '/ajax/create_list', type: 'POST', data: new URLSearchParams({ name: input.value, user: button.dataset.user }).toString(), success: (data) => { if (data.success) { document.querySelector('#lists-list ul.list-group').insertAdjacentHTML('beforeend', data.render); } window['showNotification'](data.message, data.success); }, error: (data, status, xhr) => { console.log(data, status, xhr); window['showNotification'](I18n.translate('frontend.error.message'), false); } }); } export function createListInputHandler(event: KeyboardEvent): void { // Return key if (event.which === 13) { event.preventDefault(); document.querySelector<HTMLButtonElement>('button#create-list').click(); } }
<commit_msg>Add common factory fixtures to be shared across integration tests <commit_before>import pytest @pytest.fixture def coinbase(): return '0xdc544d1aa88ff8bbd2f2aec754b1f1e99e1812fd' @pytest.fixture def private_key(): return '0x58d23b55bc9cdce1f18c2500f40ff4ab7245df9a89505e9b1fa4851f623d241d' KEYFILE = '{"address":"dc544d1aa88ff8bbd2f2aec754b1f1e99e1812fd","crypto":{"cipher":"aes-128-ctr","ciphertext":"52e06bc9397ea9fa2f0dae8de2b3e8116e92a2ecca9ad5ff0061d1c449704e98","cipherparams":{"iv":"aa5d0a5370ef65395c1a6607af857124"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"9fdf0764eb3645ffc184e166537f6fe70516bf0e34dc7311dea21f100f0c9263"},"mac":"4e0b51f42b865c15c485f4faefdd1f01a38637e5247f8c75ffe6a8c0eba856f6"},"id":"5a6124e0-10f1-4c1c-ae3e-d903eacb740a","version":3}' # noqa: E501 <commit_after>import pytest from web3.utils.module_testing.math_contract import ( MATH_BYTECODE, MATH_ABI, ) from web3.utils.module_testing.emitter_contract import ( EMITTER_BYTECODE, EMITTER_ABI, ) @pytest.fixture(scope="session") def math_contract_factory(web3): contract_factory = web3.eth.contract(abi=MATH_ABI, bytecode=MATH_BYTECODE) return contract_factory @pytest.fixture(scope="session") def emitter_contract_factory(web3): contract_factory = web3.eth.contract(abi=EMITTER_ABI, bytecode=EMITTER_BYTECODE) return contract_factory
<commit_msg>Add comments for filter enums <commit_before>extern void denoise(void*, int, const uint32_t *in, uint32_t *out, int h, int w); extern void *kernelInit(void); extern void kernelFinalize(void*); enum { SPATIAL, TEMPORAL_AVG, KNN, AKNN, ADAPTIVE_TEMPORAL_AVG, DIFF, SOBEL, MOTION, }; <commit_after>extern void denoise(void*, int, const uint32_t *in, uint32_t *out, int h, int w); extern void *kernelInit(void); extern void kernelFinalize(void*); enum { // "Real" filters SPATIAL, TEMPORAL_AVG, ADAPTIVE_TEMPORAL_AVG, KNN, AKNN, // Helpers DIFF, SOBEL, MOTION, NFILTERS, };
<commit_msg>Use command line args for client endpoint <commit_before> int main(int argc, char* argv[]) { Kontroller::Client client; client.setButtonCallback([](Kontroller::Button button, bool pressed) { printf("%s %s\n", Kontroller::getName(button), pressed ? "pressed" : "released"); }); client.setDialCallback([](Kontroller::Dial dial, float value) { printf("%s dial value: %f\n", Kontroller::getName(dial), value); }); client.setSliderCallback([](Kontroller::Slider slider, float value) { printf("%s slider value: %f\n", Kontroller::getName(slider), value); }); while (!client.getState().stop) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } return 0; } <commit_after> int main(int argc, char* argv[]) { const char* endpoint = argc > 1 ? argv[1] : "127.0.0.1"; Kontroller::Client client(endpoint); client.setButtonCallback([](Kontroller::Button button, bool pressed) { printf("%s %s\n", Kontroller::getName(button), pressed ? "pressed" : "released"); }); client.setDialCallback([](Kontroller::Dial dial, float value) { printf("%s dial value: %f\n", Kontroller::getName(dial), value); }); client.setSliderCallback([](Kontroller::Slider slider, float value) { printf("%s slider value: %f\n", Kontroller::getName(slider), value); }); while (!client.getState().stop) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } return 0; }
<commit_msg>Create a route for fetching grefs <commit_before>import os import json from flask import Flask, render_template def channels_json(station, escaped=False): channels = [{"name": channel} for channel in station.channels()] jsonbody = json.dumps(channels) if escaped: jsonbody = jsonbody.replace("</", "<\\/") return jsonbody def make_airship(station): app = Flask(__name__) @app.route("/") def index(): return render_template("index.html", channels_json=channels_json(station, True)) @app.route("/channels") def list_channels(): return channels_json(station) return app <commit_after>import os import json from flask import Flask, render_template def channels_json(station, escaped=False): channels = [{"name": channel} for channel in station.channels()] jsonbody = json.dumps(channels) if escaped: jsonbody = jsonbody.replace("</", "<\\/") return jsonbody def make_airship(station): app = Flask(__name__) @app.route("/") def index(): return render_template("index.html", channels_json=channels_json(station, True)) @app.route("/channels") def list_channels(): return channels_json(station) @app.route("/grefs/<channel>") def list_grefs(channel): return return app
<commit_msg>Fix client script exit on exception <commit_before>import socket import sys from sys import argv from os import getcwd if len(argv) < 2: print "Usage: client <command>" sys.exit(-1) try: f = file("%s/target/sbt-server-port" % getcwd(), "r") port = int(f.read()) f.close() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("localhost", port)) s.send(argv[1]) s.shutdown(socket.SHUT_WR) r = s.recv(1024) s.close() sys.exit(int(r)) except Exception as e: print "sbt server not running in the current project: %s" % e <commit_after>import socket import sys from sys import argv from os import getcwd if len(argv) < 2: print "Usage: client <command>" sys.exit(-1) try: f = file("%s/target/sbt-server-port" % getcwd(), "r") port = int(f.read()) f.close() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("localhost", port)) s.send(argv[1]) s.shutdown(socket.SHUT_WR) r = s.recv(1024) s.close() sys.exit(int(r)) except Exception as e: print "sbt server not running in the current project: %s" % e sys.exit(-2)
<commit_msg>Add more basic plotting tests <commit_before>from nose.tools import assert_less from nose.tools import assert_greater_equal import os.path import numpy as np from nose import SkipTest from sklearn import datasets import umap import umap.plot np.random.seed(42) iris = datasets.load_iris() mapper = umap.UMAP(n_epochs=100).fit(iris.data) def test_plot_runs_at_all(): umap.plot.points(mapper, labels=iris.target) umap.plot.points(mapper, values=iris.data[:, 0]) umap.plot.diagnostic(mapper, diagnostic_type="all") umap.plot.connectivity(mapper) <commit_after>from nose.tools import assert_less from nose.tools import assert_greater_equal import os.path import numpy as np from nose import SkipTest from sklearn import datasets import umap import umap.plot np.random.seed(42) iris = datasets.load_iris() mapper = umap.UMAP(n_epochs=100).fit(iris.data) def test_plot_runs_at_all(): umap.plot.points(mapper) umap.plot.points(mapper, labels=iris.target) umap.plot.points(mapper, values=iris.data[:, 0]) umap.plot.points(mapper, theme='fire') umap.plot.diagnostic(mapper, diagnostic_type='all') umap.plot.diagnostic(mapper, diagnostic_type='neighborhood') umap.plot.connectivity(mapper) umap.plot.interactive(mapper) umap.plot.interactive(mapper, labels=iris.target) umap.plot.interactive(mapper, values=iris.data[:, 0]) umap.plot.interactive(mapper, theme='fire') umap.plot._datashade_points(mapper.embedding_)
<commit_msg>Make constants in MockHttpInterceptor static <commit_before>import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from "@angular/common/http"; import { Injectable } from "@angular/core"; import { Observable, of } from "rxjs"; import { BlobAction } from "./blob-action"; // Mock the HttpClient's interceptor so that HTTP requests are handled locally and not in the real back end. @Injectable() export class MockHttpInterceptor implements HttpInterceptor { private responseUrl = { imageUrl: "imageUrl" } private responseKey = { blobKey: "blobKey" } constructor() { } // Handles get / post requests intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { if (req.method === "GET" && req.url === '/blob-service?blobAction=' + BlobAction.GET_URL) { return of(new HttpResponse({ status: 200, body: this.responseUrl })); } else if (req.method === "POST" && req.url === this.responseUrl.imageUrl) { return of(new HttpResponse({ status: 200, body: this.responseKey })); } next.handle(req); } }<commit_after>import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from "@angular/common/http"; import { Injectable } from "@angular/core"; import { Observable, of } from "rxjs"; import { BlobAction } from "./blob-action"; // Mock the HttpClient's interceptor so that HTTP requests are handled locally and not in the real back end. @Injectable() export class MockHttpInterceptor implements HttpInterceptor { private static responseUrl = { imageUrl: "imageUrl" } private static responseKey = { blobKey: "blobKey" } constructor() { } // Handles get / post requests intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { if (req.method === "GET" && req.url === '/blob-service?blobAction=' + BlobAction.GET_URL) { return of(new HttpResponse({ status: 200, body: MockHttpInterceptor.responseUrl })); } else if (req.method === "POST" && req.url === MockHttpInterceptor.responseUrl.imageUrl) { return of(new HttpResponse({ status: 200, body: MockHttpInterceptor.responseKey })); } next.handle(req); } }
<commit_msg>Update offline bat cache after adding a bat <commit_before>package peergos.server; import peergos.server.storage.auth.*; import peergos.shared.storage.auth.*; import peergos.shared.util.*; import java.util.*; import java.util.concurrent.*; public class OfflineBatCache implements BatCave { private final BatCave target; private final BatCache cache; public OfflineBatCache(BatCave target, BatCache cache) { this.target = target; this.cache = cache; } @Override public Optional<Bat> getBat(BatId id) { return target.getBat(id); } @Override public CompletableFuture<List<BatWithId>> getUserBats(String username, byte[] auth) { return Futures.asyncExceptionally( () -> target.getUserBats(username, auth).thenApply(bats -> { cache.setUserBats(username, bats); return bats; }), t -> cache.getUserBats(username)); } @Override public CompletableFuture<Boolean> addBat(String username, BatId id, Bat bat, byte[] auth) { return target.addBat(username, id, bat, auth); } } <commit_after>package peergos.server; import peergos.server.storage.auth.*; import peergos.shared.storage.auth.*; import peergos.shared.util.*; import java.util.*; import java.util.concurrent.*; public class OfflineBatCache implements BatCave { private final BatCave target; private final BatCache cache; public OfflineBatCache(BatCave target, BatCache cache) { this.target = target; this.cache = cache; } @Override public Optional<Bat> getBat(BatId id) { return target.getBat(id); } @Override public CompletableFuture<List<BatWithId>> getUserBats(String username, byte[] auth) { return Futures.asyncExceptionally( () -> target.getUserBats(username, auth).thenApply(bats -> { cache.setUserBats(username, bats); return bats; }), t -> cache.getUserBats(username)); } @Override public CompletableFuture<Boolean> addBat(String username, BatId id, Bat bat, byte[] auth) { return target.addBat(username, id, bat, auth).thenApply(res -> { getUserBats(username, (byte[])null); // update cache return res; }); } }
<commit_msg>Generalize this test to work without instruction names. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@121742 91177308-0d34-0410-b5e6-96231b3b80d8 <commit_before>// RUN: %clang_cc1 -Werror -triple i386-unknown-unknown -emit-llvm -O1 -disable-llvm-optzns -o %t %s // RUN: FileCheck < %t %s // Types with the may_alias attribute should be considered equivalent // to char for aliasing. typedef int __attribute__((may_alias)) aliasing_int; void test0(aliasing_int *ai, int *i) { *ai = 0; *i = 1; } // CHECK: store i32 0, i32* %tmp, !tbaa !1 // CHECK: store i32 1, i32* %tmp1, !tbaa !3 // CHECK: !0 = metadata !{metadata !"any pointer", metadata !1} // CHECK: !1 = metadata !{metadata !"omnipotent char", metadata !2} // CHECK: !2 = metadata !{metadata !"Simple C/C++ TBAA", null} // CHECK: !3 = metadata !{metadata !"int", metadata !1} <commit_after>// RUN: %clang_cc1 -Werror -triple i386-unknown-unknown -emit-llvm -O1 -disable-llvm-optzns -o %t %s // RUN: FileCheck < %t %s // Types with the may_alias attribute should be considered equivalent // to char for aliasing. typedef int __attribute__((may_alias)) aliasing_int; void test0(aliasing_int *ai, int *i) { *ai = 0; *i = 1; } // CHECK: store i32 0, i32* %{{.*}}, !tbaa !1 // CHECK: store i32 1, i32* %{{.*}}, !tbaa !3 // CHECK: !0 = metadata !{metadata !"any pointer", metadata !1} // CHECK: !1 = metadata !{metadata !"omnipotent char", metadata !2} // CHECK: !2 = metadata !{metadata !"Simple C/C++ TBAA", null} // CHECK: !3 = metadata !{metadata !"int", metadata !1}
<commit_msg>Fix nodiscard test when modules are enabled git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@318618 91177308-0d34-0410-b5e6-96231b3b80d8 <commit_before>// -*- C++ -*- //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Test that _LIBCPP_NODISCARD_AFTER_CXX17 works // #define _LIBCPP_NODISCARD_AFTER_CXX17 [[nodiscard]] // UNSUPPORTED: c++98, c++03, c++11, c++14 #define _LIBCPP_DISABLE_NODISCARD_AFTER_CXX17 #include <__config> _LIBCPP_NODISCARD_AFTER_CXX17 int foo() { return 6; } int main () { foo(); // no error here! } <commit_after>// -*- C++ -*- //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Test that _LIBCPP_NODISCARD_AFTER_CXX17 works // #define _LIBCPP_NODISCARD_AFTER_CXX17 [[nodiscard]] // UNSUPPORTED: c++98, c++03, c++11, c++14 // MODULES_DEFINES: _LIBCPP_DISABLE_NODISCARD_AFTER_CXX17 #define _LIBCPP_DISABLE_NODISCARD_AFTER_CXX17 #include <__config> _LIBCPP_NODISCARD_AFTER_CXX17 int foo() { return 6; } int main () { foo(); // no error here! }
<commit_msg>Print and exit on error. <commit_before>package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" ) type Result struct { Domain string Availability string } type SearchResults struct { Query string Results []Result } func main() { if len(os.Args) < 2 { log.Fatal("Missing search query. Specify a string to search domainr for.") } var query string = os.Args[1] httpResponse, _ := http.Get("https://domai.nr/api/json/search?client_id=domainr_command_line_app&q=" + query) defer httpResponse.Body.Close() body, _ := ioutil.ReadAll(httpResponse.Body) var sr SearchResults // Decode json string into custom structs. json.Unmarshal(body, &sr) // Print results to stdout fmt.Printf("\n Results for \"%s\"\n\n", sr.Query) for _, result := range sr.Results { var available string switch result.Availability { case "available": available = "✔" default: available = "✘" } fmt.Printf(" %s %s\n", available, result.Domain) } fmt.Printf("\n") } <commit_after>package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "os" ) const ( apiURL = "https://domai.nr/api/json/search?client_id=domainr_command_line_app&q=" ) type Result struct { Domain string Availability string } type SearchResults struct { Query string Results []Result } func main() { if len(os.Args) < 2 { fmt.Println("Missing search query. Specify a string to search domainr for.") os.Exit(1) } var query string = os.Args[1] httpResponse, err := http.Get(apiURL + query) if err != nil { fmt.Println(err) os.Exit(1) } defer httpResponse.Body.Close() body, err := ioutil.ReadAll(httpResponse.Body) if err != nil { fmt.Println(err) os.Exit(1) } var sr SearchResults // Decode json string into custom structs. json.Unmarshal(body, &sr) // Print results to stdout fmt.Printf("\n Results for \"%s\"\n\n", sr.Query) for _, result := range sr.Results { var available string switch result.Availability { case "available": available = "✔" default: available = "✘" } fmt.Printf(" %s %s\n", available, result.Domain) } fmt.Printf("\n") }
<commit_msg>Update RequestVote step 1 test data <commit_before>package raft import ( "reflect" "testing" ) func makeRVWithTerm(term TermNo) *RpcRequestVote { return &RpcRequestVote{term, 0, 0} } // 1. Reply false if term < currentTerm (#5.1) // Note: this test assumes server in sync with the Figure 7 leader func TestCM_RpcRV_TermLessThanCurrentTerm(t *testing.T) { f := func(setup func(t *testing.T) (mcm *managedConsensusModule, mrs *mockRpcSender)) { mcm, _ := setup(t) serverTerm := mcm.pcm.persistentState.GetCurrentTerm() requestVote := makeRVWithTerm(serverTerm - 1) reply := mcm.pcm.rpc("s2", requestVote) expectedRpc := &RpcRequestVoteReply{serverTerm, false} if !reflect.DeepEqual(reply, expectedRpc) { t.Fatal(reply) } } f(testSetupMCM_Follower_Figure7LeaderLine) f(testSetupMCM_Candidate_Figure7LeaderLine) f(testSetupMCM_Leader_Figure7LeaderLine) } <commit_after>package raft import ( "reflect" "testing" ) // 1. Reply false if term < currentTerm (#5.1) // Note: test based on Figure 7; server is leader line; peer is case (a) func TestCM_RpcRV_TermLessThanCurrentTerm(t *testing.T) { f := func(setup func(t *testing.T) (mcm *managedConsensusModule, mrs *mockRpcSender)) { mcm, _ := setup(t) serverTerm := mcm.pcm.persistentState.GetCurrentTerm() requestVote := &RpcRequestVote{7, 9, 6} reply := mcm.pcm.rpc("s2", requestVote) expectedRpc := &RpcRequestVoteReply{serverTerm, false} if !reflect.DeepEqual(reply, expectedRpc) { t.Fatal(reply) } } f(testSetupMCM_Follower_Figure7LeaderLine) f(testSetupMCM_Candidate_Figure7LeaderLine) f(testSetupMCM_Leader_Figure7LeaderLine) }
<commit_msg>Fix config_drive migration, per Matt Dietz.<commit_before> from sqlalchemy import Column, Integer, MetaData, String, Table from nova import utils meta = MetaData() instances = Table("instances", meta, Column("id", Integer(), primary_key=True, nullable=False)) config_drive_column = Column("config_drive", String(255)) # matches image_ref def upgrade(migrate_engine): meta.bind = migrate_engine instances.create_column(config_drive_column) rows = migrate_engine.execute(instances.select()) for row in rows: instance_config_drive = None # pre-existing instances don't have one. migrate_engine.execute(instances.update()\ .where(instances.c.id == row[0])\ .values(config_drive=instance_config_drive)) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column(config_drive_column) <commit_after> from sqlalchemy import Column, Integer, MetaData, String, Table from nova import utils meta = MetaData() instances = Table("instances", meta, Column("id", Integer(), primary_key=True, nullable=False)) # matches the size of an image_ref config_drive_column = Column("config_drive", String(255), nullable=True) def upgrade(migrate_engine): meta.bind = migrate_engine instances.create_column(config_drive_column) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column(config_drive_column)
<commit_msg>Fix interop issues with pytest-instafail <commit_before>def pytest_runtest_logreport(report): """Overwrite report by removing any captured stderr.""" # print("PLUGIN SAYS -> report -> {0}".format(report)) # print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections)) # print("PLUGIN SAYS -> dir(report) -> {0}".format(dir(report))) # print("PLUGIN SAYS -> type(report) -> {0}".format(type(report))) sections = [item for item in report.sections if item[0] not in ("Captured stdout call", "Captured stderr call", "Captured stdout setup", "Captured stderr setup", "Captured stdout teardown", "Captured stderr teardown")] # print("PLUGIN SAYS -> sections -> {0}".format(sections)) report.sections = sections <commit_after>import pytest @pytest.mark.tryfirst def pytest_runtest_logreport(report): """Overwrite report by removing any captured stderr.""" # print("PLUGIN SAYS -> report -> {0}".format(report)) # print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections)) # print("PLUGIN SAYS -> dir(report) -> {0}".format(dir(report))) # print("PLUGIN SAYS -> type(report) -> {0}".format(type(report))) sections = [item for item in report.sections if item[0] not in ("Captured stdout call", "Captured stderr call", "Captured stdout setup", "Captured stderr setup", "Captured stdout teardown", "Captured stderr teardown")] # print("PLUGIN SAYS -> sections -> {0}".format(sections)) report.sections = sections
<commit_msg>Fix state_to_draw_t by adding the number of possible mvts <commit_before> typedef struct { int num_goats_to_put; int num_eaten_goats; player_turn_t turn; mvt_t input; mvt_t *possible_mvts; board_t *board; } state_to_draw_t; #endif <commit_after> typedef struct { int num_goats_to_put; int num_eaten_goats; player_turn_t turn; mvt_t input; mvt_t *possible_mvts; size_t num_possible_mvts; board_t *board; } state_to_draw_t; #endif
<commit_msg>Fix bug where moving selected layer would select different layer <commit_before>import { ApplicationState } from '../../../../../shared/models/applicationState'; import { Point } from '../../../../../shared/models/point'; import { moveElement } from '../../../../../shared/utils/arrays'; import { defineAction } from '../../../../reduxWithLessSux/action'; interface MoveLayerPayload { layerIndex: number; toIndex: number; } export const moveLayer = defineAction( 'moveLayer', (state: ApplicationState, payload: MoveLayerPayload) => { const editors = state.editors.map((editor, editorIndex) => { if (editorIndex === state.activeEditorIndex) { const projectFile = editor.projectFile; let layers = [...projectFile.layers]; layers = moveElement(layers, payload.layerIndex, payload.toIndex); return { ...editor, projectFile: { ...projectFile, layers } }; } return editor; }); return { ...state, editors }; } ).getDispatcher(); <commit_after>import { ApplicationState } from '../../../../../shared/models/applicationState'; import { Point } from '../../../../../shared/models/point'; import { moveElement } from '../../../../../shared/utils/arrays'; import { defineAction } from '../../../../reduxWithLessSux/action'; interface MoveLayerPayload { layerIndex: number; toIndex: number; } export const moveLayer = defineAction( 'moveLayer', (state: ApplicationState, payload: MoveLayerPayload) => { const editors = state.editors.map((editor, editorIndex) => { if (editorIndex === state.activeEditorIndex) { const projectFile = editor.projectFile; let layers = [...projectFile.layers]; if (payload.toIndex < 0 || payload.toIndex >= layers.length) { return editor; } layers = moveElement(layers, payload.layerIndex, payload.toIndex); const selectedLayerIndex = ( editor.selectedLayerIndex === payload.layerIndex ? payload.toIndex : editor.selectedLayerIndex ); return { ...editor, projectFile: { ...projectFile, layers }, selectedLayerIndex }; } return editor; }); return { ...state, editors }; } ).getDispatcher();
<commit_msg>Replace slug field with get_slug function <commit_before>from django.db import models from django.utils.translation import pgettext as _ from django_prices.models import PriceField from satchless.util.models import Subtyped from satchless.item import ItemRange from mptt.models import MPTTModel class Category(MPTTModel): name = models.CharField(_('Category field', 'name'), max_length=128) slug = models.SlugField(_('Category field', 'slug'), max_length=50, unique=True) description = models.TextField(_('Category field', 'description'), blank=True) parent = models.ForeignKey('self', null=True, related_name='children', blank=True, verbose_name=_('Category field', 'parent')) def __unicode__(self): return self.name class Product(Subtyped, ItemRange): name = models.CharField(_('Product field', 'name'), max_length=128) slug = models.SlugField(_('Product field', 'slug'), max_length=50, unique=True) price = PriceField(_('Product field', 'price'), currency='USD', max_digits=12, decimal_places=4) category = models.ForeignKey(Category, verbose_name=_('Product field', 'category')) def __unicode__(self): return self.name <commit_after>from django.db import models from django.utils.safestring import mark_safe from django.utils.translation import pgettext as _ from django_prices.models import PriceField from mptt.models import MPTTModel from satchless.item import ItemRange from satchless.util.models import Subtyped from unidecode import unidecode import re class Category(MPTTModel): name = models.CharField(_('Category field', 'name'), max_length=128) slug = models.SlugField(_('Category field', 'slug'), max_length=50, unique=True) description = models.TextField(_('Category field', 'description'), blank=True) parent = models.ForeignKey('self', null=True, related_name='children', blank=True, verbose_name=_('Category field', 'parent')) def __unicode__(self): return self.name class Product(Subtyped, ItemRange): name = models.CharField(_('Product field', 'name'), max_length=128) price = PriceField(_('Product field', 'price'), currency='USD', max_digits=12, decimal_places=4) category = models.ForeignKey(Category, verbose_name=_('Product field', 'category')) def __unicode__(self): return self.name def get_slug(self): value = unidecode(self.name) value = re.sub('[^\w\s-]', '', value).strip().lower() return mark_safe(re.sub('[-\s]+', '-', value)) @models.permalink def get_absolute_url(self): return ('product:details', [self.get_slug(), self.id])
<commit_msg>Fix build broken by previous commit. <commit_before> from setuptools import setup, find_packages deps = [ line.strip() for line in open("deps.txt") if line and not line.startswith("#") ] metadata = dict( name='Yaka Core', version='0.1dev', url='http://www.yaka.biz/', license='LGPL', author='Stefane Fermigier', author_email='sf@fermigier.com', description='Enterprise social networking meets CRM', long_description=__doc__, packages=['yaka'], platforms='any', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], # Unsupported by distutils. #install_requires=deps, #include_package_data=True, #zip_safe=False, ) setup(**metadata) <commit_after> from setuptools import setup, find_packages def get_deps(): import re deps_raw = [ line.strip() for line in open("deps.txt")] deps = [] for dep in deps_raw: if not dep or dep.startswith("#"): continue m = re.search("#egg=(.*)", dep) if m: dep = m.group(1) deps.append(dep) return deps metadata = dict( name='Yaka Core', version='0.1dev', url='http://www.yaka.biz/', license='LGPL', author='Stefane Fermigier', author_email='sf@fermigier.com', description='Enterprise social networking meets CRM', long_description=__doc__, packages=['yaka'], platforms='any', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], # Setuptools specific install_requires=get_deps(), include_package_data=True, zip_safe=False, ) setup(**metadata)
<commit_msg>Add infixes and abbreviation exceptions (fr) <commit_before>from __future__ import unicode_literals from .. import language_data as base from ..language_data import strings_to_exc, update_exc from .stop_words import STOP_WORDS STOP_WORDS = set(STOP_WORDS) TOKENIZER_EXCEPTIONS = strings_to_exc(base.EMOTICONS) update_exc(TOKENIZER_EXCEPTIONS, strings_to_exc(base.ABBREVIATIONS)) __all__ = ["TOKENIZER_EXCEPTIONS", "STOP_WORDS"] <commit_after>from __future__ import unicode_literals from .. import language_data as base from ..language_data import strings_to_exc, update_exc from .punctuation import ELISION from ..symbols import * from .stop_words import STOP_WORDS STOP_WORDS = set(STOP_WORDS) TOKENIZER_EXCEPTIONS = strings_to_exc(base.EMOTICONS) update_exc(TOKENIZER_EXCEPTIONS, strings_to_exc(base.ABBREVIATIONS)) ABBREVIATIONS = { "janv.": [ {LEMMA: "janvier", ORTH: "janv."} ], "févr.": [ {LEMMA: "février", ORTH: "févr."} ], "avr.": [ {LEMMA: "avril", ORTH: "avr."} ], "juill.": [ {LEMMA: "juillet", ORTH: "juill."} ], "sept.": [ {LEMMA: "septembre", ORTH: "sept."} ], "oct.": [ {LEMMA: "octobre", ORTH: "oct."} ], "nov.": [ {LEMMA: "novembre", ORTH: "nov."} ], "déc.": [ {LEMMA: "décembre", ORTH: "déc."} ], } INFIXES_EXCEPTIONS_BASE = ["aujourd'hui", "prud'homme", "prud'hommes", "prud'homal", "prud'homaux", "prud'homale", "prud'homales", "prud'hommal", "prud'hommaux", "prud'hommale", "prud'hommales", "prud'homie", "prud'homies", "prud'hommesque", "prud'hommesques", "prud'hommesquement"] INFIXES_EXCEPTIONS = [] for elision_char in ELISION: INFIXES_EXCEPTIONS += [infix.replace("'", elision_char) for infix in INFIXES_EXCEPTIONS_BASE] INFIXES_EXCEPTIONS += [word.capitalize() for word in INFIXES_EXCEPTIONS] update_exc(TOKENIZER_EXCEPTIONS, strings_to_exc(INFIXES_EXCEPTIONS)) update_exc(TOKENIZER_EXCEPTIONS, ABBREVIATIONS) __all__ = ["TOKENIZER_EXCEPTIONS", "STOP_WORDS"]
<commit_msg>Fix stars logged in validation bug <commit_before>import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core'; import { AcStars } from './stars'; import { ToastService } from '../../services/shared/toast.service'; import { AuthService } from '../../services/authentication/auth.service'; import { UserService } from '../../services/shared/user.service'; @Component({ selector: 'auth-ac-stars', template: ` <ac-stars [rating]="rating" (newRate)="onRate($event)" [starCount]="starCount"> </ac-stars> ` }) export class AuthAcStars implements OnInit { private _isLogged: boolean; private _isOwner: boolean; @Input() ownerUsername: boolean; @Input() starCount: number; @Input() rating: number; @Output() newRate = new EventEmitter(); constructor( private _toastService: ToastService, private _authService: AuthService, private _userService: UserService ) { } ngOnInit() { this._isLogged = this._authService.isLoggedIn(); let loggedUser = this._userService.getUserFromLocalStorage() || {}; this._isOwner = loggedUser.username === this.ownerUsername; } onRate(star: any) { if (!this._isLogged) { this._toastService.activate("Please login!"); event.stopPropagation(); } else if (this._isOwner) { this._toastService.activate("Invalid operation!"); event.stopPropagation(); } else { this.newRate.emit(star); } } } <commit_after>import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core'; import { AcStars } from './stars'; import { ToastService } from '../../services/shared/toast.service'; import { AuthService } from '../../services/authentication/auth.service'; import { UserService } from '../../services/shared/user.service'; @Component({ selector: 'auth-ac-stars', template: ` <ac-stars [rating]="rating" (newRate)="onRate($event)" [starCount]="starCount"> </ac-stars> ` }) export class AuthAcStars implements OnInit { private _isOwner: boolean; @Input() ownerUsername: boolean; @Input() starCount: number; @Input() rating: number; @Output() newRate = new EventEmitter(); constructor( private _toastService: ToastService, private _authService: AuthService, private _userService: UserService ) { } ngOnInit() { let loggedUser = this._userService.getUserFromLocalStorage() || {}; this._isOwner = loggedUser.username === this.ownerUsername; } onRate(star: any) { let isLoggedIn = this._authService.isLoggedIn(); if (!isLoggedIn) { this._toastService.activate("Please login!"); event.stopPropagation(); } else if (this._isOwner) { this._toastService.activate("Invalid operation!"); event.stopPropagation(); } else { this.newRate.emit(star); } } }
<commit_msg>Add default import for crystal and kernel <commit_before>from .atom import * # NOQA from .molecule import * # NOQA <commit_after>from .atom import * # NOQA from .molecule import * # NOQA from .crystal import * # NOQA from .kernel import * # NOQA
<commit_msg>[auth] Add injected values check infra, and add checkcs for product and ProductChange. <commit_before>package to.etc.domui.injector; import org.eclipse.jdt.annotation.Nullable; import to.etc.domui.dom.html.AbstractPage; import to.etc.util.PropertyInfo; /** * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on 20-12-18. */ public interface ITypedValueAccessChecker<T> { boolean isAccessAllowed(PropertyInfo info, AbstractPage page, @Nullable T value) throws Exception; } <commit_after>package to.etc.domui.injector; import org.eclipse.jdt.annotation.NonNull; import to.etc.domui.dom.html.AbstractPage; import to.etc.util.PropertyInfo; /** * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on 20-12-18. */ public interface ITypedValueAccessChecker<T> { boolean isAccessAllowed(PropertyInfo info, AbstractPage page, @NonNull T value) throws Exception; }
<commit_msg>Update composite section to handle notifications <commit_before>package ca.antonious.viewcelladapter.sections; import java.util.ArrayList; import java.util.List; import ca.antonious.viewcelladapter.viewcells.AbstractViewCell; import ca.antonious.viewcelladapter.utils.ViewCellUtils; /** * Created by George on 2016-12-17. */ public class CompositeSection extends AbstractSection { private List<AbstractSection> sections; public CompositeSection() { this.sections = new ArrayList<>(); } @Override public AbstractViewCell get(int position) { return ViewCellUtils.getViewCell(sections, position); } @Override public void remove(int position) { int sectionIndex = ViewCellUtils.getSectionIndex(sections, position); int viewCellIndex = ViewCellUtils.getViewCellIndex(sections, position); sections.get(sectionIndex).remove(viewCellIndex); } @Override public int getItemCount() { return ViewCellUtils.getTotalCount(sections); } public CompositeSection addSection(AbstractSection section) { sections.add(section); return this; } public CompositeSection removeSection(AbstractSection section) { sections.remove(section); return this; } } <commit_after>package ca.antonious.viewcelladapter.sections; import java.util.ArrayList; import java.util.List; import ca.antonious.viewcelladapter.internal.SectionObserver; import ca.antonious.viewcelladapter.viewcells.AbstractViewCell; import ca.antonious.viewcelladapter.utils.ViewCellUtils; /** * Created by George on 2016-12-17. */ public class CompositeSection extends AbstractSection implements SectionObserver { private List<AbstractSection> sections; public CompositeSection() { this.sections = new ArrayList<>(); } @Override public AbstractViewCell get(int position) { return ViewCellUtils.getViewCell(sections, position); } @Override public void remove(int position) { int sectionIndex = ViewCellUtils.getSectionIndex(sections, position); int viewCellIndex = ViewCellUtils.getViewCellIndex(sections, position); sections.get(sectionIndex).remove(viewCellIndex); } @Override public int getItemCount() { return ViewCellUtils.getTotalCount(sections); } public CompositeSection addSection(AbstractSection section) { section.addObserver(this); sections.add(section); return this; } public CompositeSection removeSection(AbstractSection section) { section.removeObserver(this); sections.remove(section); return this; } @Override public void onDataChanged() { notifyDataChanged(); } }
<commit_msg>Fix for JodaTime not being initialized correctly in dev builds <commit_before>package mn.devfest; import android.app.Application; import android.content.Context; import net.danlew.android.joda.JodaTimeAndroid; import timber.log.Timber; /** * DevFest application class * * Performs application-wide configuration * * @author bherbst */ public class DevFestApplication extends Application { private DevFestGraph mGraph; @Override public void onCreate() { super.onCreate(); init(); buildComponent(); } /** * Build the Dagger component */ private void buildComponent() { mGraph = DevFestComponent.Initializer.init(this); } /** * Get the Dagger component */ public DevFestGraph component() { return mGraph; } /** * Initialize app-wide configuration * * The default implementation sets up the app for release. Do not call through to super() * if you do not want the release configuration. */ protected void init() { JodaTimeAndroid.init(this); Timber.plant(new ReleaseTree()); } /** * Get a WvwApplication from a Context * @param context The Context in which to get the WvwApplication * @return The WvwApplication associated with the given Context */ public static DevFestApplication get(Context context) { return (DevFestApplication) context.getApplicationContext(); } } <commit_after>package mn.devfest; import android.app.Application; import android.content.Context; import net.danlew.android.joda.JodaTimeAndroid; import timber.log.Timber; /** * DevFest application class * * Performs application-wide configuration * * @author bherbst */ public class DevFestApplication extends Application { private DevFestGraph mGraph; @Override public void onCreate() { super.onCreate(); JodaTimeAndroid.init(this); init(); buildComponent(); } /** * Build the Dagger component */ private void buildComponent() { mGraph = DevFestComponent.Initializer.init(this); } /** * Get the Dagger component */ public DevFestGraph component() { return mGraph; } /** * Initialize app-wide configuration * * The default implementation sets up the app for release. Do not call through to super() * if you do not want the release configuration. */ protected void init() { Timber.plant(new ReleaseTree()); } /** * Get a WvwApplication from a Context * @param context The Context in which to get the WvwApplication * @return The WvwApplication associated with the given Context */ public static DevFestApplication get(Context context) { return (DevFestApplication) context.getApplicationContext(); } }
<commit_msg>Use lazy translation for importer strings <commit_before>from corehq.apps.data_interfaces.interfaces import DataInterface from django.utils.translation import ugettext as _ class ImportCases(DataInterface): name = _("Import Cases from Excel") slug = "import_cases" description = _("Import case data from an external Excel file") report_template_path = "importer/import_cases.html" gide_filters = True asynchronous = False <commit_after>from corehq.apps.data_interfaces.interfaces import DataInterface from django.utils.translation import ugettext_lazy class ImportCases(DataInterface): name = ugettext_lazy("Import Cases from Excel") slug = "import_cases" description = ugettext_lazy("Import case data from an external Excel file") report_template_path = "importer/import_cases.html" gide_filters = True asynchronous = False
<commit_msg>ADD constant test variables OWNER_EMAIL / OWNER_PWD <commit_before>from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email="info@openmined.org", password="changethis" ) <commit_after>from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient OWNER_EMAIL = "info@openmined.org" OWNER_PWD = "changethis" async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email=OWNER_EMAIL, password=OWNER_PWD, )
<commit_msg>Change names of the interface on net part. Change has_next() to can_read(). Change read_next() to read(). So it reads more natural. <commit_before>// Created on November 19, 2013 by Lu, Wangshan. #include <boost/asio.hpp> #include <diffusion/factory.hpp> namespace diffusion { class NetReader : public Reader { public: NetReader(std::string const & listening_ip_address, std::uint16_t listening_port); virtual bool has_next(); virtual ByteBuffer get_next(); private: }; } // namespace diffusion <commit_after>// Created on November 19, 2013 by Lu, Wangshan. #include <boost/asio.hpp> #include <diffusion/factory.hpp> namespace diffusion { class NetReader : public Reader { public: NetReader(std::string const & listening_ip_address, std::uint16_t listening_port); virtual bool can_read(); virtual ByteBuffer read(); private: }; } // namespace diffusion
<commit_msg>Add test for refactored dispatcher <commit_before>import Dispatch from '../src/Dispatcher'; import * as chai from 'chai'; const expect = chai.expect; import * as path from 'path'; describe('Dispatch', function () { let dispatch: Dispatch; beforeEach(function () { dispatch = new Dispatch(); }); it('Dispatches to Cat', function (done) { dispatch .dispatch('cat', ['one', 'two'] .map((f) => path.resolve(__dirname + '/fixtures/' + f))) .then((results) => expect(results).to.be.deep.equal(['1', '2', '2', '3'])) .then(() => done()) .catch(done); }); }); <commit_after>import Dispatch, { DispatcherStandardInputStream } from '../src/Dispatcher'; import { Split } from '../src/TextOperations'; import { BasicStreamHandlerDelegate } from './BasicStreamHandler' import * as chai from 'chai'; const expect = chai.expect; import { stdio } from 'stdio-mock'; import * as path from 'path'; describe('Dispatch', function () { let dispatch: Dispatch; beforeEach(function () { dispatch = new Dispatch(); }); it('Dispatches to Cat', function (done) { dispatch .dispatch('cat', ['one', 'two'] .map((f) => path.resolve(__dirname + '/fixtures/' + f))) .then((results) => expect(results).to.be.deep.equal(['1', '2', '2', '3'])) .then(() => done()) .catch(done); }); }); describe('DispatcherStandardInputStream', function () { let dispatch: DispatcherStandardInputStream; let handlerDelegate: BasicStreamHandlerDelegate; let stdin: any; beforeEach(function() { handlerDelegate = new BasicStreamHandlerDelegate(); stdin = stdio().stdin; dispatch = new DispatcherStandardInputStream(handlerDelegate, stdin); }); it('Dispatches a basic split async operation', function (done) { const split = new Split(); dispatch .dispatch(split, [`--input-delimiter`, ` `, `--output-delimiter`, `,`]) .then(() => expect(handlerDelegate.buffer).to.deep.equal(['hello,world'])) .then(() => done()) .catch((err) => console.log(err)); stdin.write('hello world'); stdin.end(); }); });
<commit_msg>Use only absolute imports for python 3 <commit_before> try: import pandas except ImportError: pandas = None __all__ = () if pandas is not None: from pandas_data import PandasDataFrame __all__ += ('PandasDataFrame',) try: import geopandas except ImportError: geopandas = None if geopandas is not None: from geopandas_data import GeopandasDataFrame from geopandas_reader import GeopandasReader from geopandas_plot import GeopandasPlot __all__ += ( 'GeopandasDataFrame', 'GeopandasReader', 'GeopandasPlot' ) try: import xray except ImportError: xray = None if xray is not None: from xray_data import XrayDataset __all__ += ('XrayDataset',) <commit_after> try: import pandas except ImportError: pandas = None __all__ = () if pandas is not None: from gaia.pandas.pandas_data import PandasDataFrame __all__ += ('PandasDataFrame',) try: import geopandas except ImportError: geopandas = None if geopandas is not None: from gaia.pandas.geopandas_data import GeopandasDataFrame from gaia.pandas.geopandas_reader import GeopandasReader from gaia.pandas.geopandas_plot import GeopandasPlot __all__ += ( 'GeopandasDataFrame', 'GeopandasReader', 'GeopandasPlot' ) try: import xray except ImportError: xray = None if xray is not None: from gaia.pandas.xray_data import XrayDataset __all__ += ('XrayDataset',)
<commit_msg>Remove six.moves and disable linter <commit_before>from __future__ import absolute_import def register_scheme(name): from six.moves.urllib import parse as urlparse uses = urlparse.uses_netloc, urlparse.uses_query, urlparse.uses_relative, urlparse.uses_fragment for use in uses: if name not in use: use.append(name) register_scheme('app') <commit_after>from __future__ import absolute_import def register_scheme(name): try: import urlparse # NOQA except ImportError: from urllib import parse as urlparse # NOQA uses = urlparse.uses_netloc, urlparse.uses_query, urlparse.uses_relative, urlparse.uses_fragment for use in uses: if name not in use: use.append(name) register_scheme('app')
<commit_msg>Fix for wrong test: create_semester_accounts refs #448 <commit_before>from tests import OldPythonTestCase __author__ = 'felix_kluge' from pycroft.lib.finance import create_semester from pycroft.lib.config import get,config from pycroft.model.finance import FinanceAccount from sqlalchemy.orm import backref from pycroft.model import session import time from datetime import date class Test_010_Semester(OldPythonTestCase): def test_0010_create_semester_accounts(self): """ This test should verify that all semester-related finance-accounts have been created. """ new_semester = create_semester("NewSemesterName", 2500, 1500, date(2013, 9, 1), date(2014, 2, 1)) config._configpath = "../tests/example/test_config.json" for account in config["finance"]["semester_accounts"]: for new_account in new_semester.accounts: if(new_account.tag == account["tag"]): new_account_equivalent = new_account compare_account = FinanceAccount(type=account["type"],name=account["name"],semester=new_semester,tag=account["tag"]) self.assertEqual(new_account_equivalent.name, compare_account.name) self.assertEqual(new_account_equivalent.type, compare_account.type) <commit_after>from tests import OldPythonTestCase __author__ = 'felix_kluge' from pycroft.lib.finance import create_semester, import_csv from pycroft.lib.config import get, config from pycroft.model.finance import FinanceAccount, Journal, JournalEntry from sqlalchemy.orm import backref from pycroft.model import session import time from datetime import date, datetime class Test_010_Semester(OldPythonTestCase): def test_0010_create_semester_accounts(self): """ This test should verify that all semester-related finance-accounts have been created. """ new_semester = create_semester("NewSemesterName", 2500, 1500, date(2013, 9, 1), date(2014, 2, 1)) config._configpath = "../tests/example/test_config.json" for account in config["finance"]["semester_accounts"]: new_created_account = FinanceAccount.q.filter( FinanceAccount.semester == new_semester, FinanceAccount.tag == account["tag"]).first() self.assertEqual(new_created_account.name, account["name"]) self.assertEqual(new_created_account.type, account["type"]) session.session.commit()
<commit_msg>Set mobile data without reflections for Android 9. (1) <commit_before>package sk.henrichg.phoneprofilesplus; import android.net.IConnectivityManager; import android.os.ServiceManager; @SuppressWarnings("WeakerAccess") public class CmdMobileData { public static void main(String[] args) { if (!(run())) { System.exit(1); } } private static boolean run() { try { IConnectivityManager adapter = IConnectivityManager.Stub.asInterface(ServiceManager.getService("connectivity")); //adapter.; return true; } catch (Throwable e) { return false; } } } <commit_after>package sk.henrichg.phoneprofilesplus; import android.os.ServiceManager; import com.android.internal.telephony.ITelephony; @SuppressWarnings("WeakerAccess") public class CmdMobileData { public static void main(String[] args) { int subId= Integer.parseInt(args[0]); boolean enable = Boolean.parseBoolean(args[1]); if (!(run(subId, enable))) { System.exit(1); } } private static boolean run(int subId, boolean enable) { try { ITelephony adapter = ITelephony.Stub.asInterface(ServiceManager.getService("phone")); //adapter.getDataEnabled(subId); // hm podpora pre dual sim adapter.setUserDataEnabled(subId, enable); // hm podpora pre dual sim return true; } catch (Throwable e) { return false; } } }
<commit_msg>Set this in addition to annotation introspector approach <commit_before>package com.hubspot.rosetta.internal; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider; @SuppressWarnings("serial") public class RosettaModule extends Module { @Override public String getModuleName() { return "RosettaModule"; } @Override public Version version() { return Version.unknownVersion(); } @Override public void setupModule(SetupContext context) { context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier()); ObjectCodec codec = context.getOwner(); if (codec instanceof ObjectMapper) { ObjectMapper mapper = (ObjectMapper) codec; context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper)); mapper.setSerializerProvider(new DefaultSerializerProvider.Impl()); mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } } } <commit_after>package com.hubspot.rosetta.internal; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider; @SuppressWarnings("serial") public class RosettaModule extends Module { @Override public String getModuleName() { return "RosettaModule"; } @Override public Version version() { return Version.unknownVersion(); } @Override public void setupModule(SetupContext context) { context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier()); ObjectCodec codec = context.getOwner(); if (codec instanceof ObjectMapper) { ObjectMapper mapper = (ObjectMapper) codec; context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper)); mapper.setSerializerProvider(new DefaultSerializerProvider.Impl()); mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setSerializationInclusion(Include.ALWAYS); } } }
<commit_msg>Revert "Catch and ignore CTRL_LOGOFF_EVENT when run as a windows service" This reverts commit a7ddf81b37b578b1448f83b0efb4f7116de0c3fb. <commit_before>from salt.utils.winservice import Service, instart import salt # Import third party libs import win32serviceutil import win32service import winerror import win32api # Import python libs import sys class MinionService(Service): def start(self): self.runflag = True self.log("Starting the Salt Minion") minion = salt.Minion() minion.start() while self.runflag: pass #self.sleep(10) #self.log("I'm alive ...") def stop(self): self.runflag = False self.log("Shutting down the Salt Minion") def console_event_handler(event): if event == 5: # Do nothing on CTRL_LOGOFF_EVENT return True return False def _main(): win32api.SetConsoleCtrlHandler(console_event_handler, 1) servicename = 'salt-minion' try: status = win32serviceutil.QueryServiceStatus(servicename) except win32service.error as details: if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST: instart(MinionService, servicename, 'Salt Minion') sys.exit(0) if status[1] == win32service.SERVICE_RUNNING: win32serviceutil.StopServiceWithDeps(servicename) win32serviceutil.StartService(servicename) else: win32serviceutil.StartService(servicename) if __name__ == '__main__': _main() <commit_after>from salt.utils.winservice import Service, instart import salt # Import third party libs import win32serviceutil import win32service import winerror # Import python libs import sys class MinionService(Service): def start(self): self.runflag = True self.log("Starting the Salt Minion") minion = salt.Minion() minion.start() while self.runflag: pass #self.sleep(10) #self.log("I'm alive ...") def stop(self): self.runflag = False self.log("Shutting down the Salt Minion") def _main(): servicename = 'salt-minion' try: status = win32serviceutil.QueryServiceStatus(servicename) except win32service.error as details: if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST: instart(MinionService, servicename, 'Salt Minion') sys.exit(0) if status[1] == win32service.SERVICE_RUNNING: win32serviceutil.StopServiceWithDeps(servicename) win32serviceutil.StartService(servicename) else: win32serviceutil.StartService(servicename) if __name__ == '__main__': _main()
<commit_msg>Modify forums directly in categories. <commit_before>from django.contrib import admin from forum.models import Category, Forum, Thread admin.site.register(Category) admin.site.register(Forum) admin.site.register(Thread) <commit_after>from django.contrib import admin from forum.models import Category, Forum, Thread class ForumInline(admin.StackedInline): model = Forum class CategoryAdmin(admin.ModelAdmin): inlines = [ForumInline] admin.site.register(Category, CategoryAdmin) admin.site.register(Thread)
<commit_msg>Add documentation of the new functions <commit_before> """Example of irreversible reaction.""" import os from chemkinlib.utils import Parser from chemkinlib.reactions import ReactionSystems from chemkinlib.config import DATA_DIRECTORY import numpy # USER INPUT: reaction (xml) file xml_filename = os.path.join(DATA_DIRECTORY, "rxnset_long.xml") parser = Parser.ReactionParser(xml_filename) # USER INPUTS (concentrations and temperatures) concentration = ({'H':1, 'H2':1, 'H2O':1, 'H2O2':1, 'HO2':1, 'O':1, "O2":1, "OH":1}) temperature = 1000 # Set up reaction system rxnsys = ReactionSystems.ReactionSystem(parser.reaction_list, parser.NASA_poly_coefs, temperature, concentration) for i in range(10): dt = 0.001 rxnsys.step(dt) # Compute and sort reaction rates rxnrates_dict = rxnsys.sort_reaction_rates() # display reaction rates by species for k, v in rxnrates_dict.items(): print("d[{0}]/dt : \t {1:e}".format(k, v)) <commit_after> """Example of irreversible reaction.""" import os from chemkinlib.utils import Parser from chemkinlib.reactions import ReactionSystems from chemkinlib.config import DATA_DIRECTORY import numpy # USER INPUT: reaction (xml) file xml_filename = os.path.join(DATA_DIRECTORY, "rxnset_long.xml") parser = Parser.ReactionParser(xml_filename) # USER INPUTS (concentrations and temperatures) concentration = ({'H':1, 'H2':1, 'H2O':0, 'H2O2':1, 'HO2':1, 'O':1, "O2":1, "OH":1}) temperature = 1000 # Set up reaction system rxnsys = ReactionSystems.ReactionSystem(parser.reaction_list, parser.NASA_poly_coefs, temperature, concentration) #compute the concentration change with timestep for i in range(10): dt = 0.001 print(rxnsys.step(dt)) # Compute and sort reaction rates rxnrates_dict = rxnsys.sort_reaction_rates() # display reaction rates by species for k, v in rxnrates_dict.items(): print("d[{0}]/dt : \t {1:e}".format(k, v))
<commit_msg>chore(tests): Remove crazy `import require` line <commit_before>'use strict'; import assert = require('assert'); import GitLabStateHelper from '../../src/lib/states'; const projectId = process.env.GITLAB_TEST_PROJECT; describe('States', function () { describe('constructor()', function () { it('should throw an error with invalid url', function() { assert.throws(() => { new GitLabStateHelper('ftp://foo.bar', '****'); }, /Invalid url!/); }); it('should throw an error without token', function() { assert.throws(() => { new GitLabStateHelper('http://localhost', '****'); }, /Invalid token!/); }); }); describe('getState()', function() { this.timeout(5000); it('should work', projectId ? async function() { const states = await new GitLabStateHelper(); const result1 = await states.getState(projectId, 'develop'); assert.strictEqual(typeof result1.status, 'string'); assert.ok(typeof result1.coverage === 'string' || result1.coverage === undefined); const result2 = await states.getState(projectId, 'develop'); assert.strictEqual(result2.status, result1.status); assert.strictEqual(result2.coverage, result1.coverage); } : () => Promise.resolve()); }); }); <commit_after>'use strict'; import assert from 'assert'; import GitLabStateHelper from '../../src/lib/states'; const projectId = process.env.GITLAB_TEST_PROJECT; describe('States', function () { describe('constructor()', function () { it('should throw an error with invalid url', function() { assert.throws(() => { new GitLabStateHelper('ftp://foo.bar', '****'); }, /Invalid url!/); }); it('should throw an error without token', function() { assert.throws(() => { new GitLabStateHelper('http://localhost', '****'); }, /Invalid token!/); }); }); describe('getState()', function() { this.timeout(5000); it('should work', projectId ? async function() { const states = await new GitLabStateHelper(); const result1 = await states.getState(projectId, 'develop'); assert.strictEqual(typeof result1.status, 'string'); assert.ok(typeof result1.coverage === 'string' || result1.coverage === undefined); const result2 = await states.getState(projectId, 'develop'); assert.strictEqual(result2.status, result1.status); assert.strictEqual(result2.coverage, result1.coverage); } : () => Promise.resolve()); }); });
<commit_msg>Return False early if mailgun API key isn't set locally <commit_before>import hmac import hashlib from rest_framework import permissions from rest_framework import exceptions from framework import sentry from website import settings class RequestComesFromMailgun(permissions.BasePermission): """Verify that request comes from Mailgun. Adapted here from conferences/message.py Signature comparisons as recomended from mailgun docs: https://documentation.mailgun.com/en/latest/user_manual.html#webhooks """ def has_permission(self, request, view): if request.method != 'POST': raise exceptions.MethodNotAllowed(method=request.method) data = request.data if not data: raise exceptions.ParseError('Request body is empty') signature = hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format( data['timestamp'], data['token'], ), digestmod=hashlib.sha256, ).hexdigest() if 'signature' not in data: error_message = 'Signature required in request body' sentry.log_message(error_message) raise exceptions.ParseError(error_message) if not hmac.compare_digest(unicode(signature), unicode(data['signature'])): raise exceptions.ParseError('Invalid signature') return True <commit_after>import hmac import hashlib from rest_framework import permissions from rest_framework import exceptions from framework import sentry from website import settings class RequestComesFromMailgun(permissions.BasePermission): """Verify that request comes from Mailgun. Adapted here from conferences/message.py Signature comparisons as recomended from mailgun docs: https://documentation.mailgun.com/en/latest/user_manual.html#webhooks """ def has_permission(self, request, view): if request.method != 'POST': raise exceptions.MethodNotAllowed(method=request.method) data = request.data if not data: raise exceptions.ParseError('Request body is empty') if not settings.MAILGUN_API_KEY: return False signature = hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format( data['timestamp'], data['token'], ), digestmod=hashlib.sha256, ).hexdigest() if 'signature' not in data: error_message = 'Signature required in request body' sentry.log_message(error_message) raise exceptions.ParseError(error_message) if not hmac.compare_digest(unicode(signature), unicode(data['signature'])): raise exceptions.ParseError('Invalid signature') return True
<commit_msg>Fix typo & import in UserFactory<commit_before>from feder.users import models import factory class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user-{0}'.format(n)) email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) password = factory.PosteGnerationMethodCall('set_password', 'password') class Meta: model = models.User django_get_or_create = ('username', ) <commit_after>import factory class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user-{0}'.format(n)) email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) password = factory.PostGenerationMethodCall('set_password', 'password') class Meta: model = 'users.User' django_get_or_create = ('username', )
<commit_msg>Sort imports per isort; fixes failure <commit_before>from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('schedule', '0010_events_set_missing_calendar'), ] operations = [ migrations.AlterField( model_name='event', name='calendar', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='schedule.Calendar', verbose_name='calendar'), ), ] <commit_after>import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('schedule', '0010_events_set_missing_calendar'), ] operations = [ migrations.AlterField( model_name='event', name='calendar', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='schedule.Calendar', verbose_name='calendar'), ), ]
<commit_msg>Make @ember/string a non-npm package And revert the unrelated project url. <commit_before>// Type definitions for @ember/string 3.0 // Project: https://emberjs.com/api/ember/3.4/modules/@ember%2Fstring, https://github.com/emberjs/ember-string // Definitions by: Mike North <https://github.com/mike-north> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { SafeString } from 'handlebars'; export function camelize(str: string): string; export function capitalize(str: string): string; export function classify(str: string): string; export function dasherize(str: string): string; export function decamelize(str: string): string; export function htmlSafe(str: string): SafeString; export function isHTMLSafe(str: any): str is SafeString; export function loc(template: string, args?: string[]): string; export function underscore(str: string): string; export function w(str: string): string[]; <commit_after>// Type definitions for non-npm package @ember/string 3.0 // Project: https://emberjs.com/api/ember/3.4/modules/@ember%2Fstring // Definitions by: Mike North <https://github.com/mike-north> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { SafeString } from 'handlebars'; export function camelize(str: string): string; export function capitalize(str: string): string; export function classify(str: string): string; export function dasherize(str: string): string; export function decamelize(str: string): string; export function htmlSafe(str: string): SafeString; export function isHTMLSafe(str: any): str is SafeString; export function loc(template: string, args?: string[]): string; export function underscore(str: string): string; export function w(str: string): string[];
<commit_msg>Save work on bounds checking <commit_before>import System.Environment import Control.Applicative import Control.Monad inputFile :: IO (FilePath) inputFile = head <$> getArgs outputFile :: IO (FilePath) outputFile = flip (!!) 1 <$> getArgs main :: IO () main = let content = readFile =<< inputFile in join $ writeFile <$> outputFile <*> content <commit_after>import System.Environment import Control.Applicative import Control.Monad import Data.Word -- Type definitions newtype City a = City a maxCities :: Word maxCities = 100000 minCities :: Word minCities = 2 toCity :: (Word a, Ord a) => a -> a -> City a toCity city numCities | city < minCities = error "The number of cities cannot be less than " ++ (read minCities) ++ "." | city > maxCities = error "The number of cities cannot be greater than " ++ (read maxCities) ++ "." | otherwise = City city fromCity :: City a -> a fromCity (City city) = city newtype Machine a = Machine a maxMachines :: City Word -> Word maxMachines = maxCities minMachines :: Word minMachines = minCities toMachine :: (Word a, Ord a) => a -> a -> a -> Machine a toMachine machine numMachines numCities | machine < minMachines = error "The number of machines cannot be less than " ++ (read minMachines) ++ "." | machine > maxMachines = error "The number of machines cannot be greater than " ++ (read maxMachines) ++ "." | otherwise = Machine machine fromMachine :: Machine a -> a fromMachine (Machine machine) = machine newtype Road a = Road a maxRoads :: City Word -> Word maxRoads numCities = (fromCity numCities) - 1 minRoads :: Word minRoads = minCities - 1 toRoad -- Core logic inputFile :: IO (FilePath) inputFile = head <$> getArgs outputFile :: IO (FilePath) outputFile = flip (!!) 1 <$> getArgs main :: IO () main = let content = readFile =<< inputFile in join $ writeFile <$> outputFile <*> content parseInput :: String -> (N Word, K Word, )
<commit_msg>Change update_addon_node() to return the Addon node, whether created or found. <commit_before>"""Addon utilities.""" # Copyright 2015 Solinea, 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. def update_addon_node(): """Update the persistent resource graph's Addon node. This is much simpler than the update_xxxxx_nodes functions that update nodes for cloud entities. There will be only one Addon node in the table, and all add-ons will be owned by it. If we're running for the first time, the Addon node needs to be created. If it's already there, we leave it alone. """ from goldstone.core.models import Addon Addon.objects.get_or_create(native_id="Add-on", native_name="Add-on") <commit_after>"""Addon utilities.""" # Copyright 2015 Solinea, 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. def update_addon_node(): """Update the persistent resource graph's Addon node. This is much simpler than the update_xxxxx_nodes functions that update nodes for cloud entities. There will be only one Addon node in the table, and all add-ons will be owned by it. If we're running for the first time, the Addon node needs to be created. If it's already there, we leave it alone. This also differs from update_xxxxx_nodes by returning the Addon node that is found or created. """ from goldstone.core.models import Addon result, _ = Addon.objects.get_or_create(native_id="Add-on", native_name="Add-on") return result
<commit_msg>Fix spacing in demo for FileUpload. <commit_before>package to.etc.domuidemo.pages.overview.allcomponents; import to.etc.domui.component.upload.FileUpload2; import to.etc.domui.component.upload.FileUploadMultiple; import to.etc.domui.component2.form4.FormBuilder; import to.etc.domui.dom.html.Div; import to.etc.domui.dom.html.HTag; /** * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on 14-11-17. */ public class FileUploadFragment extends Div { @Override public void createContent() throws Exception { add(new HTag(2, "File upload component").css("ui-header")); FormBuilder fb = new FormBuilder(this); FileUpload2 u1 = new FileUpload2("png", "jpg", "gif", "jpeg"); fb.label("Select an image").item(u1); FileUploadMultiple u2 = new FileUploadMultiple("png", "jpg", "gif", "jpeg"); fb.label("Select multiple").item(u2); //FileUpload u2 = new FileUpload("png", "jpg", "gif", "jpeg"); //fb.label("OLD").item(u2); } } <commit_after>package to.etc.domuidemo.pages.overview.allcomponents; import to.etc.domui.component.layout.ContentPanel; import to.etc.domui.component.upload.FileUpload2; import to.etc.domui.component.upload.FileUploadMultiple; import to.etc.domui.component2.form4.FormBuilder; import to.etc.domui.dom.html.Div; import to.etc.domui.dom.html.HTag; /** * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on 14-11-17. */ public class FileUploadFragment extends Div { @Override public void createContent() throws Exception { add(new HTag(2, "File upload component").css("ui-header")); ContentPanel cp = new ContentPanel(); add(cp); FormBuilder fb = new FormBuilder(cp); FileUpload2 u1 = new FileUpload2("png", "jpg", "gif", "jpeg"); fb.label("Select an image").item(u1); FileUploadMultiple u2 = new FileUploadMultiple("png", "jpg", "gif", "jpeg"); fb.label("Select multiple").item(u2); //FileUpload u2 = new FileUpload("png", "jpg", "gif", "jpeg"); //fb.label("OLD").item(u2); } }
<commit_msg>Fix params passed to i2c.init() to include DEVICE_ADDRESS in the first position. Otherwise SDA becomes SCL_PIN and SCL becomes Default. <commit_before> //static char tag[] = "task_cpp_utils"; class I2CScanner: public Task { void run(void *data) override { I2C i2c; i2c.init((gpio_num_t)SDA_PIN, (gpio_num_t)SCL_PIN); i2c.scan(); } // End run }; static I2CScanner i2cScanner = I2CScanner(); void task_i2c_scanner(void *ignore) { i2cScanner.start(); FreeRTOS::deleteTask(); } <commit_after> //static char tag[] = "task_cpp_utils"; class I2CScanner: public Task { void run(void *data) override { I2C i2c; i2c.init((uint8_t)DEVICE_ADDRESS, (gpio_num_t)SDA_PIN, (gpio_num_t)SCL_PIN); i2c.scan(); } // End run }; static I2CScanner i2cScanner = I2CScanner(); void task_i2c_scanner(void *ignore) { i2cScanner.start(); FreeRTOS::deleteTask(); }
<commit_msg>Replace / with - in image domain names <commit_before>from dock import client def fmt(container): image, name = ns(container) return '[{image}/{name}]'.format(image=image, name=name) def ns(container): image_name = container.attrs['Image'] image = client.images.get(image_name) if len(image.tags) > 0: image_name = image.tags[0].split(":")[0] else: image_name = image.short_id.split(":")[1] return image_name, container.name def exposed_ports(container): ports = container.attrs['Config']['ExposedPorts'].keys() for port in ports: port, protocol = port.split('/')[0], port.split('/')[1] yield port, protocol def exposes_ports(container): return 'ExposedPorts' in container.attrs['Config']<commit_after>from dock import client def fmt(container): image, name = ns(container) return '[{image}/{name}]'.format(image=image, name=name) def ns(container): image_name = container.attrs['Image'] image = client.images.get(image_name) if len(image.tags) > 0: image_name = image.tags[0].split(":")[0] else: image_name = image.short_id.split(":")[1] image_name.replace('/', '-') return image_name, container.name def exposed_ports(container): ports = container.attrs['Config']['ExposedPorts'].keys() for port in ports: port, protocol = port.split('/')[0], port.split('/')[1] yield port, protocol def exposes_ports(container): return 'ExposedPorts' in container.attrs['Config']
<commit_msg>Mark the sub-package server as deprecated <commit_before>// +build go1.9 package server import ( "github.com/xgfone/go-tools/net2" ) type ( // THandle is the type alias of net2.THandle. // // DEPRECATED!!! Please the package net2. THandle = net2.THandle // THandleFunc is the type alias of net2.THandleFunc. // // DEPRECATED!!! Please the package net2. THandleFunc = net2.THandleFunc ) var ( // TCPWrapError is the alias of net2.TCPWrapError. // // DEPRECATED!!! Please the package net2. TCPWrapError = net2.TCPWrapError // TCPServerForever is the alias of net2.TCPServerForever. // // DEPRECATED!!! Please the package net2. TCPServerForever = net2.TCPServerForever // DialTCP is the alias of net2.DialTCP. // // DEPRECATED!!! Please the package net2. DialTCP = net2.DialTCP // DialTCPWithAddr is the alias of net2.DialTCPWithAddr. // // DEPRECATED!!! Please the package net2. DialTCPWithAddr = net2.DialTCPWithAddr ) <commit_after>// +build go1.9 // Package server is deprecated. which is migrated into net2. package server import ( "github.com/xgfone/go-tools/net2" ) type ( // THandle is the type alias of net2.THandle. // // DEPRECATED!!! Please the package net2. THandle = net2.THandle // THandleFunc is the type alias of net2.THandleFunc. // // DEPRECATED!!! Please the package net2. THandleFunc = net2.THandleFunc ) var ( // TCPWrapError is the alias of net2.TCPWrapError. // // DEPRECATED!!! Please the package net2. TCPWrapError = net2.TCPWrapError // TCPServerForever is the alias of net2.TCPServerForever. // // DEPRECATED!!! Please the package net2. TCPServerForever = net2.TCPServerForever // DialTCP is the alias of net2.DialTCP. // // DEPRECATED!!! Please the package net2. DialTCP = net2.DialTCP // DialTCPWithAddr is the alias of net2.DialTCPWithAddr. // // DEPRECATED!!! Please the package net2. DialTCPWithAddr = net2.DialTCPWithAddr )
<commit_msg>Add a menu to the test runner. <commit_before>from AppKit import * from PyObjCTools import AppHelper class _VanillaMiniAppDelegate(NSObject): def applicationShouldTerminateAfterLastWindowClosed_(self, notification): return True def executeVanillaTest(cls, **kwargs): """ Execute a Vanilla UI class in a mini application. """ app = NSApplication.sharedApplication() delegate = _VanillaMiniAppDelegate.alloc().init() app.setDelegate_(delegate) cls(**kwargs) app.activateIgnoringOtherApps_(True) AppHelper.runEventLoop() <commit_after>from AppKit import * from PyObjCTools import AppHelper class _VanillaMiniAppDelegate(NSObject): def applicationShouldTerminateAfterLastWindowClosed_(self, notification): return True def executeVanillaTest(cls, **kwargs): """ Execute a Vanilla UI class in a mini application. """ app = NSApplication.sharedApplication() delegate = _VanillaMiniAppDelegate.alloc().init() app.setDelegate_(delegate) mainMenu = NSMenu.alloc().initWithTitle_("Vanilla Test") fileMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("File", None, "") fileMenu = NSMenu.alloc().initWithTitle_("File") fileMenuItem.setSubmenu_(fileMenu) mainMenu.addItem_(fileMenuItem) editMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Edit", None, "") editMenu = NSMenu.alloc().initWithTitle_("Edit") editMenuItem.setSubmenu_(editMenu) mainMenu.addItem_(editMenuItem) helpMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Help", None, "") helpMenu = NSMenu.alloc().initWithTitle_("Help") helpMenuItem.setSubmenu_(helpMenu) mainMenu.addItem_(helpMenuItem) app.setMainMenu_(mainMenu) cls(**kwargs) app.activateIgnoringOtherApps_(True) AppHelper.runEventLoop()
<commit_msg>Add positive test for search <commit_before> import pytest from pages.home import HomePage class TestAvailableTasks(): @pytest.mark.nondestructive def test_assign_tasks(self, base_url, selenium, nonrepeatable_assigned_task, new_user): home_page = HomePage(selenium, base_url).open() home_page.login(new_user) available_tasks_page = home_page.click_available_tasks() home_page.search_for_task(nonrepeatable_assigned_task.name) assert len(available_tasks_page.available_tasks) == 0 <commit_after> import pytest from pages.home import HomePage class TestAvailableTasks(): @pytest.mark.nondestructive def test_assign_tasks(self, base_url, selenium, nonrepeatable_assigned_task, task, new_user): home_page = HomePage(selenium, base_url).open() home_page.login(new_user) available_tasks_page = home_page.click_available_tasks() # Check if assignable task is found home_page.search_for_task(task.name) assert len(available_tasks_page.available_tasks) home_page.search_for_task(nonrepeatable_assigned_task.name) assert len(available_tasks_page.available_tasks) == 0
<commit_msg>Disable error dialog on Windows It make the test hang for nothing <commit_before> /* * Catch main file for faster compilation. This file is the only one defining the * main function. */ <commit_after> // On Windows, disable the "Application error" dialog box, because it // requires an human intervention, and there is no one on Appveyor. // // On UNIX, does nothing void silent_crash_handlers(); int main(int argc, char* argv[]) { silent_crash_handlers(); return Catch::Session().run(argc, argv); } #if (defined(WIN32) || defined(WIN64)) #include <windows.h> void silent_crash_handlers() { SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); } #else void silent_crash_handlers() {} #endif
<commit_msg>Use correct cffi type for 'value' <commit_before> namespace nme { // If you put this structure on the stack, then you do not have to worry about GC. // If you store this in a heap structure, then you will need to use GC roots for mValue... struct ByteArray { ByteArray(int inSize); ByteArray(const ByteArray &inRHS); ByteArray(); ByteArray(struct _value *Value); ByteArray(const QuickVec<unsigned char> &inValue); ByteArray(const char *inResourceName); void Resize(int inSize); int Size() const; unsigned char *Bytes(); const unsigned char *Bytes() const; bool Ok() { return mValue!=0; } struct _value *mValue; static ByteArray FromFile(const OSChar *inFilename); #ifdef HX_WINDOWS static ByteArray FromFile(const char *inFilename); #endif }; #ifdef ANDROID ByteArray AndroidGetAssetBytes(const char *); struct FileInfo { int fd; off_t offset; off_t length; }; FileInfo AndroidGetAssetFD(const char *); #endif } #endif <commit_after> namespace nme { // If you put this structure on the stack, then you do not have to worry about GC. // If you store this in a heap structure, then you will need to use GC roots for mValue... struct ByteArray { ByteArray(int inSize); ByteArray(const ByteArray &inRHS); ByteArray(); ByteArray(value Value); ByteArray(const QuickVec<unsigned char> &inValue); ByteArray(const char *inResourceName); void Resize(int inSize); int Size() const; unsigned char *Bytes(); const unsigned char *Bytes() const; bool Ok() { return mValue!=0; } value mValue; static ByteArray FromFile(const OSChar *inFilename); #ifdef HX_WINDOWS static ByteArray FromFile(const char *inFilename); #endif }; #ifdef ANDROID ByteArray AndroidGetAssetBytes(const char *); struct FileInfo { int fd; off_t offset; off_t length; }; FileInfo AndroidGetAssetFD(const char *); #endif } #endif
<commit_msg>Add some flags to nbgrader assign <commit_before>from IPython.config.loader import Config from IPython.config.application import catch_config_error from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp class AssignApp(CustomNbConvertApp): name = Unicode(u'nbgrader-assign') description = Unicode(u'Prepare a student version of an assignment by removing solutions') def _export_format_default(self): return 'notebook' def build_extra_config(self): self.extra_config = Config() self.extra_config.Exporter.preprocessors = [ 'nbgrader.preprocessors.IncludeHeaderFooter', 'nbgrader.preprocessors.ClearSolutions', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor' ] self.config.merge(self.extra_config) <commit_after>from IPython.config.loader import Config from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp from nbgrader.apps.customnbconvertapp import aliases as base_aliases from nbgrader.apps.customnbconvertapp import flags as base_flags aliases = {} aliases.update(base_aliases) aliases.update({ 'header': 'IncludeHeaderFooter.header', 'footer': 'IncludeHeaderFooter.footer' }) flags = {} flags.update(base_flags) flags.update({ }) class AssignApp(CustomNbConvertApp): name = Unicode(u'nbgrader-assign') description = Unicode(u'Prepare a student version of an assignment by removing solutions') aliases = aliases flags = flags def _export_format_default(self): return 'notebook' def build_extra_config(self): self.extra_config = Config() self.extra_config.Exporter.preprocessors = [ 'nbgrader.preprocessors.IncludeHeaderFooter', 'nbgrader.preprocessors.ClearSolutions', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor' ] self.config.merge(self.extra_config)
<commit_msg>Update test case; VLA's are now supported. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@64168 91177308-0d34-0410-b5e6-96231b3b80d8 <commit_before>// RUN: clang -verify -emit-llvm -o - %s int f0(int x) { int vla[x]; return vla[x-1]; // expected-error {{cannot compile this return inside scope with VLA yet}} } <commit_after>// RUN: clang -verify -emit-llvm -o - %s void *x = L"foo"; // expected-error {{cannot compile this wide string yet}}
<commit_msg>Fix service error filter tests due to error message refactoring <commit_before>package io.spacedog.test; import org.junit.Test; import io.spacedog.client.SpaceDog; import io.spacedog.client.http.SpaceRequest; public class ServiceErrorFilterTest extends SpaceTest { @Test public void catchesFluentResourceErrors() { prepareTest(); SpaceDog superadmin = clearServer(); // should fail to access invalid route SpaceRequest.get("/1/toto")// .backend(superadmin.backend())// .go(404)// .assertEquals("path [/1/toto] invalid", "error.message"); // should fail to use this method for this valid route superadmin.put("/1/login").go(405)// .assertEquals("method [PUT] invalid for path [/1/login]", "error.message"); } @Test public void notifySuperdogsForInternalServerErrors() { // prepare prepareTest(); // this fails and send notification to superdogs with error details SpaceRequest.post("/1/admin/_return_500").go(500); } } <commit_after>package io.spacedog.test; import org.junit.Test; import io.spacedog.client.SpaceDog; import io.spacedog.client.http.SpaceRequest; public class ServiceErrorFilterTest extends SpaceTest { @Test public void catchesFluentResourceErrors() { prepareTest(); SpaceDog superadmin = clearServer(); // should fail to access invalid route SpaceRequest.get("/1/toto")// .backend(superadmin.backend())// .go(404)// .assertEquals("[path][/1/toto] not found", "error.message"); // should fail to use this method for this valid route superadmin.put("/1/login").go(405)// .assertEquals("[PUT][/1/login] is not supported", "error.message"); } @Test public void notifySuperdogsForInternalServerErrors() { // prepare prepareTest(); // this fails and send notification to superdogs with error details SpaceRequest.post("/1/admin/_return_500").go(500); } }
<commit_msg>Update env id generator test to handle hypenated lake names [#121817095] <commit_before>package helpers_test import ( "crypto/rand" "errors" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/pivotal-cf-experimental/bosh-bootloader/fakes" "github.com/pivotal-cf-experimental/bosh-bootloader/helpers" ) var _ = Describe("EnvIDGenerator", func() { Describe("Generate", func() { It("generates a env id with a lake and timestamp", func() { generator := helpers.NewEnvIDGenerator(rand.Reader) envID, err := generator.Generate() Expect(err).NotTo(HaveOccurred()) Expect(envID).To(MatchRegexp(`bbl-env-[a-z]+-\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z`)) }) Context("when there are errors", func() { It("it returns the error", func() { anError := errors.New("banana") badReader := fakes.Reader{} badReader.ReadCall.Returns.Error = anError generator := helpers.NewEnvIDGenerator(&badReader) _, err := generator.Generate() Expect(err).To(Equal(anError)) }) }) }) }) <commit_after>package helpers_test import ( "crypto/rand" "errors" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/pivotal-cf-experimental/bosh-bootloader/fakes" "github.com/pivotal-cf-experimental/bosh-bootloader/helpers" ) var _ = Describe("EnvIDGenerator", func() { Describe("Generate", func() { It("generates a env id with a lake and timestamp", func() { generator := helpers.NewEnvIDGenerator(rand.Reader) envID, err := generator.Generate() Expect(err).NotTo(HaveOccurred()) Expect(envID).To(MatchRegexp(`bbl-env-([a-z]+-{1}){1,2}\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z`)) }) Context("when there are errors", func() { It("it returns the error", func() { anError := errors.New("banana") badReader := fakes.Reader{} badReader.ReadCall.Returns.Error = anError generator := helpers.NewEnvIDGenerator(&badReader) _, err := generator.Generate() Expect(err).To(Equal(anError)) }) }) }) })
<commit_msg>Make NagiosPluginHTTP available from monitoring.nagios.plugin package. <commit_before>from monitoring.nagios.plugin.base import NagiosPlugin from monitoring.nagios.plugin.snmp import NagiosPluginSNMP from monitoring.nagios.plugin.secureshell import NagiosPluginSSH from monitoring.nagios.plugin.database import NagiosPluginMSSQL from monitoring.nagios.plugin.wmi import NagiosPluginWMI<commit_after>from monitoring.nagios.plugin.base import NagiosPlugin from monitoring.nagios.plugin.snmp import NagiosPluginSNMP from monitoring.nagios.plugin.secureshell import NagiosPluginSSH from monitoring.nagios.plugin.database import NagiosPluginMSSQL from monitoring.nagios.plugin.wmi import NagiosPluginWMI from monitoring.nagios.plugin.http import NagiosPluginHTTP
<commit_msg>Make reachable depend on availability <commit_before>package com.phonegap.demo; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.net.*; import android.webkit.WebView; public class NetworkManager { Context mCtx; WebView mView; ConnectivityManager sockMan; NetworkManager(Context ctx, WebView view) { mCtx = ctx; mView = view; sockMan = (ConnectivityManager) mCtx.getSystemService(Context.CONNECTIVITY_SERVICE); } public boolean isAvailable() { NetworkInfo info = sockMan.getActiveNetworkInfo(); return info.isConnected(); } public boolean isReachable(String uri) { boolean reached = true; try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(uri); httpclient.execute(httpget); } catch (Exception e) { reached = false;} return reached; } } <commit_after>package com.phonegap.demo; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.net.*; import android.webkit.WebView; public class NetworkManager { Context mCtx; WebView mView; ConnectivityManager sockMan; NetworkManager(Context ctx, WebView view) { mCtx = ctx; mView = view; sockMan = (ConnectivityManager) mCtx.getSystemService(Context.CONNECTIVITY_SERVICE); } public boolean isAvailable() { NetworkInfo info = sockMan.getActiveNetworkInfo(); return info.isConnected(); } public boolean isReachable(String uri) { boolean reached = isAvailable(); try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(uri); httpclient.execute(httpget); } catch (Exception e) { reached = false;} return reached; } }
<commit_msg>Create the Subscriber Form - Part II > Update the Form <commit_before>from django import forms from django.contrib.auth.forms import UserCreationForm class SubscriberForm(UserCreationForm): email = forms.EmailField( required=True, widget=forms.TextInput(attrs={'class':'form-control'}) ) username = forms.CharField( widget=forms.TextInput(attrs={'class':'form-control'}) ) password1 = forms.CharField( widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'}) ) password2 = forms.CharField( widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'}) ) <commit_after>from django import forms from django.contrib.auth.forms import UserCreationForm from .models import Subscriber class AddressMixin(forms.ModelForm): class Meta: model = Subscriber fields = ('address_one', 'address_two', 'city', 'state',) widgets = { 'address_one': forms.TextInput(attrs={'class':'form-control'}), 'address_two': forms.TextInput(attrs={'class':'form-control'}), 'city': forms.TextInput(attrs={'class':'form-control'}), 'state': forms.TextInput(attrs={'class':'form-control'}), } class SubscriberForm(AddressMixin, UserCreationForm): first_name = forms.CharField( required=True, widget=forms.TextInput(attrs={'class':'form-control'}) ) last_name = forms.CharField( required=True, widget=forms.TextInput(attrs={'class':'form-control'}) ) email = forms.EmailField( required=True, widget=forms.TextInput(attrs={'class':'form-control'}) ) username = forms.CharField( widget=forms.TextInput(attrs={'class':'form-control'}) ) password1 = forms.CharField( widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'}) ) password2 = forms.CharField( widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'}) )
<commit_msg>Add some debug for debian box <commit_before>import subprocess import string class Command(object): def execute(self, command: str): cliArgs = self.parseCliArgs(command) process = subprocess.Popen(cliArgs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = process.communicate() if process.returncode != 0: return False return output.decode("utf-8").strip() def parseCliArgs(self, command: str): rawArgs = command.split(" ") parsedArgs = [] tmpString = False isSingle = False isDouble = False for arg in rawArgs: # handle strings in single quotes if arg.startswith("'") and isSingle == False and isDouble == False: isSingle = True tmpString = arg elif arg.endswith("'") and isSingle == True: arg = "%s %s" % (tmpString, arg) parsedArgs.append(arg) isSingle = False tmpString = False # handle strings in double quotes elif arg.startswith('"') and isDouble == False and isSingle == False: isDouble = True tmpString = arg elif arg.endswith('"') and isDouble == True: arg = "%s %s" % (tmpString, arg) parsedArgs.append(arg) isDouble = False tmpString = False # extend current string elif tmpString != False: tmpString = "%s %s" % (tmpString, arg) else: parsedArgs.append(arg) return parsedArgs<commit_after>import subprocess import string from pprint import pprint class Command(object): def execute(self, command: str): cliArgs = self.parseCliArgs(command) pprint(cliArgs) process = subprocess.Popen(cliArgs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = process.communicate() if process.returncode != 0: return False return output.decode("utf-8").strip() def parseCliArgs(self, command: str): rawArgs = command.split(" ") parsedArgs = [] tmpString = False isSingle = False isDouble = False for arg in rawArgs: # handle strings in single quotes if arg.startswith("'") and isSingle == False and isDouble == False: isSingle = True tmpString = arg elif arg.endswith("'") and isSingle == True: arg = "%s %s" % (tmpString, arg) parsedArgs.append(arg) isSingle = False tmpString = False # handle strings in double quotes elif arg.startswith('"') and isDouble == False and isSingle == False: isDouble = True tmpString = arg elif arg.endswith('"') and isDouble == True: arg = "%s %s" % (tmpString, arg) parsedArgs.append(arg) isDouble = False tmpString = False # extend current string elif tmpString != False: tmpString = "%s %s" % (tmpString, arg) else: parsedArgs.append(arg) return parsedArgs