text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add tests for char in string -- including required exceptions for non-char in string.
from test_support import TestFailed class base_set: def __init__(self, el): self.el = el class set(base_set): def __contains__(self, el): return self.el == el class seq(base_set): def __getitem__(self, n): return [self.el][n] def check(ok, *args): if not ok: raise TestFailed, join(map(str, args), " ") a = base_set(1) b = set(1) c = seq(1) check(1 in b, "1 not in set(1)") check(0 not in b, "0 in set(1)") check(1 in c, "1 not in seq(1)") check(0 not in c, "0 in seq(1)") try: 1 in a check(0, "in base_set did not raise error") except AttributeError: pass try: 1 not in a check(0, "not in base_set did not raise error") except AttributeError: pass # Test char in string check('c' in 'abc', "'c' not in 'abc'") check('d' not in 'abc', "'d' in 'abc'") try: '' in 'abc' check(0, "'' in 'abc' did not raise error") except TypeError: pass try: 'ab' in 'abc' check(0, "'ab' in 'abc' did not raise error") except TypeError: pass try: None in 'abc' check(0, "None in 'abc' did not raise error") except TypeError: pass
from test_support import TestFailed class base_set: def __init__(self, el): self.el = el class set(base_set): def __contains__(self, el): return self.el == el class seq(base_set): def __getitem__(self, n): return [self.el][n] def check(ok, *args): if not ok: raise TestFailed, join(map(str, args), " ") a = base_set(1) b = set(1) c = seq(1) check(1 in b, "1 not in set(1)") check(0 not in b, "0 in set(1)") check(1 in c, "1 not in seq(1)") check(0 not in c, "0 in seq(1)") try: 1 in a check(0, "in base_set did not raise error") except AttributeError: pass try: 1 not in a check(0, "not in base_set did not raise error") except AttributeError: pass
TST: Remove yield from datasets tests Remove yield which is pending deprecation in pytest xref #4000
import importlib import numpy as np import pandas as pd import nose import pytest import statsmodels.datasets from statsmodels.datasets.utils import Dataset exclude = ['check_internet', 'clear_data_home', 'get_data_home', 'get_rdataset', 'tests', 'utils', 'webuse'] datasets = [] for dataset_name in dir(statsmodels.datasets): if not dataset_name.startswith('_') and dataset_name not in exclude: datasets.append(dataset_name) # TODO: Remove nottest when nose support is dropped @nose.tools.nottest @pytest.mark.parametrize('dataset_name', datasets) def test_dataset(dataset_name): dataset = importlib.import_module('statsmodels.datasets.' + dataset_name) data = dataset.load() assert isinstance(data, Dataset) assert isinstance(data.data, np.recarray) df_data = dataset.load_pandas() assert isinstance(df_data, Dataset) assert isinstance(df_data.data, pd.DataFrame) # TODO: Remove when nose support is dropped def test_all_datasets(): for dataset in datasets: test_dataset(dataset)
import numpy as np import pandas as pd import statsmodels.datasets as datasets from statsmodels.datasets import co2 from statsmodels.datasets.utils import Dataset def test_co2_python3(): # this failed in pd.to_datetime on Python 3 with pandas <= 0.12.0 dta = co2.load_pandas() class TestDatasets(object): @classmethod def setup_class(cls): exclude = ['check_internet', 'clear_data_home', 'get_data_home', 'get_rdataset', 'tests', 'utils', 'webuse'] cls.sets = [] for dataset_name in dir(datasets): if not dataset_name.startswith('_') and dataset_name not in exclude: cls.sets.append(dataset_name) def check(self, dataset_name): dataset = __import__('statsmodels.datasets.' + dataset_name, fromlist=['']) data = dataset.load() assert isinstance(data, Dataset) assert isinstance(data.data, np.recarray) df_data = dataset.load_pandas() assert isinstance(data, Dataset) assert isinstance(df_data.data, pd.DataFrame) def test_all_datasets(self): for dataset_name in self.sets: yield (self.check, dataset_name)
Allow 15% deviation of memory attack integration test Signed-off-by: Xabier Larrakoetxea <30fb0ea44f2104eb1a81e793d922a064c3916c2f@gmail.com>
// +build integration package memory import ( "context" "runtime" "testing" "time" "github.com/stretchr/testify/assert" ) func TestMemoryAllocationAttack(t *testing.T) { assert := assert.New(t) var size uint64 = 200 * MiB ma, err := NewMemAllocation(size) assert.NoError(err, "Creation of memory allocator shouldn't error") // Get current memory var mem runtime.MemStats runtime.ReadMemStats(&mem) startMem := mem.Alloc // Allocate memory and test if increased. ma.Apply(context.TODO()) time.Sleep(1 * time.Millisecond) runtime.ReadMemStats(&mem) endMem := mem.Alloc // Let 10% margin delta from the wanted size assert.InDelta((endMem - startMem), size, float64(size)*0.15, "current memory allocation should be wanted allocation (15% deviation)") // Free memory and test if released. ma.Revert() time.Sleep(1 * time.Millisecond) runtime.ReadMemStats(&mem) // Let 10% margin delta from the wanted size assert.InDelta(startMem, mem.Alloc, float64(size)*0.15, "current memory and initial memory should be equal (15% deviation)") }
// +build integration package memory import ( "context" "runtime" "testing" "time" "github.com/stretchr/testify/assert" ) func TestMemoryAllocationAttack(t *testing.T) { assert := assert.New(t) var size uint64 = 200 * MiB ma, err := NewMemAllocation(size) assert.NoError(err, "Creation of memory allocator shouldn't error") // Get current memory var mem runtime.MemStats runtime.ReadMemStats(&mem) startMem := mem.Alloc // Allocate memory and test if increased. ma.Apply(context.TODO()) time.Sleep(1 * time.Millisecond) runtime.ReadMemStats(&mem) endMem := mem.Alloc // Let 10% margin delta from the wanted size assert.InDelta((endMem - startMem), size, float64(size)*0.1, "current memory allocation should be wanted allocation (5% deviation)") // Free memory and test if released. ma.Revert() time.Sleep(1 * time.Millisecond) runtime.ReadMemStats(&mem) // Let 10% margin delta from the wanted size assert.InDelta(startMem, mem.Alloc, float64(size)*0.1, "current memory and initial memory should be equal (5% deviation)") }
Remove old user from adorsys url paths
package de.fau.amos.virtualledger.server.banking.adorsys.api; import org.springframework.stereotype.Component; /** * Class that holds all configuration required for the banking api access * examples: URL of the banking api, dummy configuration, ... */ @Component public class BankingApiConfiguration { private final String bankingApiUrlAbsolute = "https://multibanking-service.dev.adorsys.de:443/api/v1/"; private final String bankAccessApiUrlRelative = "bankaccesses"; private final String bankAccountApiUrlRelative = "bankaccesses/{accessId}/accounts"; private final String bankAccountSyncApiUrlRelative = "bankaccesses/{accessId}/accounts/{accountId}/sync"; /** * username of the test user that does not use adorsys api but dummies */ private final String testUserName = "test@user.de"; public String getBankingApiUrlAbsolute() { return bankingApiUrlAbsolute; } public String getBankAccessApiUrlRelative() { return bankAccessApiUrlRelative; } public String getBankAccountApiUrlRelative() { return bankAccountApiUrlRelative; } public String getBankAccountSyncApiUrlRelative() { return bankAccountSyncApiUrlRelative; } public String getTestUserName() { return testUserName; } }
package de.fau.amos.virtualledger.server.banking.adorsys.api; import org.springframework.stereotype.Component; /** * Class that holds all configuration required for the banking api access * examples: URL of the banking api, dummy configuration, ... */ @Component public class BankingApiConfiguration { private final String bankingApiUrlAbsolute = "https://multibanking-service.dev.adorsys.de:443/api/v1/"; private final String bankAccessApiUrlRelative = "users/{userId}/bankaccesses"; private final String bankAccountApiUrlRelative = "users/{userId}/bankaccesses/{accessId}/accounts"; private final String bankAccountSyncApiUrlRelative = "users/{userId}/bankaccesses/{accessId}/accounts/{accountId}/sync"; /** * username of the test user that does not use adorsys api but dummies */ private final String testUserName = "test@user.de"; public String getBankingApiUrlAbsolute() { return bankingApiUrlAbsolute; } public String getBankAccessApiUrlRelative() { return bankAccessApiUrlRelative; } public String getBankAccountApiUrlRelative() { return bankAccountApiUrlRelative; } public String getBankAccountSyncApiUrlRelative() { return bankAccountSyncApiUrlRelative; } public String getTestUserName() { return testUserName; } }
Add validate_night to public API
# # See top-level LICENSE.rst file for Copyright information # # -*- coding: utf-8 -*- """ desispec.io =========== Tools for data and metadata I/O. """ # help with 2to3 support from __future__ import absolute_import, division from .meta import (findfile, get_exposures, get_files, rawdata_root, specprod_root, validate_night) from .frame import read_frame, write_frame from .sky import read_sky, write_sky from .fiberflat import read_fiberflat, write_fiberflat from .fibermap import read_fibermap, write_fibermap, empty_fibermap from .brick import Brick from .qa import read_qa_frame, write_qa_frame from .zfind import read_zbest, write_zbest from .image import read_image, write_image from .util import (header2wave, fitsheader, native_endian, makepath, write_bintable, iterfiles) from .fluxcalibration import ( read_stdstar_templates, write_stdstar_model, read_flux_calibration, write_flux_calibration) from .filters import read_filter_response from .download import download, filepath2url from .crc import memcrc, cksum from .database import (load_brick, is_night, load_night, is_flavor, load_flavor, get_bricks_by_name, get_brickid_by_name, load_data)
# # See top-level LICENSE.rst file for Copyright information # # -*- coding: utf-8 -*- """ desispec.io =========== Tools for data and metadata I/O. """ # help with 2to3 support from __future__ import absolute_import, division from .meta import findfile, get_exposures, get_files, rawdata_root, specprod_root from .frame import read_frame, write_frame from .sky import read_sky, write_sky from .fiberflat import read_fiberflat, write_fiberflat from .fibermap import read_fibermap, write_fibermap, empty_fibermap from .brick import Brick from .qa import read_qa_frame, write_qa_frame from .zfind import read_zbest, write_zbest from .image import read_image, write_image from .util import (header2wave, fitsheader, native_endian, makepath, write_bintable, iterfiles) from .fluxcalibration import ( read_stdstar_templates, write_stdstar_model, read_flux_calibration, write_flux_calibration) from .filters import read_filter_response from .download import download, filepath2url from .crc import memcrc, cksum from .database import (load_brick, is_night, load_night, is_flavor, load_flavor, get_bricks_by_name, get_brickid_by_name, load_data)
Add ) as sentence end marker to cap word after :-)
package ee.ioc.phon.android.speak.service; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Constants { public static final Set<Character> CHARACTERS_WS = new HashSet<>(Arrays.asList(new Character[]{' ', '\n', '\t'})); // Symbols that should not be preceded by space in a written text. public static final Set<Character> CHARACTERS_PUNCT = new HashSet<>(Arrays.asList(new Character[]{',', ':', ';', '.', '!', '?'})); // Symbols after which the next word should be capitalized. // We include ) because ;-) often finishes a sentence. public static final Set<Character> CHARACTERS_EOS = new HashSet<>(Arrays.asList(new Character[]{'.', '!', '?', ')'})); }
package ee.ioc.phon.android.speak.service; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Constants { public static final Set<Character> CHARACTERS_WS = new HashSet<>(Arrays.asList(new Character[]{' ', '\n', '\t'})); // Symbols that should not be preceded by space in a written text. public static final Set<Character> CHARACTERS_PUNCT = new HashSet<>(Arrays.asList(new Character[]{',', ':', ';', '.', '!', '?'})); // Symbols after which the next word should be capitalized. public static final Set<Character> CHARACTERS_EOS = new HashSet<>(Arrays.asList(new Character[]{'.', '!', '?'})); }
Include Laravel 5.5 in Laravel53Worker implementation
<?php namespace Dusterio\AwsWorker\Integrations; use Dusterio\AwsWorker\Wrappers\WorkerInterface; use Dusterio\AwsWorker\Wrappers\DefaultWorker; use Dusterio\AwsWorker\Wrappers\Laravel53Worker; /** * Class BindsWorker * @package Dusterio\AwsWorker\Integrations */ trait BindsWorker { /** * @var array */ protected $workerImplementations = [ '5\.[345].*' => Laravel53Worker::class ]; /** * @param $version * @return mixed */ protected function findWorkerClass($version) { foreach ($this->workerImplementations as $regexp => $class) { if (preg_match('/' . $regexp . '/', $version)) return $class; } return DefaultWorker::class; } /** * @return void */ protected function bindWorker() { $this->app->bind(WorkerInterface::class, $this->findWorkerClass($this->app->version())); } }
<?php namespace Dusterio\AwsWorker\Integrations; use Dusterio\AwsWorker\Wrappers\WorkerInterface; use Dusterio\AwsWorker\Wrappers\DefaultWorker; use Dusterio\AwsWorker\Wrappers\Laravel53Worker; /** * Class BindsWorker * @package Dusterio\AwsWorker\Integrations */ trait BindsWorker { /** * @var array */ protected $workerImplementations = [ '5\.[34].*' => Laravel53Worker::class ]; /** * @param $version * @return mixed */ protected function findWorkerClass($version) { foreach ($this->workerImplementations as $regexp => $class) { if (preg_match('/' . $regexp . '/', $version)) return $class; } return DefaultWorker::class; } /** * @return void */ protected function bindWorker() { $this->app->bind(WorkerInterface::class, $this->findWorkerClass($this->app->version())); } }
Add dimension for expense subtype
window.OpenBudget = {"data":{"meta":{ "hierarchy": ["Funding Source", "Department", "Expense Type", "Expense Subtype"], "page_title": "City of Philadelphia Budget", "description": "", "h1": "City of Philadelphia", "h2": "Operating Budget", "data_link": "https://github.com/CityOfPhiladelphia/open-budget-data-transformer/blob/master/data/FY2014-actual.csv", "data_title": "Download Data", "uservoice": "", "base_headline": "Funding Sources", "gross_cost_label": "Expenses", "revenue_label": "Revenues", "currency_prefix": "$", "overview_label": "Overview", "deficit_label": "Deficit", "surplus_label": "Surplus", "data_url": "data/phl/data.json", "cache_url": "data/phl/cache.json", "value": { "label": "FY 2016", "type": "accounts", "year": "2016" }, "value2": { "label": "FY 2015", "type": "accounts", "year": "2015" } }}};
window.OpenBudget = {"data":{"meta":{ "hierarchy": ["Funding Source", "Department", "Expense Type", "Subcategory"], "page_title": "City of Philadelphia Budget", "description": "", "h1": "City of Philadelphia", "h2": "Operating Budget", "data_link": "https://github.com/CityOfPhiladelphia/open-budget-data-transformer/blob/master/data/FY2014-actual.csv", "data_title": "Download Data", "uservoice": "", "base_headline": "Funding Sources", "gross_cost_label": "Expenses", "revenue_label": "Revenues", "currency_prefix": "$", "overview_label": "Overview", "deficit_label": "Deficit", "surplus_label": "Surplus", "data_url": "data/phl/data.json", "cache_url": "data/phl/cache.json", "value": { "label": "FY 2016", "type": "accounts", "year": "2016" }, "value2": { "label": "FY 2015", "type": "accounts", "year": "2015" } }}};
Fix URL to use HTTPS.
import * as types from './ActionTypes' import axios from 'axios' export function addPattern(name, pattern) { return { type: types.ADD_PATTERN, name: name, pattern: pattern } } export function selectPattern(pattern) { return { type: types.SELECT_PATTERN, name: pattern } } export function deselectPattern(pattern) { return { type: types.DESELECT_PATTERN, name: pattern } } export function changeText(text) { return function(dispatch) { dispatch(requestData(text)) } } export function requestData() { return { type: types.REQUEST_DATA } } export function receiveData(json) { return { type: types.RECEIVE_DATA, data: json } } export function receiveError(json) { return { type: types.RECEIVE_ERROR, data: json } } export function evaluateText(pattern, text) { return function(dispatch) { dispatch(requestData()) return axios.post('https://api.riveter.site/v1/process/', { pattern: pattern, textContent: text }) .then(function(data) { dispatch(receiveData(data)) }) .catch(function(err) { dispatch(receiveError(err)) }) } }
import * as types from './ActionTypes' import axios from 'axios' export function addPattern(name, pattern) { return { type: types.ADD_PATTERN, name: name, pattern: pattern } } export function selectPattern(pattern) { return { type: types.SELECT_PATTERN, name: pattern } } export function deselectPattern(pattern) { return { type: types.DESELECT_PATTERN, name: pattern } } export function changeText(text) { return function(dispatch) { dispatch(requestData(text)) } } export function requestData() { return { type: types.REQUEST_DATA } } export function receiveData(json) { return { type: types.RECEIVE_DATA, data: json } } export function receiveError(json) { return { type: types.RECEIVE_ERROR, data: json } } export function evaluateText(pattern, text) { return function(dispatch) { dispatch(requestData()) return axios.post('http://api.riveter.site/v1/process/', { pattern: pattern, textContent: text }) .then(function(data) { dispatch(receiveData(data)) }) .catch(function(err) { dispatch(receiveError(err)) }) } }
Return update flag from erase tool. Fixes a bug introduced a couple commits earlier.
class BaseTool (object): draw_locks = False def update_cursor(self, mouse): mouse.set_cursor(None) class DrawTool (BaseTool): def __init__(self, block_class): self.block_class = block_class def apply(self, pos, game, editor): old = game.grid.get(pos) if old.__class__ == self.block_class: old.cycle_states() else: game.place_block(pos, self.block_class, not editor) game.grid[pos].locked = editor return True def update_cursor(self, mouse): mouse.set_cursor(self.block_class) class EraseTool (BaseTool): def apply(self, pos, game, editor): game.erase_block(pos) return True class LockTool (BaseTool): draw_locks = True def apply(self, pos, game, editor): obj = game.grid.get(pos) if obj: obj.locked = not obj.locked class TriggerTool (BaseTool): def apply(self, pos, game, editor): if pos in game.grid: game.grid[pos].cycle_states()
class BaseTool (object): draw_locks = False def update_cursor(self, mouse): mouse.set_cursor(None) class DrawTool (BaseTool): def __init__(self, block_class): self.block_class = block_class def apply(self, pos, game, editor): old = game.grid.get(pos) if old.__class__ == self.block_class: old.cycle_states() else: game.place_block(pos, self.block_class, not editor) game.grid[pos].locked = editor return True def update_cursor(self, mouse): mouse.set_cursor(self.block_class) class EraseTool (BaseTool): def apply(self, pos, game, editor): game.erase_block(pos) class LockTool (BaseTool): draw_locks = True def apply(self, pos, game, editor): obj = game.grid.get(pos) if obj: obj.locked = not obj.locked class TriggerTool (BaseTool): def apply(self, pos, game, editor): if pos in game.grid: game.grid[pos].cycle_states()
Add some more ABILTYPEs to MyCharacter.getAbilityValue
'use strict'; /** * @constructor */ function MyCharacter(world) { CharObject.call(this, world); this.type = 'local'; this.useMoveCollision = true; this.mp = undefined; this.inventory = undefined; this.quests = undefined; }; MyCharacter.prototype = Object.create( CharObject.prototype ); MyCharacter.prototype.getAbilityValue = function(abilType) { switch(abilType) { case ABILTYPE.STR: return this.stats.str; case ABILTYPE.DEX: return this.stats.dex; case ABILTYPE.INT: return this.stats.int; case ABILTYPE.CON: return this.stats.con; case ABILTYPE.CHA: return this.stats.cha; case ABILTYPE.SEN: return this.stats.sen; case ABILTYPE.MP: return this.mp; case ABILTYPE.EXP: return this.xp; case ABILTYPE.MONEY: return this.inventory.money; case ABILTYPE.BIRTH: return this.birthStone; case ABILTYPE.UNION: return this.union; case ABILTYPE.RANK: return this.rank; case ABILTYPE.FAME: return this.fame; } return CharObject.prototype.getAbilityValue.call(this, abilType); }; MyCharacter.prototype.debugValidate = function() { debugValidateProps(this, [ ['mp', 0, 999999], ['inventory'], ['quests'] ]); CharObject.prototype.debugValidate.call(this); }; /** * @name MC * @type {MyCharacter} */ var MC = null;
'use strict'; /** * @constructor */ function MyCharacter(world) { CharObject.call(this, world); this.type = 'local'; this.useMoveCollision = true; this.mp = undefined; this.inventory = undefined; this.quests = undefined; } MyCharacter.prototype = Object.create( CharObject.prototype ); MyCharacter.prototype.getAbilityValue = function(abilType) { switch(abilType) { case ABILTYPE.STR: return this.stats.str; case ABILTYPE.DEX: return this.stats.dex; case ABILTYPE.INT: return this.stats.int; case ABILTYPE.CON: return this.stats.con; case ABILTYPE.CHA: return this.stats.cha; case ABILTYPE.SEN: return this.stats.sen; case ABILTYPE.MP: return this.mp; case ABILTYPE.MONEY: return this.inventory.money; } return CharObject.prototype.getAbilityValue.call(this, abilType); }; MyCharacter.prototype.debugValidate = function() { debugValidateProps(this, [ ['mp', 0, 999999], ['inventory'], ['quests'] ]); CharObject.prototype.debugValidate.call(this); }; /** * @name MC * @type {MyCharacter} */ var MC = null;
Add to log db connection url
import tornado.ioloop import tornado.web import logging import motor from settings import routing from tornado.options import options import os if not os.path.exists(options.log_dir): os.makedirs(options.log_dir) logging.basicConfig( format='%(asctime)s [%(name)s] %(levelname)s: %(message)s', filename='%s/%s' % (options.log_dir, options.log_file), level=logging.DEBUG ) logging.getLogger('INIT').info('Connecting to mongodb at: %s' % options.db_address) ioLoop = tornado.ioloop.IOLoop.current() mongodb = ioLoop.run_sync(motor.MotorClient(options.db_address).open) app = tornado.web.Application(routing, db=mongodb, autoreload=options.autoreload) app.listen(options.port) if __name__ == "__main__": try: logging.info("Starting HTTP server on port %d" % options.port) ioLoop.start() except KeyboardInterrupt: logging.info("Shutting down server HTTP proxy on port %d" % options.port) ioLoop.stop()
import tornado.ioloop import tornado.web import logging import motor from settings import routing from tornado.options import options import os if not os.path.exists(options.log_dir): os.makedirs(options.log_dir) logging.basicConfig( format='%(asctime)s [%(name)s] %(levelname)s: %(message)s', filename='%s/%s' % (options.log_dir, options.log_file), level=logging.DEBUG ) ioLoop = tornado.ioloop.IOLoop.current() mongodb = ioLoop.run_sync(motor.MotorClient(options.db_address).open) app = tornado.web.Application(routing, db=mongodb, autoreload=options.autoreload) app.listen(options.port) if __name__ == "__main__": try: logging.info("Starting HTTP server on port %d" % options.port) ioLoop.start() except KeyboardInterrupt: logging.info("Shutting down server HTTP proxy on port %d" % options.port) ioLoop.stop()
Fix typo on config namespaces.controller to namespace.controllers
<?php namespace App\Providers; use App, URL; use Illuminate\Routing\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * Called before routes are registered. * * Register any model bindings or pattern based filters. * * @return void */ public function before() { URL::setRootControllerNamespace( trim(config('namespaces.controllers'), '\\') ); } /** * Define the routes for the application. * * @return void */ public function map() { App::booted(function() { // Once the application has booted, we will include the default routes // file. This "namespace" helper will load the routes file within a // route group which automatically sets the controller namespace. $this->namespaced(function() { require app_path().'/Http/routes.php'; }); }); } }
<?php namespace App\Providers; use App, URL; use Illuminate\Routing\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * Called before routes are registered. * * Register any model bindings or pattern based filters. * * @return void */ public function before() { URL::setRootControllerNamespace( trim(config('namespaces.controller'), '\\') ); } /** * Define the routes for the application. * * @return void */ public function map() { App::booted(function() { // Once the application has booted, we will include the default routes // file. This "namespace" helper will load the routes file within a // route group which automatically sets the controller namespace. $this->namespaced(function() { require app_path().'/Http/routes.php'; }); }); } }
Read from a specified config file.
// Webserver package main import ( "flag" "fmt" "gopkg.in/gcfg.v1" "log" "net/http" ) var configFile = flag.String("config", "/etc/bobbi.conf", "INI file for bobbi") func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Welcome, %s!", r.URL.Path[1:]) } type config struct { Main struct { Port string } } func getConfig(filename string) config { cfg := new(config) err := gcfg.ReadFileInto(cfg, filename) if err != nil { log.Fatalf("Failed reading config: %s", err) } return *cfg } func main() { flag.Parse() cfg := getConfig(*configFile) port := cfg.Main.Port if port == "" { port = "8000" } fmt.Println("Listening on port:", port) http.HandleFunc("/", handler) http.ListenAndServe(fmt.Sprintf(":%s", port), nil) }
// Webserver package main import ( "fmt" "gopkg.in/gcfg.v1" "log" "net/http" "os" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Welcome, %s!", r.URL.Path[1:]) } type config struct { Main struct { Port string } } func getConfig() config { cfg := new(config) err := gcfg.ReadFileInto(cfg, "./config-example.conf") if err != nil { log.Fatalf("Failed to parse gcfg data: %s", err) os.Exit(1) } return *cfg } func main() { cfg := getConfig() port := cfg.Main.Port if port == "" { port = "8000" } fmt.Println(port) http.HandleFunc("/", handler) http.ListenAndServe(fmt.Sprintf(":%s", port), nil) }
Update conary migration script to deal with extended config
#!/usr/bin/python # # Copyright (c) SAS Institute Inc. # import sys import os import pwd from conary.server import schema from conary.lib import cfgtypes, tracelog from conary import dbstore from .config import UpsrvConfig class SimpleFileLog(tracelog.FileLog): def printLog(self, level, msg): self.fd.write("%s\n" % msg) try: cfg = UpsrvConfig.load() except cfgtypes.CfgEnvironmentError: print "Error reading config file" sys.exit(1) tracelog.FileLog = SimpleFileLog tracelog.initLog(filename='stderr', level=2) db = dbstore.connect(cfg.repositoryDB[1], cfg.repositoryDB[0]) schema.loadSchema(db, doMigrate=True) if cfg.repositoryDB[0] == 'sqlite': os.chown(cfg.repositoryDB[1], pwd.getpwnam('apache')[2], pwd.getpwnam('apache')[3])
#!/usr/bin/python # Copyright (c) 2006 rPath, Inc # All rights reserved import sys import os import pwd from conary.server import schema from conary.lib import cfgtypes, tracelog from conary.repository.netrepos.netserver import ServerConfig from conary import dbstore class SimpleFileLog(tracelog.FileLog): def printLog(self, level, msg): self.fd.write("%s\n" % msg) cnrPath = '/srv/conary/repository.cnr' cfg = ServerConfig() tracelog.FileLog = SimpleFileLog tracelog.initLog(filename='stderr', level=2) try: cfg.read(cnrPath) except cfgtypes.CfgEnvironmentError: print "Error reading %s" % cnrPath sys.exit(1) db = dbstore.connect(cfg.repositoryDB[1], cfg.repositoryDB[0]) schema.loadSchema(db, doMigrate=True) if cfg.repositoryDB[0] == 'sqlite': os.chown(cfg.repositoryDB[1], pwd.getpwnam('apache')[2], pwd.getpwnam('apache')[3])
Change order of migration operations.
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-10-24 23:38 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('team', '0001_initial'), ] operations = [ migrations.AddField( model_name='teammember', name='order', field=models.PositiveSmallIntegerField(default=0), ), migrations.AlterModelOptions( name='teammember', options={'ordering': ('order',)}, ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-10-24 23:38 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('team', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='teammember', options={'ordering': ('order',)}, ), migrations.AddField( model_name='teammember', name='order', field=models.PositiveSmallIntegerField(default=0), ), ]
Fix compatibility php 7 strict mode Picked from 1a289a49a8c346f19535dec55be02906797e6acd
<?php /* Copyight: Deux Huit Huit 2013 License: MIT, see the LICENCE file */ if(!defined("__IN_SYMPHONY__")) die("<h2>Error</h2><p>You cannot directly access this file</p>"); /** * * @author Deux Huit Huit * http://www.deuxhuithuit.com * */ class extension_system_log_link extends Extension { /** * Name of the extension * @var string */ const EXT_NAME = 'System Log Link'; /** * Add the System logs to the naviguation */ public function fetchNavigation() { return array( array ( 'location' => __('System'), 'name' => __('Log'), 'limit' => 'developer', 'link' => 'system/log/', 'relative' => false, 'target' => '_blank' ) ); } /* ********* INSTALL/UPDATE/UNISTALL ******* */ /** * Creates the table needed for the settings of the field */ public function install() { return true; } /** * Creates the table needed for the settings of the field */ public function update($previousVersion = false) { return true; } /** * * Drops the table needed for the settings of the field */ public function uninstall() { return true; } }
<?php /* Copyight: Deux Huit Huit 2013 License: MIT, see the LICENCE file */ if(!defined("__IN_SYMPHONY__")) die("<h2>Error</h2><p>You cannot directly access this file</p>"); /** * * @author Deux Huit Huit * http://www.deuxhuithuit.com * */ class extension_system_log_link extends Extension { /** * Name of the extension * @var string */ const EXT_NAME = 'System Log Link'; /** * Add the System logs to the naviguation */ public function fetchNavigation() { return array( array ( 'location' => __('System'), 'name' => __('Log'), 'limit' => 'developer', 'link' => 'system/log/', 'relative' => false, 'target' => '_blank' ) ); } /* ********* INSTALL/UPDATE/UNISTALL ******* */ /** * Creates the table needed for the settings of the field */ public function install() { return true; } /** * Creates the table needed for the settings of the field */ public function update($previousVersion) { return true; } /** * * Drops the table needed for the settings of the field */ public function uninstall() { return true; } }
Allow svg as email logo attachment
from email.mime.image import MIMEImage from django.contrib.staticfiles import finders from .base import EmailBase class PlatformEmailMixin: """ Attaches the static file images/logo.png so it can be used in an html email. """ def get_attachments(self): attachments = super().get_attachments() filename = ( finders.find('images/email_logo.png') or finders.find('images/email_logo.svg') ) if filename: f = open(filename, 'rb') logo = MIMEImage(f.read()) logo.add_header('Content-ID', '<{}>'.format('logo')) return attachments + [logo] return attachments class SyncEmailMixin(EmailBase): """Send Emails synchronously.""" @classmethod def send(cls, object, *args, **kwargs): """Call dispatch immediately""" return cls().dispatch(object, *args, **kwargs)
from email.mime.image import MIMEImage from django.contrib.staticfiles import finders from .base import EmailBase class PlatformEmailMixin: """ Attaches the static file images/logo.png so it can be used in an html email. """ def get_attachments(self): attachments = super().get_attachments() filename = finders.find('images/email_logo.png') if filename: f = open(filename, 'rb') logo = MIMEImage(f.read()) logo.add_header('Content-ID', '<{}>'.format('logo')) return attachments + [logo] return attachments class SyncEmailMixin(EmailBase): """Send Emails synchronously.""" @classmethod def send(cls, object, *args, **kwargs): """Call dispatch immediately""" return cls().dispatch(object, *args, **kwargs)
ADD https flags and flags improvement
var WebSocketServer = require('websocket').server; var http = require('http'); var argv = require('yargs') .alias('e', 'exec') .default('port', 8080) .alias('p', 'password') .alias('ssl', 'https') .boolean('ssl') .describe('ssl', 'Add https support') .describe('ssl-key', 'Route to SSL key') .describe('ssl-cert', 'Route to SSL certificate') .describe('port', 'Set the port to listen') .describe('e', 'Set the command you want to execute') .describe('p', 'Set a specific password to the WebSocket server') .demand(['e']) .implies('ssl', 'ssl-cert') .implies('ssl-cert', 'ssl-key') .argv; var controllers = require('./lib/connectionCtrl.js'); var utils = require('./lib/utils.js'); var PORT = argv.port; if (argv.password === undefined) console.log("\033[31m\nWARNING: It is recommended to set a password and use encrypted connections with sensible data.\n \x1b[0m") var server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(PORT, function() { utils.log('Server is listening on port ' + PORT); }); wsServer = new WebSocketServer({ httpServer: server, autoAcceptConnections: false }); wsServer.on('request', function(request) { controllers.onRequest(request, argv); });
var WebSocketServer = require('websocket').server; var http = require('http'); var argv = require('yargs') .alias('e', 'exec') .default('port', 8080) .alias('p', 'password') .describe('p', 'Set a specific password to the WebSocket server') .demand(['e']) .argv; var controllers = require('./lib/connectionCtrl.js'); var utils = require('./lib/utils.js'); var PORT = argv.port; if (argv.password === undefined) console.log("\033[31m\nWARNING: It is recommended to set a password and use encrypted connections with sensible data.\n \x1b[0m") var server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(PORT, function() { utils.log('Server is listening on port ' + PORT); }); wsServer = new WebSocketServer({ httpServer: server, autoAcceptConnections: false }); wsServer.on('request', function(request) { controllers.onRequest(request, argv); });
Use new functions for getting (next) nearest neighbors
import numpy as np from .system import System class TightBindingSystem(System): def setDefaultParams(self): self.params.setdefault('t', 1) # nearest neighbor tunneling strength self.params.setdefault('t2', 0) # next-nearest neighbor .. def tunnelingRate(self, dr): t = self.get("t") t2 = self.get("t2") # Orbital matrix m = np.array([[1, 0], [0, -1]]) # m = np.array([-t]) nn = dr.getNeighborsMask(1) nnn = dr.getNeighborsMask(2) return t * m * nn[:, :, :, None, None] + t2 * m * nnn[:, :, :, None, None]
import numpy as np from .system import System class TightBindingSystem(System): def setDefaultParams(self): self.params.setdefault('t', 1) # nearest neighbor tunneling strength self.params.setdefault('t2', 0) # next-nearest neighbor .. def tunnelingRate(self, dr): t = self.get("t") t2 = self.get("t2") # Nearest neighbors: # Only with newest numpy version: # nn = np.linalg.norm(dr, axis=3) == 1 # TODO! get the real nearest neighbor distance # nnn = np.linalg.norm(dr, axis=3) == 2 # TODO! nn = np.sqrt(np.sum(dr ** 2, axis=3)) == 1 # TODO! get the real nearest neighbor distance nnn = np.sqrt(np.sum(dr ** 2, axis=3)) == 2 # TODO # Orbital matrix m = np.array([[1, 0], [0, -1]]) # m = np.array([-t]) return t * m * nn[:, :, :, None, None] + t2 * m * nnn[:, :, :, None, None]
Change the test board size to make it run faster
#!/usr/bin/env python import unittest import pdb import gui import human_player import rules import game #import profile from ai_player import * class AIPlayerTest(unittest.TestCase): def setUp(self): # TODO player1 = AIPlayer("Blomp") player2 = human_player.HumanPlayer("Kubba") r = rules.Rules(5, "standard") self.game = game.Game(r, player1, player2) self.gui = None ''' self.s = ABState() self.s.set_state(my_game.current_state) ''' def test_find_one_move(self): p = AIPlayer("Deep thunk") pdb.set_trace() p.prompt_for_action(self.game, self.gui) ma = p.get_action(self.game, self.gui) self.assertEquals(ma, gui.MoveAction.create_from_tuple(2,2)) if __name__ == "__main__": unittest.main()
#!/usr/bin/env python import unittest import pdb import gui import human_player import rules import game #import profile from ai_player import * class AIPlayerTest(unittest.TestCase): def setUp(self): # TODO player1 = AIPlayer("Blomp") player2 = human_player.HumanPlayer("Kubba") r = rules.Rules(13, "standard") self.game = game.Game(r, player1, player2) self.gui = None ''' self.s = ABState() self.s.set_state(my_game.current_state) ''' def test_find_one_move(self): p = AIPlayer("Deep thunk") pdb.set_trace() p.prompt_for_action(self.game, self.gui) ma = p.get_action(self.game, self.gui) self.assertEquals(ma, gui.MoveAction(6,6)) if __name__ == "__main__": unittest.main()
Update search api to produce results more consistant with those found on youtube
from apiclient.discovery import build import json # Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps # tab of # https://cloud.google.com/console # Please ensure that you have enabled the YouTube Data API for your project. devKeyFile = open("search-api.key", "rb") DEVELOPER_KEY = devKeyFile.read() devKeyFile.close() YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" def youtubeSearch(query, maxResults=50): youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY) # Call the search.list method to retrieve results matching the specified # query term. search_request = youtube.search().list( part="id,snippet", q=query, type="video", maxResults=maxResults, order="relevance" ) search_response = json.dumps(search_request.execute(), separators=[',',':']) return search_response if __name__ == "__main__": print youtubeSearch("paramore", 5)
from apiclient.discovery import build import json # Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps # tab of # https://cloud.google.com/console # Please ensure that you have enabled the YouTube Data API for your project. devKeyFile = open("search-api.key", "rb") DEVELOPER_KEY = devKeyFile.read() devKeyFile.close() YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" def youtubeSearch(query, maxResults=50): youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY) # Call the search.list method to retrieve results matching the specified # query term. search_request = youtube.search().list( part="id,snippet", q=query, type="video", maxResults=maxResults, safeSearch="moderate", #could also be strict videoSyndicated="true", eventType="completed", videoDefinition="high", #could also be standard videoDuration="short", #max length of video 4mins, medium:4min-20min long order="relevance" ) search_response = json.dumps(search_request.execute(), separators=[',',':']) return search_response if __name__ == "__main__": print youtubeSearch("paramore", 5)
Remove APC loader because Pair is a pooper
<?php use Symfony\Component\ClassLoader\ApcClassLoader; use Symfony\Component\HttpFoundation\Request; $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; // Use APC for autoloading to improve performance. // Change 'sf2' to a unique prefix in order to prevent cache key conflicts // with other applications also using APC. // $apcLoader = new ApcClassLoader('timmd909APC', $loader); // $loader->unregister(); // $apcLoader->register(true); require_once __DIR__.'/../app/AppKernel.php'; //require_once __DIR__.'/../app/AppCache.php'; $kernel = new AppKernel('prod', false); $kernel->loadClassCache(); //$kernel = new AppCache($kernel); // When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter //Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
<?php use Symfony\Component\ClassLoader\ApcClassLoader; use Symfony\Component\HttpFoundation\Request; $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; // Use APC for autoloading to improve performance. // Change 'sf2' to a unique prefix in order to prevent cache key conflicts // with other applications also using APC. $apcLoader = new ApcClassLoader('timmd909APC', $loader); $loader->unregister(); $apcLoader->register(true); require_once __DIR__.'/../app/AppKernel.php'; //require_once __DIR__.'/../app/AppCache.php'; $kernel = new AppKernel('prod', false); $kernel->loadClassCache(); //$kernel = new AppCache($kernel); // When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter //Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
Fix atomic file write to force a Sync and not shadow an error.
// Copyright 2012, Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package ioutil2 provides extra functionality along similar lines to io/ioutil. package ioutil2 import ( "io" "io/ioutil" "os" "path" ) // Write file to temp and atomically move when everything else succeeds. func WriteFileAtomic(filename string, data []byte, perm os.FileMode) error { dir, name := path.Split(filename) f, err := ioutil.TempFile(dir, name) if err != nil { return err } n, err := f.Write(data) if err == nil { f.Sync() } f.Close() if err == nil { if n < len(data) { err = io.ErrShortWrite } else { err = os.Chmod(f.Name(), perm) } } if err != nil { os.Remove(f.Name()) return err } return os.Rename(f.Name(), filename) }
// Copyright 2012, Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package ioutil2 provides extra functionality along similar lines to io/ioutil. package ioutil2 import ( "io" "io/ioutil" "os" "path" ) // Write file to temp and atomically move when everything else succeeds. func WriteFileAtomic(filename string, data []byte, perm os.FileMode) error { dir, name := path.Split(filename) f, err := ioutil.TempFile(dir, name) if err != nil { return err } n, err := f.Write(data) f.Close() if err == nil && n < len(data) { err = io.ErrShortWrite } else { err = os.Chmod(f.Name(), perm) } if err != nil { os.Remove(f.Name()) return err } return os.Rename(f.Name(), filename) }
Index creation should apply across the board.
import logging try: NullHandler = logging.NullHandler except AttributeError: class NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger("statzlogger") log.addHandler(NullHandler()) class StatzHandler(logging.Handler): def __init__(self, level=logging.NOTSET): logging.Handler.__init__(self, level) self.indices = {} def emit(self, record): pass class Collection(StatzHandler): def emit(self, record): indices = getattr(record, "indices", []) indices.append(getattr(record, "index", None)) for index in indices: self.indices.setdefault(index, []).append(record) class Sum(StatzHandler): pass class Top(StatzHandler): pass
import logging try: NullHandler = logging.NullHandler except AttributeError: class NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger("statzlogger") log.addHandler(NullHandler()) class StatzHandler(logging.Handler): def emit(self, record): pass class Collection(StatzHandler): def __init__(self, level=logging.NOTSET): StatzHandler.__init__(self, level) self.indices = {} def emit(self, record): indices = getattr(record, "indices", []) indices.append(getattr(record, "index", None)) for index in indices: self.indices.setdefault(index, []).append(record) class Sum(StatzHandler): pass class Top(StatzHandler): pass
Fix typos in tempest API tests for profile_delete This patch fixes typos in tempest API tests for profile_delete. Change-Id: Ic6aa696f59621a5340d6cf67be76e830bbd30e67
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.lib import decorators from senlin.tests.tempest.api import base from senlin.tests.tempest.common import constants class TestProfileDelete(base.BaseSenlinTest): @classmethod def resource_setup(cls): super(TestProfileDelete, cls).resource_setup() # Create profile cls.profile = cls.create_profile(constants.spec_nova_server) @decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27') def test_delete_profile(self): # Verify resp of profile delete API res = self.client.delete_obj('profiles', self.profile['id']) self.assertEqual(204, res['status']) self.assertIsNone(res['body'])
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.lib import decorators from senlin.tests.tempest.api import base from senlin.tests.tempest.common import constants class TestProfileDelete(base.BaseSenlinTest): @classmethod def resource_setup(cls): super(TestProfileDelete, cls).resource_setup() # Create profile cls.profile = cls.create_profile(constants.spec_nova_server) @decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27') def test_delete_policy(self): # Verify resp of policy delete API res = self.client.delete_obj('profiles', self.profile['id']) self.assertEqual(204, res['status']) self.assertIsNone(res['body'])
Sort objectives alphabetically in single event view
import Ember from 'ember'; import layout from '../templates/components/ilios-calendar-single-event-objective-list'; const { computed, isEmpty } = Ember; export default Ember.Component.extend({ layout, objectives: [], domains: computed('objectives.@each.[title,domain]', function(){ let objectives = this.get('objectives'); if(isEmpty(objectives)){ return []; } let domainTitles = objectives.map(obj => { return obj.domain.toString(); }); domainTitles = Ember.A(domainTitles).uniq(); let domains = domainTitles.map(title => { let domain = { title, objectives: [] }; let objectives = this.get('objectives').filter(obj => { return obj.domain.toString() === title; }).map(obj => { return obj.title; }); domain.objectives = Ember.A(objectives).sortBy('title'); return domain; }); //make it an ennumerable so it can be observed return Ember.A(domains).sortBy('title'); }), });
import Ember from 'ember'; import layout from '../templates/components/ilios-calendar-single-event-objective-list'; const { computed, isEmpty } = Ember; export default Ember.Component.extend({ layout, objectives: [], domains: computed('objectives.@each.[title,domain]', function(){ let objectives = this.get('objectives'); if(isEmpty(objectives)){ return []; } let domainTitles = objectives.map(obj => { return obj.domain.toString(); }); domainTitles = Ember.A(domainTitles).uniq(); let domains = domainTitles.map(title => { let domain = { title, objectives: [] }; domain.objectives = this.get('objectives').filter(obj => { return obj.domain.toString() === title; }).map(obj => { return obj.title; }); return domain; }); //make it an ennumerable so it can be observed return Ember.A(domains); }), });
Change scope of watch manager.
import os import sys import pyinotify import analyzer class ProcessProfilerEvent(pyinotify.ProcessEvent): def process_IN_CLOSE_WRITE(self, event): if event.name.endswith(".json"): base = os.path.splitext(os.path.join(event.path, event.name))[0] analyzer.analyze_profiling_result(base) def monitor(directory): wm = pyinotify.WatchManager() notifier = pyinotify.Notifier(wm, ProcessProfilerEvent()) mask = pyinotify.IN_CLOSE_WRITE # Watched events wdd = wm.add_watch(directory, mask) while True: try: # process the queue of events as explained above notifier.process_events() if notifier.check_events(): # read notified events and enqeue them notifier.read_events() # you can do some tasks here... except KeyboardInterrupt: # destroy the inotify's instance on this interrupt (stop monitoring) notifier.stop() break if __name__ == '__main__': monitor(sys.argv[1])
import os import sys import pyinotify import analyzer wm = pyinotify.WatchManager() class ProcessProfilerEvent(pyinotify.ProcessEvent): def process_IN_CLOSE_WRITE(self, event): if event.name.endswith(".json"): base = os.path.splitext(os.path.join(event.path, event.name))[0] analyzer.analyze_profiling_result(base) def monitor(directory): notifier = pyinotify.Notifier(wm, ProcessProfilerEvent()) mask = pyinotify.IN_CLOSE_WRITE # Watched events wdd = wm.add_watch(directory, mask) while True: try: # process the queue of events as explained above notifier.process_events() if notifier.check_events(): # read notified events and enqeue them notifier.read_events() # you can do some tasks here... except KeyboardInterrupt: # destroy the inotify's instance on this interrupt (stop monitoring) notifier.stop() break if __name__ == '__main__': monitor(sys.argv[1])
Bring back `render` to module
// Configuration export {default as render} from './render'; export {default as configure} from './configure'; export {default as configureRoutes} from './configureRoutes'; // Components export {default as Card} from './components/Card/Card'; export {default as Span} from './components/Specimen/Span'; // Higher-order component for creating specimens export {default as Specimen} from './components/Specimen/Specimen'; // Specimens export {default as AudioSpecimen} from './specimens/Audio'; export {default as ButtonSpecimen} from './specimens/Button'; export {default as CodeSpecimen} from './specimens/Code'; export {default as ColorSpecimen} from './specimens/Color'; export {default as HtmlSpecimen} from './specimens/Html'; export {default as HintSpecimen} from './specimens/Hint'; export {default as ImageSpecimen} from './specimens/Image'; export {default as TypeSpecimen} from './specimens/Type'; export {default as ProjectSpecimen} from './specimens/Project/Project'; export {default as DownloadSpecimen} from './specimens/Download'; export {default as ReactSpecimen} from './specimens/ReactSpecimen/ReactSpecimen'; export {default as VideoSpecimen} from './specimens/Video';
// Configuration export {default as configure} from './configure'; export {default as configureRoutes} from './configureRoutes'; // Components export {default as Card} from './components/Card/Card'; export {default as Span} from './components/Specimen/Span'; // Higher-order component for creating specimens export {default as Specimen} from './components/Specimen/Specimen'; // Specimens export {default as AudioSpecimen} from './specimens/Audio'; export {default as ButtonSpecimen} from './specimens/Button'; export {default as CodeSpecimen} from './specimens/Code'; export {default as ColorSpecimen} from './specimens/Color'; export {default as HtmlSpecimen} from './specimens/Html'; export {default as HintSpecimen} from './specimens/Hint'; export {default as ImageSpecimen} from './specimens/Image'; export {default as TypeSpecimen} from './specimens/Type'; export {default as ProjectSpecimen} from './specimens/Project/Project'; export {default as DownloadSpecimen} from './specimens/Download'; export {default as ReactSpecimen} from './specimens/ReactSpecimen/ReactSpecimen'; export {default as VideoSpecimen} from './specimens/Video';
Use new base class for BeanInfo.
/*** * Image/J Plugins * Copyright (C) 2002-2005 Jarek Sacha * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Latest release available at http://sourceforge.net/projects/ij-plugins/ */ package net.sf.ij_plugins.filters; import net.sf.ij_plugins.util.IJPluginsSimpleBeanInfo; /** * @author Jarek Sacha * @version $Revision: 1.2 $ */ public class FluxAnisotropicDiffusionFilterBeanInfo extends IJPluginsSimpleBeanInfo { public FluxAnisotropicDiffusionFilterBeanInfo() { super(FluxAnisotropicDiffusionFilter.class); } }
/*** * Image/J Plugins * Copyright (C) 2002-2004 Jarek Sacha * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Latest release available at http://sourceforge.net/projects/ij-plugins/ */ package net.sf.ij_plugins.filters; import java.beans.SimpleBeanInfo; /** * @author Jarek Sacha * @version $Revision: 1.1 $ */ public class FluxAnisotropicDiffusionFilterBeanInfo extends SimpleBeanInfo { }
Move the YTSearch function into its own method, call that when we start the app and pass in a default search term, add a property of onSearchTermChange which throws a function which calls the videoSearch method passing in the term as an argument.
import React, { Component } from 'react'; import ReactDom from 'react-dom'; import YTSearch from 'youtube-api-search'; import SearchBar from './components/search_bar'; import VideoList from './components/video_list'; import VideoDetail from './components/video_detail'; import file from './variables.js'; // Rename the sample-variables.js to variables.js and place any variables you do // not want pushed to the repo there. const API_KEY = file.api_key; class App extends Component { constructor (props) { super(props); this.state = { videos: [], selectedVideo: null }; this.videoSearch('Dragon Ball Super'); } videoSearch(term) { YTSearch({key: API_KEY, term: term}, (videos) => { console.log(videos); this.setState({ videos: videos, selectedVideo: videos[0] }); }); } render () { return ( <div> <SearchBar onSearchTermChange={term => this.videoSearch(term)} /> <VideoDetail video={this.state.selectedVideo} /> <VideoList videos={this.state.videos} onVideoSelect={selectedVideo => this.setState({selectedVideo})} /> </div> ); } } ReactDom.render(<App />, document.querySelector('.container'));
import React, { Component } from 'react'; import ReactDom from 'react-dom'; import YTSearch from 'youtube-api-search'; import SearchBar from './components/search_bar'; import VideoList from './components/video_list'; import VideoDetail from './components/video_detail'; import file from './variables.js'; // Create a variables file modeled after the sample-variables.js file. const API_KEY = file.api_key; class App extends Component { constructor (props) { super(props); this.state = { videos: [], selectedVideo: null }; YTSearch({key: API_KEY, term: 'dragonball super'}, (videos) => { console.log(videos); this.setState({ videos: videos, selectedVideo: videos[0] }); }); } render () { return ( <div> <SearchBar /> <VideoDetail video={this.state.selectedVideo} /> <VideoList videos={this.state.videos} onVideoSelect={selectedVideo => this.setState({selectedVideo})} /> </div> ); } } ReactDom.render(<App />, document.querySelector('.container'));
Return actual json to fix webhook testing showing a potential debugbar
<?php namespace MikeVrind\Deployer\Controllers; use Illuminate\Routing\Controller; use MikeVrind\Deployer\Deployer; class DeployController extends Controller { /** * Parse the incoming webhook to the deployer * * @param Deployer $deployer * @return mixed */ public function handle( Deployer $deployer ) { if( $deployer->deploy() ) { return response()->json( [ 'status' => 200, 'message' => 'Deployment successful' ], 200 ); } else { return response()->json( [ 'status' => 503, 'message' => $deployer->getErrorMessage() ], 503 ); } } }
<?php namespace MikeVrind\Deployer\Controllers; use Illuminate\Routing\Controller; use MikeVrind\Deployer\Deployer; class DeployController extends Controller { /** * Parse the incoming webhook to the deployer * * @param Deployer $deployer * @return mixed */ public function handle( Deployer $deployer ) { if( $deployer->deploy() ) { return response( [ 'status' => 200, 'message' => 'deployment successful' ], 200 ); } else { return response( [ 'status' => 503, 'message' => $deployer->getErrorMessage() ], 503 ); } } }
Return an error when number of jobs exceeds max_jobs ghactions API call we're using limits number of jobs returned in one call. If jobs exceed this number they are grouped into "pages". Page handling code shall be added when we exceed this number.
import urllib.request import json import subprocess import time import os import sys # We're limited to this number by GH Actions API # https://docs.github.com/en/free-pro-team@latest/rest/reference/actions#list-jobs-for-a-workflow-run max_jobs=100 status_url = "https://api.github.com/repos/" \ + os.environ['GITHUB_REPOSITORY'] \ + "/actions/runs/" \ + os.environ['GITHUB_RUN_ID'] \ + "/jobs" \ + "?per_page=" + str(max_jobs) numOfJobs = int(os.environ['NUM_OF_JOBS']) if(numOfJobs > max_jobs): sys.exit("ERROR: number of jobs exceeded max_jobs: " + str(max_jobs)) while(True): time.sleep(60) countCompleted = 0 with urllib.request.urlopen(status_url) as url: data = json.loads(url.read().decode()) for j in data["jobs"]: if(j["status"] == "completed"): countCompleted += 1 print("Completed jobs:" + str(countCompleted) + ". Jobs overall: " + str(numOfJobs)) if(countCompleted >= numOfJobs): break subprocess.call(os.environ['GITHUB_WORKSPACE'] + "/.github/scripts/master-package.sh") subprocess.call(os.environ['GITHUB_WORKSPACE'] + "/.github/scripts/cleanup-anaconda.sh")
import urllib.request import json import subprocess import time import os # We're limited to this number by GH Actions API # https://docs.github.com/en/free-pro-team@latest/rest/reference/actions#list-jobs-for-a-workflow-run max_jobs=100 status_url = "https://api.github.com/repos/" \ + os.environ['GITHUB_REPOSITORY'] \ + "/actions/runs/" \ + os.environ['GITHUB_RUN_ID'] \ + "/jobs" \ + "?per_page=" + str(max_jobs) numOfJobs = int(os.environ['NUM_OF_JOBS']) while(True): time.sleep(60) countCompleted = 0 with urllib.request.urlopen(status_url) as url: data = json.loads(url.read().decode()) for j in data["jobs"]: if(j["status"] == "completed"): countCompleted += 1 print("Completed jobs:" + str(countCompleted) + ". Jobs overall: " + str(numOfJobs)) if(countCompleted >= numOfJobs): break subprocess.call(os.environ['GITHUB_WORKSPACE'] + "/.github/scripts/master-package.sh") subprocess.call(os.environ['GITHUB_WORKSPACE'] + "/.github/scripts/cleanup-anaconda.sh")
Allow dots in phone numbers
import i18n from '@/i18n' export function mandatory() { return v => !!v || i18n.t('validation.mandatory') } function regexMatch(regex, key) { return v => { if (!v) { return true } return !!String(v).match(regex) || i18n.t(key) } } export function email() { // Not really the right regex but it's sufficient return regexMatch(/^[^@]+@[^@]+$/, 'validation.email') } export function isbn() { return regexMatch(/^[0-9-]{10,}X?( ?\/ ?[0-9]+)?$/i, 'validation.isbn') } export function integer() { // Note that this rule only works partially because browsers will return an empty value for // number fields. But that's the best we can do while keeping up/down arrows. return regexMatch(/^[0-9]*$/, 'validation.integer') } export function number() { // Note that this rule only works partially because browsers will return an empty value for // number fields. But that's the best we can do while keeping up/down arrows. return regexMatch(/^([0-9]*|[0-9]+\.[0-9]+)$/, 'validation.number') } export function phone() { return regexMatch(/^\+?[0-9() /.-]+$/, 'validation.phone') } export function url() { return regexMatch(/^https?:\/\/.*$/, 'validation.url') }
import i18n from '@/i18n' export function mandatory() { return v => !!v || i18n.t('validation.mandatory') } function regexMatch(regex, key) { return v => { if (!v) { return true } return !!String(v).match(regex) || i18n.t(key) } } export function email() { // Not really the right regex but it's sufficient return regexMatch(/^[^@]+@[^@]+$/, 'validation.email') } export function isbn() { return regexMatch(/^[0-9-]{10,}X?( ?\/ ?[0-9]+)?$/i, 'validation.isbn') } export function integer() { // Note that this rule only works partially because browsers will return an empty value for // number fields. But that's the best we can do while keeping up/down arrows. return regexMatch(/^[0-9]*$/, 'validation.integer') } export function number() { // Note that this rule only works partially because browsers will return an empty value for // number fields. But that's the best we can do while keeping up/down arrows. return regexMatch(/^([0-9]*|[0-9]+\.[0-9]+)$/, 'validation.number') } export function phone() { return regexMatch(/^\+?[0-9() /-]+$/, 'validation.phone') } export function url() { return regexMatch(/^https?:\/\/.*$/, 'validation.url') }
Fix NPE on item despawn or destroy.
package me.jjm_223.pt; import me.jjm_223.pt.listeners.EggClick; import me.jjm_223.pt.listeners.EggHit; import me.jjm_223.pt.listeners.ItemDespawn; import me.jjm_223.pt.utils.DataStorage; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.io.IOException; /** * Main class for PetTransportation. */ public class PetTransportation extends JavaPlugin { private DataStorage storage; @Override public void onEnable() { storage = new DataStorage(this); PluginManager pm = getServer().getPluginManager(); pm.registerEvents(new EggHit(this), this); pm.registerEvents(new EggClick(this), this); pm.registerEvents(new ItemDespawn(this), this); } @Override public void onDisable() { try { storage.save(); } catch (IOException e) { e.printStackTrace(); } } public DataStorage getStorage() { return this.storage; } }
package me.jjm_223.pt; import me.jjm_223.pt.listeners.EggClick; import me.jjm_223.pt.listeners.EggHit; import me.jjm_223.pt.listeners.ItemDespawn; import me.jjm_223.pt.utils.DataStorage; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.io.IOException; /** * Main class for PetTransportation. */ public class PetTransportation extends JavaPlugin { private DataStorage storage; @Override public void onEnable() { //Register relevant events. PluginManager pm = getServer().getPluginManager(); pm.registerEvents(new EggHit(this), this); pm.registerEvents(new EggClick(this), this); pm.registerEvents(new ItemDespawn(this), this); storage = new DataStorage(this); } @Override public void onDisable() { try { storage.save(); } catch (IOException e) { e.printStackTrace(); } } public DataStorage getStorage() { return this.storage; } }
Create migration directory if not exist
<?php namespace Dami\Cli\Command; use Symfony\Component\Console\Command\Command, Symfony\Component\Console\Input\InputOption, Symfony\Component\Console\Input\InputInterface, Symfony\Component\Console\Output\OutputInterface; class AbstractCommand extends Command { protected function configure() { $this ->addOption('env', null, InputOption::VALUE_REQUIRED, 'Set environment'); } protected function execute(InputInterface $input, OutputInterface $output) { $environment = $input->getOption('env'); if (null !== $environment) { $config = $this->getContainer()->get('connection_config'); $config->changeEnvironment($environment); } $migrationDirectory = $this->getContainer()->getparameter('dami.migrations_directory'); if (!file_exists($migrationDirectory)) { mkdir($migrationDirectory); } } }
<?php namespace Dami\Cli\Command; use Symfony\Component\Console\Command\Command, Symfony\Component\Console\Input\InputOption, Symfony\Component\Console\Input\InputInterface, Symfony\Component\Console\Output\OutputInterface; class AbstractCommand extends Command { protected function configure() { $this ->addOption('env', null, InputOption::VALUE_REQUIRED, 'Set environment'); } protected function execute(InputInterface $input, OutputInterface $output) { $environment = $input->getOption('env'); if (null !== $environment) { $config = $this->getContainer()->get('connection_config'); $config->changeEnvironment($environment); } } }
Remove job when done and match servicelayer api
import logging from followthemoney import model from servicelayer.worker import Worker from servicelayer.jobs import JobStage as Stage from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, stage, context, entities): next_stage = context.get('next_stage') if next_stage is None: return next_queue = Stage(stage.conn, next_stage, stage.job.id, stage.dataset, priority=stage.priority) log.info("Sending %s entities to: %s", len(entities), next_stage) for entity_id in entities: next_queue.queue_task({'entity_id': entity_id}, context) def handle(self, task): manager = Manager(task.stage, task.context) entity = model.get_proxy(task.payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(task.stage, task.context, manager.emitted)
import logging from followthemoney import model from servicelayer.worker import Worker from servicelayer.jobs import JobStage as Stage from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, stage, context, entities): next_stage = context.get('next_stage') if next_stage is None: return next_queue = Stage(stage.conn, next_stage, stage.job.id, stage.dataset, priority=stage.priority) log.info("Sending %s entities to: %s", len(entities), next_stage) for entity_id in entities: next_queue.queue_task({'entity_id': entity_id}, context) def handle(self, stage, payload, context): manager = Manager(stage, context) entity = model.get_proxy(payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(stage, context, manager.emitted)
Revert using array_merge due to numerical array issues
<?php /** * Starlit Db. * * @copyright Copyright (c) 2019 Starweb AB * @license BSD 3-Clause */ namespace Starlit\Db; use PDO; class PdoFactory implements PdoFactoryInterface { public function createPdo(string $dsn, string $username = null, string $password = null, array $options = []): PDO { $defaultPdoOptions = [ PDO::ATTR_TIMEOUT => 5, // We want emulation by default (faster for single queries). Disable if you want to // use proper native prepared statements PDO::ATTR_EMULATE_PREPARES => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ]; $pdoOptions = $defaultPdoOptions + (isset($options['pdo']) ? $options['pdo'] : []); return new PDO($dsn, $username, $password, $pdoOptions); } }
<?php /** * Starlit Db. * * @copyright Copyright (c) 2019 Starweb AB * @license BSD 3-Clause */ namespace Starlit\Db; use PDO; class PdoFactory implements PdoFactoryInterface { public function createPdo(string $dsn, string $username = null, string $password = null, array $options = []): PDO { $defaultPdoOptions = [ PDO::ATTR_TIMEOUT => 5, // We want emulation by default (faster for single queries). Disable if you want to // use proper native prepared statements PDO::ATTR_EMULATE_PREPARES => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ]; $pdoOptions = \array_merge($defaultPdoOptions, (isset($options['pdo']) ? $options['pdo'] : [])); return new PDO($dsn, $username, $password, $pdoOptions); } }
Fix: Modify Cached Item in Memory, MCC returns now cloned object for in place manipulation
<?php namespace SPHERE\System\Cache\Handler; /** * Class MemoryContainer * @package SPHERE\System\Cache\Handler */ class MemoryContainer { /** @var int $TimeStamp */ private $TimeStamp = 0; /** @var int $TimeOut */ private $TimeOut = 0; /** @var mixed $Value */ private $Value = null; /** * MemoryContainer constructor. * @param $Value * @param $Timeout */ public function __construct($Value, $Timeout = 0) { $this->TimeStamp = time(); $this->Value = $Value; $this->TimeOut = $Timeout; } /** * @return bool */ public function isValid() { if ($this->TimeOut === 0 || ($this->TimeStamp + $this->TimeOut) > time()) { return true; } return false; } /** * @return mixed */ public function getValue() { if (is_object($this->Value)) { return clone $this->Value; } else { return $this->Value; } } }
<?php namespace SPHERE\System\Cache\Handler; /** * Class MemoryContainer * @package SPHERE\System\Cache\Handler */ class MemoryContainer { /** @var int $TimeStamp */ private $TimeStamp = 0; /** @var int $TimeOut */ private $TimeOut = 0; /** @var mixed $Value */ private $Value = null; /** * MemoryContainer constructor. * @param $Value * @param $Timeout */ public function __construct($Value, $Timeout = 0) { $this->TimeStamp = time(); $this->Value = $Value; $this->TimeOut = $Timeout; } /** * @return bool */ public function isValid() { if ($this->TimeOut === 0 || ($this->TimeStamp + $this->TimeOut) > time()) { return true; } return false; } /** * @return mixed */ public function getValue() { return $this->Value; } }
Use a new updating strategy.
import { Component } from 'substance' export default class SelectInput extends Component { render($$) { const label = this.props.label const value = this.props.value const options = this.props.availableOptions const el = $$('div').addClass('sc-select-input') const selectEl = $$('select').addClass('se-select') .ref('input') .on('change', this._onChange) const defaultOpt = $$('option').attr({value: false}) .append(this.getLabel('select-default-value')) if(!value) { defaultOpt.attr({selected: 'selected'}) } selectEl.append(defaultOpt) options.forEach(opt => { const optEl = $$('option').attr({value: opt.id}).append(opt.text) if(opt.id === value) optEl.attr({selected: 'selected'}) selectEl.append(optEl) }) el.append( $$('div').addClass('se-label').append(label), selectEl ) return el } _onChange() { const name = this.props.name const value = this._getValue() this.send('set-value', name, value) } _getValue() { const input = this.refs.input return input.value } }
import { Component } from 'substance' export default class SelectInput extends Component { render($$) { const label = this.props.label const value = this.props.value const options = this.props.availableOptions const el = $$('div').addClass('sc-select-input') const selectEl = $$('select').addClass('se-select') .ref('input') .on('change', this._onChange) const defaultOpt = $$('option').attr({value: false}) .append(this.getLabel('select-default-value')) if(!value) { defaultOpt.attr({selected: 'selected'}) } selectEl.append(defaultOpt) options.forEach(opt => { const optEl = $$('option').attr({value: opt.id}).append(opt.text) if(opt.id === value) optEl.attr({selected: 'selected'}) selectEl.append(optEl) }) el.append( $$('div').addClass('se-label').append(label), selectEl ) return el } _onChange() { const id = this.props.id if(id) { const value = this._getValue() this.send('input:change', id, value) } } _getValue() { const input = this.refs.input return input.value } }
Add more prefer event listeners to observe compose window creating/deleting
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ (function (aGlobal) { var tbBug766495 = { init: function() { window.removeEventListener('load', this, false); window.addEventListener('unload', this, false); document.documentElement.addEventListener('compose-window-init', this, false); document.documentElement.addEventListener('compose-window-close', this, false); }, destroy: function() { window.removeEventListener('unload', this, false); document.documentElement.removeEventListener('compose-window-init', this, false); document.documentElement.removeEventListener('compose-window-close', this, false); }, handleEvent: function(aEvent) { switch (aEvent.type) { case 'load': this.init(); return; case 'unload': this.destroy(); return; } } }; window.addEventListener('load', tbBug766495, false); aGlobal.tbBug766495 = tbBug766495; })(this);
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ (function (aGlobal) { var tbBug766495 = { init: function() { window.removeEventListener('load', this, false); window.addEventListener('unload', this, false); }, destroy: function() { window.removeEventListener('unload', this, false); }, handleEvent: function(aEvent) { switch (aEvent.type) { case 'load': this.init(); return; case 'unload': this.destroy(); return; } } }; window.addEventListener('load', tbBug766495, false); aGlobal.tbBug766495 = tbBug766495; })(this);
Refactor Petri Dish state machine
package org.nusco.narjillos.views.utilities; public class PetriDishState { private volatile Light light = Light.ON; private volatile Speed speed = Speed.REALTIME; public Light getLight() { return light; } public Speed getSpeed() { return speed; } public void toggleLight() { switch (light) { case INFRARED: this.light = Light.ON; break; case ON: this.light = Light.OFF; this.speed = Speed.HIGH; break; case OFF: this.light = Light.ON; this.speed = Speed.REALTIME; break; } } public void toggleInfrared() { switch (light) { case INFRARED: this.light = Light.ON; break; case ON: this.light = Light.INFRARED; break; case OFF: this.light = Light.INFRARED; this.speed = Speed.REALTIME; break; } } public void toggleSpeed() { switch (speed) { case REALTIME: this.speed = Speed.HIGH; break; case HIGH: this.speed = Speed.REALTIME; break; } } }
package org.nusco.narjillos.views.utilities; public class PetriDishState { private volatile Light light = Light.ON; private volatile Speed speed = Speed.REALTIME; public Light getLight() { return light; } public Speed getSpeed() { return speed; } public void toggleLight() { if (light == Light.INFRARED) this.light = Light.ON; else if (light == Light.ON) { this.light = Light.OFF; this.speed = Speed.HIGH; } else { this.light = Light.ON; this.speed = Speed.REALTIME; } } public void toggleInfrared() { if (light == Light.OFF) { this.light = Light.INFRARED; this.speed = Speed.REALTIME; } else if (light == Light.INFRARED) this.light = Light.ON; else this.light = Light.INFRARED; } public void toggleSpeed() { if (speed == Speed.REALTIME) this.speed = Speed.HIGH; else this.speed = Speed.REALTIME; } }
Use module.exports instead of exports
'use strict'; /** * winston transport support */ var sender = require('./sender'); var util = require('util'); var winston = require('winston'); var Transport = winston.Transport; var DEFAULT_TAG = 'winston'; function fluentTransport(tag, options) { if (arguments.length === 0) { tag = DEFAULT_TAG; } else { if (typeof(tag) === 'object') { options = tag; tag = DEFAULT_TAG; } } options = options || {}; this.sender = new sender.FluentSender(tag, options); Transport.call(this, options); } util.inherits(fluentTransport, Transport); fluentTransport.prototype.log = function(level, message, meta, callback) { var sender = this.sender; var data = { level: level, message: message, meta: meta }; sender.emit(data, (error) => { if (error) { this.emit('error', error); callback(error, false); } else { this.emit('logged'); callback(null, true); } }); }; fluentTransport.prototype.name = 'fluent'; module.exports.Transport = fluentTransport;
'use strict'; /** * winston transport support */ var sender = require('./sender'); var util = require('util'); var winston = require('winston'); var Transport = winston.Transport; var DEFAULT_TAG = 'winston'; function fluentTransport(tag, options) { if (arguments.length === 0) { tag = DEFAULT_TAG; } else { if (typeof(tag) === 'object') { options = tag; tag = DEFAULT_TAG; } } options = options || {}; this.sender = new sender.FluentSender(tag, options); Transport.call(this, options); } util.inherits(fluentTransport, Transport); fluentTransport.prototype.log = function(level, message, meta, callback) { var sender = this.sender; var data = { level: level, message: message, meta: meta }; sender.emit(data, (error) => { if (error) { this.emit('error', error); callback(error, false); } else { this.emit('logged'); callback(null, true); } }); }; fluentTransport.prototype.name = 'fluent'; exports.Transport = fluentTransport;
Use PHP 8 constructor property promotion
<?php declare(strict_types = 1); /** * /src/Validator/Constraints/LocaleValidator.php * * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ namespace App\Validator\Constraints; use App\Service\Localization; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use function in_array; /** * Class LocaleValidator * * @package App\Validator\Constraints * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ class LocaleValidator extends ConstraintValidator { public function __construct( private Localization $localization, ) { } /** * {@inheritdoc} */ public function validate($value, Constraint $constraint): void { if (in_array($value, $this->localization->getLocales(), true) !== true) { $this->context ->buildViolation(Locale::MESSAGE) ->setParameter('{{ locale }}', (string)$value) ->setCode(Locale::INVALID_LOCALE) ->addViolation(); } } }
<?php declare(strict_types = 1); /** * /src/Validator/Constraints/LocaleValidator.php * * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ namespace App\Validator\Constraints; use App\Service\Localization; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use function in_array; /** * Class LocaleValidator * * @package App\Validator\Constraints * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ class LocaleValidator extends ConstraintValidator { private Localization $localization; public function __construct(Localization $localization) { $this->localization = $localization; } /** * {@inheritdoc} */ public function validate($value, Constraint $constraint): void { if (in_array($value, $this->localization->getLocales(), true) !== true) { $this->context ->buildViolation(Locale::MESSAGE) ->setParameter('{{ locale }}', (string)$value) ->setCode(Locale::INVALID_LOCALE) ->addViolation(); } } }
Use slugify to filenameify the strings passed in. This should probably live in a test_utils.utils. Too many utils!
from django.http import HttpResponse import logging from test_utils.testmaker.processors.base import slugify from test_utils.testmaker import Testmaker def set_logging(request, filename=None): if not filename: filename = request.REQUEST['filename'] filename = slugify(filename) log_file = '/tmp/testmaker/tests/%s_tests_custom.py' % filename serialize_file = '/tmp/testmaker/tests/%s_serial_custm.py' % filename tm = Testmaker() tm.setup_logging(test_file=log_file, serialize_file=serialize_file) tm.prepare_test_file() return HttpResponse('Setup logging %s' % tm.test_file) def show_log(request): file = Testmaker.logfile() contents = open(file) return HttpResponse(contents.read(), content_type='text/plain') HttpResponse()
from django.http import HttpResponse import logging from test_utils.testmaker import Testmaker def set_logging(request, filename=None): if not filename: filename = request.REQUEST['filename'] log_file = '/tmp/testmaker/tests/%s_tests_custom.py' % filename serialize_file = '/tmp/testmaker/tests/%s_serial_custm.py' % filename tm = Testmaker() tm.setup_logging(test_file=log_file, serialize_file=serialize_file) tm.prepare_test_file() return HttpResponse('Setup logging %s' % tm.test_file) def show_log(request): file = Testmaker.logfile() contents = open(file) return HttpResponse(contents.read(), content_type='text/plain') HttpResponse()
Implement getTitle and getDescription for search
Meteor.startup(function () { PostsSearchController = PostsListController.extend({ view: 'search', getTitle: function() { return i18n.t("Search") + ' - ' + getSetting('title', "Telescope"); }, getDescription: function() { return getSetting('description'); }, onBeforeAction: function() { var query = this.params.query; if ('q' in query) { Session.set('searchQuery', query.q); if (query.q) { Meteor.call('logSearch', query.q) } } this.next(); } }); Router.onBeforeAction(Router._filters.isAdmin, {only: ['logs']}); // Search Router.route('/search/:limit?', { name: 'search', controller: PostsSearchController }); // Search Logs Router.route('/logs/:limit?', { name: 'searchLogs', waitOn: function () { var limit = this.params.limit || 100; if(Meteor.isClient) { Session.set('logsLimit', limit); } return Meteor.subscribe('searches', limit); }, data: function () { return Searches.find({}, {sort: {timestamp: -1}}); }, fastRender: true }); });
Meteor.startup(function () { PostsSearchController = PostsListController.extend({ view: 'search', onBeforeAction: function() { var query = this.params.query; if ('q' in query) { Session.set('searchQuery', query.q); if (query.q) { Meteor.call('logSearch', query.q) } } this.next(); } }); Router.onBeforeAction(Router._filters.isAdmin, {only: ['logs']}); // Search Router.route('/search/:limit?', { name: 'search', controller: PostsSearchController }); // Search Logs Router.route('/logs/:limit?', { name: 'searchLogs', waitOn: function () { var limit = this.params.limit || 100; if(Meteor.isClient) { Session.set('logsLimit', limit); } return Meteor.subscribe('searches', limit); }, data: function () { return Searches.find({}, {sort: {timestamp: -1}}); }, fastRender: true }); });
Create function that works for someone else
(function(ext) { // Cleanup function when the extension is unloaded ext._shutdown = function() {}; // Status reporting code // Use this to report missing hardware, plugin or unsupported browser ext._getStatus = function() { return {status: 2, msg: 'Ready'}; }; ext.my_first_block = function(string) { alert(string); }; ext.power = function(base, exponent) { return Math.pow(base,exponent); }; // Block and block menu descriptions var descriptor = { blocks: [ ['', 'My First Block', 'my_first_block'], ['r', '%n ^ %n', 'power', 2, 3], ] }; // Register the extension ScratchExtensions.register('Kinect2Scratch', descriptor, ext); })({});
(function(ext) { // Cleanup function when the extension is unloaded ext._shutdown = function() {}; // Status reporting code // Use this to report missing hardware, plugin or unsupported browser ext._getStatus = function() { return {status: 2, msg: 'Ready'}; }; ext.my_first_block = function() { nchgm(); }; ext.power = function(base, exponent) { return Math.pow(base,exponent); }; // Block and block menu descriptions var descriptor = { blocks: [ ['', 'My First Block', 'my_first_block'], ['r', '%n ^ %n', 'power', 2, 3], ] }; // Register the extension ScratchExtensions.register('Kinect2Scratch', descriptor, ext); })({});
Add loadOptions and wrap submit logic.
function submitHandler() { var $submitButton = $('#submitButton'); $submitButton.on('click', function() { console.log('Submit'); var return_to = getQueryParam('return_to', 'pebblejs://close#'); document.location = return_to + encodeURIComponent(JSON.stringify(getAndStoreConfigData())); }); } function loadOptions() { var $backgroundColorPicker = $('#backgroundColorPicker'); var $timeFormatCheckbox = $('#timeFormatCheckbox'); if (localStorage.backgroundColor) { $backgroundColorPicker[0].value = localStorage.backgroundColor; $timeFormatCheckbox[0].checked = localStorage.twentyFourHourFormat === 'true'; } } function getAndStoreConfigData() { var $backgroundColorPicker = $('#backgroundColorPicker'); var $timeFormatCheckbox = $('#timeFormatCheckbox'); var options = { backgroundColor: $backgroundColorPicker.val(), twentyFourHourFormat: $timeFormatCheckbox[0].checked }; localStorage.backgroundColor = options.backgroundColor; localStorage.twentyFourHourFormat = options.twentyFourHourFormat; console.log('Got options: ' + JSON.stringify(options)); return options; } function getQueryParam(variable, defaultValue) { var query = location.search.substring(1); var vars = query.split('&'); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split('='); if (pair[0] === variable) { return decodeURIComponent(pair[1]); } } return defaultValue || false; }
(function() { loadOptions(); submitHandler(); })(); function submitHandler() { var $submitButton = $('#submitButton'); $submitButton.on('click', function() { console.log('Submit'); var return_to = getQueryParam('return_to', 'pebblejs://close#'); document.location = return_to + encodeURIComponent(JSON.stringify(getAndStoreConfigData())); }); } function loadOptions() { var $backgroundColorPicker = $('#backgroundColorPicker'); var $timeFormatCheckbox = $('#timeFormatCheckbox'); if (localStorage.backgroundColor) { $backgroundColorPicker[0].value = localStorage.backgroundColor; $timeFormatCheckbox[0].checked = localStorage.twentyFourHourFormat === 'true'; } } function getAndStoreConfigData() { var $backgroundColorPicker = $('#backgroundColorPicker'); var $timeFormatCheckbox = $('#timeFormatCheckbox'); var options = { backgroundColor: $backgroundColorPicker.val(), twentyFourHourFormat: $timeFormatCheckbox[0].checked }; localStorage.backgroundColor = options.backgroundColor; localStorage.twentyFourHourFormat = options.twentyFourHourFormat; console.log('Got options: ' + JSON.stringify(options)); return options; } function getQueryParam(variable, defaultValue) { var query = location.search.substring(1); var vars = query.split('&'); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split('='); if (pair[0] === variable) { return decodeURIComponent(pair[1]); } } return defaultValue || false; }
Remove last uses of `popup`
/* * Word Count content script */ /* global chrome:false, $:false, pluralize:false, PeripheryLabel:false, SelectionListener:false */ /* * Instantiate label and and listeners */ var COUNTED_NOUN = 'word'; var label = new PeripheryLabel(COUNTED_NOUN); var selectionListener = new SelectionListener(window); // Listen for selection changes and show/hide the label based on the number of words selected $(window).on(SelectionListener.SELECTION_CHANGE_EVENT, function (event) { var count = event.selection ? event.selection.wordCount : 0; if (!count) { label.hide(); } else { var message = count + ' ' + pluralize(COUNTED_NOUN, count); label.show(message); } }); // Listen for messages from other parts of the extension to start/stop selection listening chrome.runtime.onMessage.addListener(function (message) { if (message.active) { selectionListener.start(); } else { selectionListener.stop(); } }); // On ESC key down, disable the extension $(document).on('keydown', function (event) { if (event.which === 27) { // ESC key chrome.runtime.sendMessage({ active: false }); } });
/* * Word Count content script */ /* global chrome:false, $:false, pluralize:false, PeripheryLabel:false, SelectionListener:false */ /* * Instantiate popup and and listeners */ var COUNTED_NOUN = 'word'; var popup = new PeripheryLabel(COUNTED_NOUN); var selectionListener = new SelectionListener(window); // Listen for selection changes and show/hide the popup based on the number of words selected $(window).on(SelectionListener.SELECTION_CHANGE_EVENT, function (event) { var count = event.selection ? event.selection.wordCount : 0; if (!count) { popup.hide(); } else { var message = count + ' ' + pluralize(COUNTED_NOUN, count); popup.show(message); } }); // Listen for messages from other parts of the extension to start/stop selection listening chrome.runtime.onMessage.addListener(function (message) { if (message.active) { selectionListener.start(); } else { selectionListener.stop(); } }); // On ESC key down, disable the extension $(document).on('keydown', function (event) { if (event.which === 27) { // ESC key chrome.runtime.sendMessage({ active: false }); } });
Improve error logging in file IO
import codecs, os, time def readFile(filePath): try: with open(filePath, "r") as f: return f.read() except Exception as e: today = time.strftime("[%H:%M:%S]") print "{} *** ERROR: An exception occurred while reading file \"{}\" ({})".format(today, filePath, e) return None def writeFile(filePath, line, append=False): try: action = "a+" if append else "w" with codecs.open(filePath, action, "utf-8") as f: f.write(line) return True except Exception as e: today = time.strftime("[%H:%M:%S]") print "{} *** ERROR: An exception occurred while writing file \"{}\" ({})".format(today, filePath, e) return False def createDirs(path): if not os.path.exists(path): os.makedirs(path)
import codecs, os def readFile(filePath): try: with open(filePath, "r") as f: return f.read() except Exception as e: print "*** ERROR: An exception occurred while reading file \"{}\" ({})".format(filePath, e) return None def writeFile(filePath, line, append=False): try: action = "a+" if append else "w" with codecs.open(filePath, action, "utf-8") as f: f.write(line) return True except Exception as e: print "*** ERROR: An exception occurred while writing file \"{}\" ({})".format(filePath, e) def createDirs(path): if not os.path.exists(path): os.makedirs(path)
Extend funcname_scope so that it accepts funcnames
import functools import numpy import tensorflow as tf def static_shape(tensor): return tf.convert_to_tensor(tensor).get_shape().as_list() def static_rank(tensor): return len(static_shape(tf.convert_to_tensor(tensor))) def funcname_scope(func_or_name): if isinstance(func_or_name, str): def wrapper(func): func.__name__ = func_or_name return funcname_scope(func) return wrapper func = func_or_name @functools.wraps(func) def wrapper(*args, **kwargs): with tf.variable_scope(func.__name__): return func(*args, **kwargs) return wrapper def on_device(device_name): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): with tf.device(device_name): return func(*args, **kwargs) return wrapper return decorator def dimension_indices(tensor, start=0): return list(range(static_rank(tensor)))[start:] @funcname_scope def dtype_min(dtype): return tf.constant(_numpy_min(dtype.as_numpy_dtype)) def _numpy_min(dtype): return numpy.finfo(dtype).min @funcname_scope def dtype_epsilon(dtype): return tf.constant(_numpy_epsilon(dtype.as_numpy_dtype)) def _numpy_epsilon(dtype): return numpy.finfo(dtype).eps def flatten(x): return tf.reshape(x, [-1])
import functools import numpy import tensorflow as tf def static_shape(tensor): return tf.convert_to_tensor(tensor).get_shape().as_list() def static_rank(tensor): return len(static_shape(tf.convert_to_tensor(tensor))) def funcname_scope(func): @functools.wraps(func) def wrapper(*args, **kwargs): with tf.variable_scope(func.__name__): return func(*args, **kwargs) return wrapper def on_device(device_name): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): with tf.device(device_name): return func(*args, **kwargs) return wrapper return decorator def dimension_indices(tensor, start=0): return list(range(static_rank(tensor)))[start:] @funcname_scope def dtype_min(dtype): return tf.constant(_numpy_min(dtype.as_numpy_dtype)) def _numpy_min(dtype): return numpy.finfo(dtype).min @funcname_scope def dtype_epsilon(dtype): return tf.constant(_numpy_epsilon(dtype.as_numpy_dtype)) def _numpy_epsilon(dtype): return numpy.finfo(dtype).eps def flatten(x): return tf.reshape(x, [-1])
Change executed command to echo
package org.chodavarapu.datamill.cucumber; import com.google.common.io.Files; import org.junit.Test; import java.io.File; import java.nio.charset.Charset; import java.util.Arrays; import static org.junit.Assert.assertFalse; /** * @author Ravi Chodavarapu (rchodava@gmail.com) */ public class CommandLineStepsTest { @Test public void executeAndVerifyFiles() throws Exception { PropertyStore store = new PropertyStore(); store.put("fileName", "test.txt"); PlaceholderResolver resolver = new PlaceholderResolver(store); CommandLineSteps steps = new CommandLineSteps(store, resolver); steps.executeCommand("echo \"Hello\""); File temporaryDirectory = (File) store.get(CommandLineSteps.TEMPORARY_DIRECTORY); Files.write("Hello", new File(temporaryDirectory, "test.txt"), Charset.defaultCharset()); steps.verifyTemporaryDirectoryHasFiles(Arrays.asList("test.txt")); steps.verifyTemporaryDirectoryHasFiles(Arrays.asList("{fileName}")); steps.cleanUp(); assertFalse(new File(temporaryDirectory, "test.txt").exists()); assertFalse(temporaryDirectory.exists()); } }
package org.chodavarapu.datamill.cucumber; import com.google.common.io.Files; import org.junit.Test; import java.io.File; import java.nio.charset.Charset; import java.util.Arrays; import static org.junit.Assert.assertFalse; /** * @author Ravi Chodavarapu (rchodava@gmail.com) */ public class CommandLineStepsTest { @Test public void executeAndVerifyFiles() throws Exception { PropertyStore store = new PropertyStore(); PlaceholderResolver resolver = new PlaceholderResolver(store); CommandLineSteps steps = new CommandLineSteps(store, resolver); steps.executeCommand("ping localhost"); File temporaryDirectory = (File) store.get(CommandLineSteps.TEMPORARY_DIRECTORY); Files.write("Hello", new File(temporaryDirectory, "test.txt"), Charset.defaultCharset()); steps.verifyTemporaryDirectoryHasFiles(Arrays.asList("test.txt")); steps.cleanUp(); assertFalse(new File(temporaryDirectory, "test.txt").exists()); assertFalse(temporaryDirectory.exists()); } }
Comment out sphinx test. maven is ignoring eanbled=false
package org.sphinx; import org.sphinx.api.ISphinxClient; import org.sphinx.api.SphinxResult; import org.sphinx.pool.PooledSphinxDataSource; import org.testng.annotations.Test; import static org.testng.Assert.*; /** * SphinxQueryTest * * @author Brian Cowdery * @since 29-05-2015 */ @Test(enabled = false, description = "Live integration test, not part of automated test suite.") public class SphinxQueryTest { /* @Test public void testSphinxQuery() throws Exception { PooledSphinxDataSource dataSource = new PooledSphinxDataSource(); dataSource.setHost("190.10.14.168"); dataSource.setPort(9312); dataSource.setTestOnBorrow(true); dataSource.setTestOnReturn(true); dataSource.setMinIdle(0); dataSource.setMaxIdle(8); dataSource.setMaxTotal(8); ISphinxClient client = dataSource.getSphinxClient(); assertNotNull(client); SphinxResult result = client.Query("SELECT name, postdate FROM releases WHERE MATCH('Futurama')"); assertNotNull(result); } */ }
package org.sphinx; import org.sphinx.api.ISphinxClient; import org.sphinx.api.SphinxResult; import org.sphinx.pool.PooledSphinxDataSource; import org.testng.annotations.Test; import static org.testng.Assert.*; /** * SphinxQueryTest * * @author Brian Cowdery * @since 29-05-2015 */ @Test(enabled = false, description = "Live integration test, not part of automated test suite.") public class SphinxQueryTest { @Test public void testSphinxQuery() throws Exception { PooledSphinxDataSource dataSource = new PooledSphinxDataSource(); dataSource.setHost("190.10.14.168"); dataSource.setPort(9312); dataSource.setTestOnBorrow(true); dataSource.setTestOnReturn(true); dataSource.setMinIdle(0); dataSource.setMaxIdle(8); dataSource.setMaxTotal(8); ISphinxClient client = dataSource.getSphinxClient(); assertNotNull(client); SphinxResult result = client.Query("SELECT name, postdate FROM releases WHERE MATCH('Futurama')"); assertNotNull(result); } }
Handler: Fix bug of using DefaultMarkovMap
package heff import ( "io" "log" "net/http" "sync" ) // DefaultHoneypot is an http.HandlerFunc that serves random HTML from the // DefaultMarkovMap, 100KB at a time. var DefaultHoneypot = NewHoneypot(DefaultMarkovMap, 100*1<<10) // NewHoneypot creates an http.HandlerFunc from a MarkovMap func NewHoneypot(mm MarkovMap, buffsize int) http.HandlerFunc { var pool sync.Pool getBuffer := func() []byte { x := pool.Get() if buf, ok := x.([]byte); ok { return buf } return make([]byte, buffsize) } putBuffer := func(buf []byte) { pool.Put(buf) } return func(w http.ResponseWriter, r *http.Request) { log.Printf("Started writing: %v", r.URL) buf := getBuffer() defer putBuffer(buf) io.WriteString(w, "<HTML>\n<BODY>\n") n, err := io.CopyBuffer(w, mm, buf) log.Printf("Wrote: %d (%v)", n, err) } }
package heff import ( "io" "log" "net/http" "sync" ) // DefaultHoneypot is an http.HandlerFunc that serves random HTML from the // DefaultMarkovMap, 100KB at a time. var DefaultHoneypot = NewHoneypot(DefaultMarkovMap, 100*1<<10) // NewHoneypot creates an http.HandlerFunc from a MarkovMap func NewHoneypot(mm MarkovMap, buffsize int) http.HandlerFunc { var pool sync.Pool getBuffer := func() []byte { x := pool.Get() if buf, ok := x.([]byte); ok { return buf } return make([]byte, buffsize) } putBuffer := func(buf []byte) { pool.Put(buf) } return func(w http.ResponseWriter, r *http.Request) { log.Printf("Started writing: %v", r.URL) buf := getBuffer() defer putBuffer(buf) io.WriteString(w, "<HTML>\n<BODY>\n") n, err := io.CopyBuffer(w, DefaultMarkovMap, buf) log.Printf("Wrote: %d (%v)", n, err) } }
Put the endpoint at /launch_taskflow/launch Put it here instead of under "queues" Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>
from .configuration import Configuration from girder.api.rest import Resource from girder.utility import setting_utilities from .constants import Features, Branding, Deployment from .launch_taskflow import launch_taskflow from .user import get_orcid, set_orcid, get_twitter, set_twitter from girder.plugin import GirderPlugin @setting_utilities.validator({ Features.NOTEBOOKS, Deployment.SITE, Branding.PRIVACY, Branding.LICENSE, Branding.HEADER_LOGO_ID, Branding.FOOTER_LOGO_ID, Branding.FOOTER_LOGO_URL, Branding.FAVICON_ID }) def validateSettings(event): pass class AppPlugin(GirderPlugin): DISPLAY_NAME = 'OpenChemistry App' def load(self, info): info['apiRoot'].configuration = Configuration() # Twitter and orcid stuff info['apiRoot'].user.route('GET', (':id', 'orcid'), get_orcid) info['apiRoot'].user.route('POST', (':id', 'orcid'), set_orcid) info['apiRoot'].user.route('GET', (':id', 'twitter'), get_twitter) info['apiRoot'].user.route('POST', (':id', 'twitter'), set_twitter) # Launch a taskflow with a single endpoint info['apiRoot'].launch_taskflow = Resource() info['apiRoot'].launch_taskflow.route('POST', ('launch',), launch_taskflow)
from .configuration import Configuration from girder.utility import setting_utilities from .constants import Features, Branding, Deployment from .launch_taskflow import launch_taskflow from .user import get_orcid, set_orcid, get_twitter, set_twitter from girder.plugin import GirderPlugin @setting_utilities.validator({ Features.NOTEBOOKS, Deployment.SITE, Branding.PRIVACY, Branding.LICENSE, Branding.HEADER_LOGO_ID, Branding.FOOTER_LOGO_ID, Branding.FOOTER_LOGO_URL, Branding.FAVICON_ID }) def validateSettings(event): pass class AppPlugin(GirderPlugin): DISPLAY_NAME = 'OpenChemistry App' def load(self, info): info['apiRoot'].configuration = Configuration() # Twitter and orcid stuff info['apiRoot'].user.route('GET', (':id', 'orcid'), get_orcid) info['apiRoot'].user.route('POST', (':id', 'orcid'), set_orcid) info['apiRoot'].user.route('GET', (':id', 'twitter'), get_twitter) info['apiRoot'].user.route('POST', (':id', 'twitter'), set_twitter) # Launch a taskflow with a single endpoint info['apiRoot'].queues.route('POST', ('launchtaskflow',), launch_taskflow)
Make casing of command description consistent with built-in commands The descriptions of the built-in Artisan commands use sentence case, not title case.
<?php namespace Wnx\LaravelStats; use Illuminate\Console\Command; use Wnx\LaravelStats\Formatters\TableOutput; use Wnx\LaravelStats\Statistics\ProjectStatistics; class StatsListCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'stats'; /** * The console command description. * * @var string */ protected $description = 'Generate statistics for this Laravel project'; /** * Execute the console command. * * @param $finder Wnx\LaravelStats\ComponentFinder * @return mixed */ public function handle(ComponentFinder $finder) { $statistics = new ProjectStatistics($finder->get()); (new TableOutput($this->output))->render($statistics); } }
<?php namespace Wnx\LaravelStats; use Illuminate\Console\Command; use Wnx\LaravelStats\Formatters\TableOutput; use Wnx\LaravelStats\Statistics\ProjectStatistics; class StatsListCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'stats'; /** * The console command description. * * @var string */ protected $description = 'Generate Statistics for this Laravel Project'; /** * Execute the console command. * * @param $finder Wnx\LaravelStats\ComponentFinder * @return mixed */ public function handle(ComponentFinder $finder) { $statistics = new ProjectStatistics($finder->get()); (new TableOutput($this->output))->render($statistics); } }
Remove debug message about hiding toasts
// var socket = io.connect(window.location.host); function Socket(){ this.socket = io.connect(window.location.host); } Socket.prototype.makeMarkerFromTweet = function(map){ this.socket.on('tweet', function(data){ // $(".toast").hide(); makeMarker(data.coordinates, map, data.tweet, data.color); }); } Socket.prototype.performNewSearch = function(searchWord){ this.socket.emit('newSearch'); this.socket.emit('search', { word: searchWord }); } Socket.prototype.listenForGeocode = function(map){ this.socket.on('geocoder', function(data){ var address = data.location if (address !== ""){ setTimeout(function(){ geocoding(address, function(latLng) { makeMarker(latLng, map, data.tweet, data.color); }); }, 500); } }); } Socket.prototype.listenForError = function(){ this.socket.on('openModal', function(data){ $('#modal1').openModal(); }); } Socket.prototype.listenForFirstTweet = function(){ console.log("listening..."); this.socket.on('hideToast', function(){ $(".toast").hide(); }); }
// var socket = io.connect(window.location.host); function Socket(){ this.socket = io.connect(window.location.host); } Socket.prototype.makeMarkerFromTweet = function(map){ this.socket.on('tweet', function(data){ // $(".toast").hide(); makeMarker(data.coordinates, map, data.tweet, data.color); }); } Socket.prototype.performNewSearch = function(searchWord){ this.socket.emit('newSearch'); this.socket.emit('search', { word: searchWord }); } Socket.prototype.listenForGeocode = function(map){ this.socket.on('geocoder', function(data){ var address = data.location if (address !== ""){ setTimeout(function(){ geocoding(address, function(latLng) { makeMarker(latLng, map, data.tweet, data.color); }); }, 500); } }); } Socket.prototype.listenForError = function(){ this.socket.on('openModal', function(data){ $('#modal1').openModal(); }); } Socket.prototype.listenForFirstTweet = function(){ console.log("listening..."); this.socket.on('hideToast', function(){ console.log("i'm supposed to be hiding..."); $(".toast").hide(); }); }
Update regex of image source
import EventEmitter from 'eventemitter3' import Mousetrap from 'mousetrap' import dragDrop from 'drag-drop' class Commands extends EventEmitter { constructor() { super() this._initKeybind() this._initDragDrop() } _initKeybind() { Mousetrap.bind('esc', () => { this.emit('reset-canvas') return false }) Mousetrap.bind('command+s', () => { this.emit('save-canvas') return false }) Mousetrap.bind('command+1', () => { this.emit('reload-effects') return false }) Mousetrap.bind('f', () => { this.emit('step-forward') }) } _initDragDrop() { dragDrop('body', (files) => this._validateImageAndEmit('load-source', files)) } _validateImageAndEmit(eventName, files) { if (files.length == 1 && files[0].name.match(/\.(jpg|jpeg|png|gif)$/i)) { this.emit(eventName, files[0]) } else { console.log('failed') } } // public loadImage(eventName) { $('#image-loader') .on('change', (e) => this._validateImageAndEmit(eventName, e.target.files)) .trigger('click') } execute() { this.emit(...arguments) } } window.Commands = new Commands()
import EventEmitter from 'eventemitter3' import Mousetrap from 'mousetrap' import dragDrop from 'drag-drop' class Commands extends EventEmitter { constructor() { super() this._initKeybind() this._initDragDrop() } _initKeybind() { Mousetrap.bind('esc', () => { this.emit('reset-canvas') return false }) Mousetrap.bind('command+s', () => { this.emit('save-canvas') return false }) Mousetrap.bind('command+1', () => { this.emit('reload-effects') return false }) } _initDragDrop() { dragDrop('body', (files) => this._validateImageAndEmit('load-source', files)) } _validateImageAndEmit(eventName, files) { if (files.length == 1 && files[0].name.match(/\.(jpg|jpeg|png|gif)$/)) { this.emit(eventName, files[0]) } else { console.log('failed') } } // public loadImage(eventName) { $('#image-loader') .on('change', (e) => this._validateImageAndEmit(eventName, e.target.files)) .trigger('click') } execute() { this.emit(...arguments) } } window.Commands = new Commands()
Fix path to API doc
# Lint as: python3 # Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Constants definitions for tuner sub module.""" import os # API definition of Cloud AI Platform Optimizer service OPTIMIZER_API_DOCUMENT_FILE = os.path.join( os.path.dirname(os.path.abspath(__file__)), "api/ml_public_google_rest_v1.json") # By default, the Tuner worker(s) always requests one trial at a time because # we would parallelize the tuning loop themselves as opposed to getting multiple # trial suggestions in one tuning loop. SUGGESTION_COUNT_PER_REQUEST = 1 # Number of tries to retry getting study if it was already created NUM_TRIES_FOR_STUDIES = 3
# Lint as: python3 # Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Constants definitions for tuner sub module.""" # API definition of Cloud AI Platform Optimizer service OPTIMIZER_API_DOCUMENT_FILE = "api/ml_public_google_rest_v1.json" # By default, the Tuner worker(s) always requests one trial at a time because # we would parallelize the tuning loop themselves as opposed to getting multiple # trial suggestions in one tuning loop. SUGGESTION_COUNT_PER_REQUEST = 1 # Number of tries to retry getting study if it was already created NUM_TRIES_FOR_STUDIES = 3
Use ops instead of _
from tkinter import Tk, Label, Frame import rx from rx import operators as ops from rx.subjects import Subject from rx.concurrency import TkinterScheduler def main(): root = Tk() root.title("Rx for Python rocks") scheduler = TkinterScheduler(root) mousemove = Subject() frame = Frame(root, width=600, height=600) frame.bind("<Motion>", mousemove.on_next) text = 'TIME FLIES LIKE AN ARROW' def on_next(info): label, ev, i = info label.place(x=ev.x + i*12 + 15, y=ev.y) def handle_label(label, i): label.config(dict(borderwidth=0, padx=0, pady=0)) mapper = ops.map(lambda ev: (label, ev, i)) delayer = ops.delay(i*100) return mousemove.pipe( delayer, mapper ) labeler = ops.flat_mapi(handle_label) mapper = ops.map(lambda c: Label(frame, text=c)) rx.from_(text).pipe( mapper, labeler ).subscribe_(on_next, on_error=print, scheduler=scheduler) frame.pack() root.mainloop() if __name__ == '__main__': main()
from tkinter import Tk, Label, Frame from rx import from_ from rx import operators as _ from rx.subjects import Subject from rx.concurrency import TkinterScheduler def main(): root = Tk() root.title("Rx for Python rocks") scheduler = TkinterScheduler(root) mousemove = Subject() frame = Frame(root, width=600, height=600) frame.bind("<Motion>", mousemove.on_next) text = 'TIME FLIES LIKE AN ARROW' def on_next(info): label, ev, i = info label.place(x=ev.x + i*12 + 15, y=ev.y) def handle_label(label, i): label.config(dict(borderwidth=0, padx=0, pady=0)) mapper = _.map(lambda ev: (label, ev, i)) delayer = _.delay(i*100) return mousemove.pipe( delayer, mapper ) labeler = _.flat_mapi(handle_label) mapper = _.map(lambda c: Label(frame, text=c)) from_(text).pipe( mapper, labeler ).subscribe_(on_next, on_error=print, scheduler=scheduler) frame.pack() root.mainloop() if __name__ == '__main__': main()
Fix an inconsistency of line separator in RunWithAnnotationIntegrationTest. Summary: In `ParametrizedTest` `\n` should be explicitly printed instead of `println` in order to match string pattern defined in `RunWithAnnotationIntegrationTest`. Test Plan: Unit tests.
/* * Copyright 2013-present Facebook, 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. */ package com.example; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; @RunWith(Parameterized.class) public class ParametrizedTest { private int number; public ParametrizedTest(int number) { this.number = number; } @Parameterized.Parameters public static Collection<Object[]> data() { Object[][] data = new Object[][] { { 0 }, { 1 }, { 2 }, { 3 } }; return Arrays.asList(data); } @Test public void parametrizedTest() { System.out.print(String.format("Parameter: %d\n", number)); } }
/* * Copyright 2013-present Facebook, 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. */ package com.example; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; @RunWith(Parameterized.class) public class ParametrizedTest { private int number; public ParametrizedTest(int number) { this.number = number; } @Parameterized.Parameters public static Collection<Object[]> data() { Object[][] data = new Object[][] { { 0 }, { 1 }, { 2 }, { 3 } }; return Arrays.asList(data); } @Test public void parametrizedTest() { System.out.println("Parameter: " + number); } }
Allow coverage to work and keep stdout and be activated before initial imports.
import sys class ResultPlugin(object): """ Captures the TestResult object for later inspection. nose doesn't return the full test result object from any of its runner methods. Pass an instance of this plugin to the TestProgram and use ``result`` after running the tests to get the TestResult object. """ name = "result" enabled = True def finalize(self, result): self.result = result class DjangoSetUpPlugin(object): """ Configures Django to setup and tear down the environment. This allows coverage to report on all code imported and used during the initialisation of the test runner. """ name = "django setup" enabled = True def __init__(self, runner): super(DjangoSetUpPlugin, self).__init__() self.runner = runner self.sys_stdout = sys.stdout def begin(self): """Setup the environment""" sys_stdout = sys.stdout sys.stdout = self.sys_stdout self.runner.setup_test_environment() self.old_names = self.runner.setup_databases() sys.stdout = sys_stdout def finalize(self, result): """Destroy the environment""" self.runner.teardown_databases(self.old_names) self.runner.teardown_test_environment()
class ResultPlugin(object): """ Captures the TestResult object for later inspection. nose doesn't return the full test result object from any of its runner methods. Pass an instance of this plugin to the TestProgram and use ``result`` after running the tests to get the TestResult object. """ name = "result" enabled = True def finalize(self, result): self.result = result class DjangoSetUpPlugin(object): """ Configures Django to setup and tear down the environment. This allows coverage to report on all code imported and used during the initialisation of the test runner. """ name = "django setup" enabled = True # We need this to run before the coverage plugin (which has a score # of 500), so that we still have a stdout for the user interaction # Django sometimes wants to do during test database setup. score = 700 def __init__(self, runner): super(DjangoSetUpPlugin, self).__init__() self.runner = runner def begin(self): """Setup the environment""" self.runner.setup_test_environment() self.old_names = self.runner.setup_databases() def finalize(self, result): """Destroy the environment""" self.runner.teardown_databases(self.old_names) self.runner.teardown_test_environment()
Add error handling so JS errors don't break streams Fixes #1
var gulp = require('gulp'), browserify = require('browserify'), babelify = require('babelify'), source = require('vinyl-source-stream'), paths = require('../paths'); gulp.task('scripts:app', function () { return browserify({ entries: paths.app.scriptsMain, debug: true, transform: ['browserify-handlebars'] }) .transform('babelify', { presets: ['es2015'] }) .bundle() .on('error', function (err) { console.log(err.toString()); this.emit('end'); }) .pipe(source('app.js')) .pipe(gulp.dest(paths.app.tmpJSDir)); }); gulp.task('scripts:vendor', function () { return browserify({ entries: paths.app.scriptsVendor }) .transform('babelify', { presets: ['es2015'] }) .bundle() .on('error', function (err) { console.log(err.toString()); this.emit('end'); }) .pipe(source('vendor.js')) .pipe(gulp.dest(paths.app.tmpJSDir)); });
var gulp = require('gulp'), browserify = require('browserify'), babelify = require('babelify'), source = require('vinyl-source-stream'), paths = require('../paths'); gulp.task('scripts:app', function () { return browserify({ entries: paths.app.scriptsMain, debug: true, transform: ['browserify-handlebars'] }) .transform('babelify', { presets: ['es2015'] }) .bundle() .pipe(source('app.js')) .pipe(gulp.dest(paths.app.tmpJSDir)); }); gulp.task('scripts:vendor', function () { return browserify({ entries: paths.app.scriptsVendor }) .transform('babelify', { presets: ['es2015'] }) .bundle() .pipe(source('vendor.js')) .pipe(gulp.dest(paths.app.tmpJSDir)); });
Change port from 8443 to 443
import { map } from 'mobx'; export const server = { credentials: map(), application: { secure: true, host: 'live.zoomdata.com', path: '/zoomdata', port: 443 }, oauthOptions: { client_id: 'bmh0c2FfY2xpZW50MTQ1ODA2NzM4MTE3NDdkNzAxZGIzLTA3MDMtNDk4Mi1iNThiLTQ4NzU2OTZkOTYwNw==', redirect_uri: 'http://demos.zoomdata.com/nhtsa-dashboard-2.2/index.html', auth_uri: 'https://live.zoomdata.com/zoomdata/oauth/authorize', scope: ['read'] } }; server.credentials = map({ key: '58cbe712e4b0336a00f938d7' });
import { map } from 'mobx'; export const server = { credentials: map(), application: { secure: true, host: 'live.zoomdata.com', path: '/zoomdata', port: 8443 }, oauthOptions: { client_id: 'bmh0c2FfY2xpZW50MTQ1ODA2NzM4MTE3NDdkNzAxZGIzLTA3MDMtNDk4Mi1iNThiLTQ4NzU2OTZkOTYwNw==', redirect_uri: 'http://demos.zoomdata.com/nhtsa-dashboard-2.2/index.html', auth_uri: 'https://live.zoomdata.com/zoomdata/oauth/authorize', scope: ['read'] } }; server.credentials = map({ key: '58cbe712e4b0336a00f938d7' });
Add case insensitive metric parsing
import abc class BaseMetric(abc.ABC): ALIAS = 'base_metric' @abc.abstractmethod def __call__(self, y_true, y_pred): """""" def __repr__(self): return self.ALIAS def parse_metric(metric): if isinstance(metric, BaseMetric): return metric elif isinstance(metric, str): for subclass in BaseMetric.__subclasses__(): if metric.lower() == subclass.ALIAS or metric in subclass.ALIAS: return subclass() return metric # keras native metrics elif issubclass(metric, BaseMetric): return metric() def compute_metric_on_groups(groups, metric): return groups.apply( lambda l: metric(l['y_true'], l['y_pred'])).mean()
import abc class BaseMetric(abc.ABC): ALIAS = 'base_metric' @abc.abstractmethod def __call__(self, y_true, y_pred): """""" def __repr__(self): return self.ALIAS def parse_metric(metric): if isinstance(metric, BaseMetric): return metric elif isinstance(metric, str): for subclass in BaseMetric.__subclasses__(): if metric == subclass.ALIAS or metric in subclass.ALIAS: return subclass() return metric # keras native metrics elif issubclass(metric, BaseMetric): return metric() def compute_metric_on_groups(groups, metric): return groups.apply( lambda l: metric(l['y_true'], l['y_pred'])).mean()
Fix documentation and type annotation
<?php namespace SBLayout\Model\Page\Content; /** * Represents the contents that ends up in the dynamic content sections of a page. * * The content is in most cases a single division containing HTML code, but it can also * be multiple divisions each having their own HTML fragments. */ class Contents { /** An associative array mapping division ids onto PHP files representing HTML content */ public array $sections; /** A string containing the path to the controller page that handles GET or POST parameters or NULL if there is no controller */ public ?string $controller; /** An array containing stylesheet files to include */ public ?array $styles; /** An array containing script files to include */ public ?array $scripts; /** * Creates a new contents instance. * * @param $sections An associative array mapping division ids onto files representing HTML content or a string, which represents the contents of the contents division. * @param $controller A string containing the path to the controller page that handles GET or POST parameters * @param $styles An array containing stylesheet files to include when requesting this page * @param $scripts An array containing script files to include when requesting this page */ public function __construct(array|string $sections, string $controller = null, ?array $styles = array(), ?array $scripts = array()) { if(is_array($sections)) $this->sections = $sections; else $this->sections = array("contents" => $sections); $this->controller = $controller; $this->styles = $styles; $this->scripts = $scripts; } } ?>
<?php namespace SBLayout\Model\Page\Content; /** * Represents the contents that ends up in the dynamic content sections of a page. * * The content is in most cases a single division containing HTML code, but it can also * be multiple divisions each having their own HTML fragments. */ class Contents { /** An associative array mapping division ids onto PHP files representing HTML content */ public array $sections; /** A string containing the path to the controller page that handles GET or POST parameters or NULL if there is no controller */ public ?string $controller; /** An array containing stylesheet files to include */ public ?array $styles; /** An array containing script files to include */ public ?array $scripts; /** * Creates a new contents instance. * * @param $sections An associative array mapping division ids onto files representing HTML content or a string, which represents the contents of the contents division. * @param $controller A string containing the path to the controller page that handles GET or POST parameters * @param array $styles An array containing stylesheet files to include when requesting this page * @param array $scripts An array containing script files to include when requesting this page */ public function __construct(array|string $sections, $controller = NULL, ?array $styles = array(), ?array $scripts = array()) { if(is_array($sections)) $this->sections = $sections; else $this->sections = array("contents" => $sections); $this->controller = $controller; $this->styles = $styles; $this->scripts = $scripts; } } ?>
Use include, not a view, for the root URL.
"""podium URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from .talks import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^talks/', include('podium.talks.urls')), url(r'^', include('podium.talks.urls')), ]
"""podium URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from .talks import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^talks/', include('podium.talks.urls')), url(r'^$', views.session_list_view), ]
Fix flake8 error (too long line)
class DockerError(Exception): def __init__(self, status, data, *args): super().__init__(*args) self.status = status self.message = data['message'] def __repr__(self): return 'DockerError({self.status}, {self.message!r})'.format(self=self) def __str__(self): return 'DockerError({self.status}, {self.message!r})'.format(self=self) class DockerContainerError(DockerError): def __init__(self, status, data, container_id, *args): super().__init__(status, data, *args) self.container_id = container_id def __repr__(self): return ('DockerContainerError(' '{self.status}, {self.message!r}, ' '{self.container_id!r})').format(self=self) def __str__(self): return ('DockerContainerError(' '{self.status}, {self.message!r}, ' '{self.container_id!r})').format(self=self)
class DockerError(Exception): def __init__(self, status, data, *args): super().__init__(*args) self.status = status self.message = data['message'] def __repr__(self): return 'DockerError({self.status}, {self.message!r})'.format(self=self) def __str__(self): return 'DockerError({self.status}, {self.message!r})'.format(self=self) class DockerContainerError(DockerError): def __init__(self, status, data, container_id, *args): super().__init__(status, data, *args) self.container_id = container_id def __repr__(self): return 'DockerContainerError({self.status}, {self.message!r}, {self.container_id!r})'.format(self=self) def __str__(self): return 'DockerContainerError({self.status}, {self.message!r}, {self.container_id!r})'.format(self=self)
Add create sub grid method
# Implement an algorithm that will check whether a given grid of numbers represents a valid Sudoku puzzle def check_rows(grid): i = 0 while i < len(grid): j = 0 ref_check = {} while j < len(grid[i]): if grid[i][j] != '.' and grid[i][j] in ref_check: return False else: ref_check[grid[i][j]] = 1 j += 1 i += 1 return True def check_columns(grid): column = 0 length = len(grid) while column < length: row = 0 ref_check = {} while row < length: if grid[row][column] != '.' and grid[row][column] in ref_check: return False else: ref_check[grid[row][column]] = 1 row += 1 column += 1 return True def create_sub_grid(grid): ref_check = {} for square in grid: if square != '.' and square in ref_check: return False else: ref_check[square] = 1 return True def check_sub_grid(grid): sub_grid = [] for row in range(0, 9, 3): for i in range(0, 9, 3): a = [] for j in range(row, row + 3): for column in range(i, i + 3): a.append(grid[j][column]) sub_grid.append(a) for row in sub_grid: if not create_sub_grid(row): return False return True
# Implement an algorithm that will check whether a given grid of numbers represents a valid Sudoku puzzle def check_rows(grid): i = 0 while i < len(grid): j = 0 ref_check = {} while j < len(grid[i]): if grid[i][j] != '.' and grid[i][j] in ref_check: return False else: ref_check[grid[i][j]] = 1 j += 1 i += 1 return True def check_columns(grid): column = 0 length = len(grid) while column < length: row = 0 ref_check = {} while row < length: if grid[row][column] != '.' and grid[row][column] in ref_check: return False else: ref_check[grid[row][column]] = 1 row += 1 column += 1 return True def create_sub_grid(grid): ref_check = {} for square in grid: if square != '.' and square in ref_check: return False else: ref_check[square] = 1 return True
Use included carton executable on deploy
from fabric.api import * env.hosts = [ 'shaperia@lynx.uberspace.de' ] env.target_directory = './happyman' def init(): run('git clone -q https://github.com/skyshaper/happyman.git ' + env.target_directory) with cd(env.target_directory): run('virtualenv python_virtualenv') def deploy(): local('git push') with cd(env.target_directory): run('git remote update && git reset --hard origin/master') run('./vendor/bin/carton install --cached --deployment') with cd('python_virtualenv'): run('./bin/pip install -r ../cobe_python_requirements.txt') execute(restart) def restart(): run('svc -t ~/service/happyman')
from fabric.api import * env.hosts = [ 'shaperia@lynx.uberspace.de' ] env.target_directory = './happyman' def init(): run('git clone -q https://github.com/skyshaper/happyman.git ' + env.target_directory) with cd(env.target_directory): run('virtualenv python_virtualenv') def deploy(): local('git push') with cd(env.target_directory): run('git remote update && git reset --hard origin/master') run('carton install --cached --deployment') with cd('python_virtualenv'): run('./bin/pip install -r ../cobe_python_requirements.txt') execute(restart) def restart(): run('svc -t ~/service/happyman')
Handle when database is None
# -*- coding: utf-8 -*- import contextlib import logging from framework.mongo import database as proxy_database from website import settings as osfsettings logger = logging.getLogger(__name__) @contextlib.contextmanager def handle_missing_client(): try: yield except AttributeError: if not osfsettings.DEBUG_MODE: logger.error('MongoDB client not attached to request.') def begin(database=None): database = database or proxy_database with handle_missing_client(): database.command('beginTransaction') def rollback(database=None): database = database or proxy_database with handle_missing_client(): database.command('rollbackTransaction') def commit(database=None): database = database or proxy_database with handle_missing_client(): database.command('commitTransaction') def show_live(database=None): database = database or proxy_database with handle_missing_client(): return database.command('showLiveTransactions') def disconnect(database=None): database = database or proxy_database with handle_missing_client(): database.connection.close()
# -*- coding: utf-8 -*- import logging from framework.mongo import database as proxy_database from website import settings as osfsettings logger = logging.getLogger(__name__) def begin(database=None): database = database or proxy_database database.command('beginTransaction') def rollback(database=None): database = database or proxy_database database.command('rollbackTransaction') def commit(database=None): database = database or proxy_database database.command('commitTransaction') def show_live(database=None): database = database or proxy_database return database.command('showLiveTransactions') def disconnect(database=None): database = database or proxy_database try: database.connection.close() except AttributeError: if not osfsettings.DEBUG_MODE: logger.error('MongoDB client not attached to request.')
Change shorthand array syntax to pre-5.4
<?php use ToniPeric\Oib; class OibTest extends PHPUnit_Framework_TestCase { /** * @test */ function it_validates_a_single_oib() { $this->assertEquals(true, Oib::validate(71481280786)); } /** * @test */ function it_invalidates_a_single_oib() { $this->assertEquals(false, Oib::validate('foo')); } /** * @test */ public function it_validates_an_array_of_oibs() { $oibs = array(71481280786, 64217529143, 'foo'); $this->assertEquals(array($oibs[0] => true, $oibs[1] => true, $oibs[2] => false), Oib::validate($oibs)); } }
<?php use ToniPeric\Oib; class OibTest extends PHPUnit_Framework_TestCase { /** * @test */ function it_validates_a_single_oib() { $this->assertEquals(true, Oib::validate(71481280786)); } /** * @test */ function it_invalidates_a_single_oib() { $this->assertEquals(false, Oib::validate('foo')); } /** * @test */ public function it_validates_an_array_of_oibs() { $oibs = [71481280786, 64217529143, 'foo']; $this->assertEquals([$oibs[0] => true, $oibs[1] => true, $oibs[2] => false], Oib::validate($oibs)); } }
Tag output directory for better input/output handling
/** * Copyright © 2013 Commerce Technologies, LLC. * * 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.commercehub.gradle.plugin.avro; import org.gradle.api.file.FileCollection; import org.gradle.api.specs.Spec; import org.gradle.api.tasks.OutputDirectory; import org.gradle.api.tasks.SourceTask; import java.io.File; class OutputDirTask extends SourceTask { private File outputDir; public void setOutputDir(File outputDir) { this.outputDir = outputDir; getOutputs().dir(outputDir); } @OutputDirectory protected File getOutputDir() { return outputDir; } protected FileCollection filterSources(Spec<? super File> spec) { return getInputs().getSourceFiles().filter(spec); } }
/** * Copyright © 2013 Commerce Technologies, LLC. * * 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.commercehub.gradle.plugin.avro; import org.gradle.api.file.FileCollection; import org.gradle.api.specs.Spec; import org.gradle.api.tasks.SourceTask; import java.io.File; class OutputDirTask extends SourceTask { private File outputDir; public void setOutputDir(File outputDir) { this.outputDir = outputDir; getOutputs().dir(outputDir); } protected File getOutputDir() { return outputDir; } protected FileCollection filterSources(Spec<? super File> spec) { return getInputs().getSourceFiles().filter(spec); } }
Update source directory in coveralls configuration.
<?php use mageekguy\atoum\reports; $runner ->addTestsFromDirectory(__DIR__ . '/tests/units/classes') ->disallowUndefinedMethodInInterface() ; $travis = getenv('TRAVIS'); if ($travis) { $script->addDefaultReport(); $coverallsToken = getenv('COVERALLS_REPO_TOKEN'); if ($coverallsToken) { $coverallsReport = new reports\asynchronous\coveralls('classes', $coverallsToken); $defaultFinder = $coverallsReport->getBranchFinder(); $coverallsReport ->setBranchFinder(function() use ($defaultFinder) { if (($branch = getenv('TRAVIS_BRANCH')) === false) { $branch = $defaultFinder(); } return $branch; } ) ->setServiceName('travis-ci') ->setServiceJobId(getenv('TRAVIS_JOB_ID')) ->addDefaultWriter() ; $runner->addReport($coverallsReport); } }
<?php use mageekguy\atoum\reports; $runner ->addTestsFromDirectory(__DIR__ . '/tests/units/classes') ->disallowUndefinedMethodInInterface() ; $travis = getenv('TRAVIS'); if ($travis) { $script->addDefaultReport(); $coverallsToken = getenv('COVERALLS_REPO_TOKEN'); if ($coverallsToken) { $coverallsReport = new reports\asynchronous\coveralls(__DIR__ . '/classes', $coverallsToken); $defaultFinder = $coverallsReport->getBranchFinder(); $coverallsReport ->setBranchFinder(function() use ($defaultFinder) { if (($branch = getenv('TRAVIS_BRANCH')) === false) { $branch = $defaultFinder(); } return $branch; } ) ->setServiceName('travis-ci') ->setServiceJobId(getenv('TRAVIS_JOB_ID')) ->addDefaultWriter() ; $runner->addReport($coverallsReport); } }
Change context to / to support OS X and Windows
package scratch; import com.ettrema.httpclient.ReportMethod; import java.io.IOException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.StringRequestEntity; /** * * @author brad */ public class PrincipalsReport { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { HttpClient client = new HttpClient(); ReportMethod rm = new ReportMethod( "http://localhost:9080/principals"); rm.setRequestHeader( "depth", "0"); rm.setRequestEntity( new StringRequestEntity( "<x0:principal-search-property-set xmlns:x0=\"DAV:\"/>", "text/xml", "UTF-8")); int result = client.executeMethod( rm ); System.out.println( "result: " + result ); String resp = rm.getResponseBodyAsString(); System.out.println( "response--" ); System.out.println( resp ); } }
package scratch; import com.ettrema.httpclient.ReportMethod; import java.io.IOException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.StringRequestEntity; /** * * @author brad */ public class PrincipalsReport { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { HttpClient client = new HttpClient(); ReportMethod rm = new ReportMethod( "http://localhost:9080/webdav-caldav/principals"); rm.setRequestHeader( "depth", "0"); rm.setRequestEntity( new StringRequestEntity( "<x0:principal-search-property-set xmlns:x0=\"DAV:\"/>", "text/xml", "UTF-8")); int result = client.executeMethod( rm ); System.out.println( "result: " + result ); String resp = rm.getResponseBodyAsString(); System.out.println( "response--" ); System.out.println( resp ); } }
Create feature flag to log extra data in ReactWebView Summary: This diff creates a new react feature flag to enable extra logging on React Web Views Reviewed By: RSNara Differential Revision: D15729871 fbshipit-source-id: 931d4a1b022c6a405228bf896b50ecc7a44478d1
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.config; /** * Hi there, traveller! This configuration class is not meant to be used by end-users of RN. It * contains mainly flags for features that are either under active development and not ready for * public consumption, or for use in experiments. * * These values are safe defaults and should not require manual changes. */ public class ReactFeatureFlags { /** * Whether we should load a specific view manager immediately or when it is accessed by JS */ public static boolean lazilyLoadViewManagers = false; /** * Reduce the number of Java-JS interops while accessing native arrays */ public static boolean useArrayNativeAccessor = false; /** * Reduce the number of Java-JS interops while accessing native maps */ public static boolean useMapNativeAccessor = false; /** * Should this application use TurboModules. If yes, then any module that inherits * {@link com.facebook.react.turbomodule.core.interfaces.TurboModule} will NOT be passed in to * C++ CatalystInstanceImpl */ public static boolean useTurboModules = false; /** * Log tags of when a view deleted on the native side * {@link com.facebook.react.uimanager.NativeViewHierarchyManager dropView} */ public static boolean logDroppedViews = false; /* * This feature flag enables extra logging on ReactWebViews. * Default value is false. */ public static boolean enableExtraWebViewLogs = false; }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.config; /** * Hi there, traveller! This configuration class is not meant to be used by end-users of RN. It * contains mainly flags for features that are either under active development and not ready for * public consumption, or for use in experiments. * * These values are safe defaults and should not require manual changes. */ public class ReactFeatureFlags { /** * Whether we should load a specific view manager immediately or when it is accessed by JS */ public static boolean lazilyLoadViewManagers = false; /** * Reduce the number of Java-JS interops while accessing native arrays */ public static boolean useArrayNativeAccessor = false; /** * Reduce the number of Java-JS interops while accessing native maps */ public static boolean useMapNativeAccessor = false; /** * Should this application use TurboModules. If yes, then any module that inherits * {@link com.facebook.react.turbomodule.core.interfaces.TurboModule} will NOT be passed in to * C++ CatalystInstanceImpl */ public static boolean useTurboModules = false; /** * Log tags of when a view deleted on the native side * {@link com.facebook.react.uimanager.NativeViewHierarchyManager dropView} */ public static boolean logDroppedViews = false; }
Fix panic on missing assertion attribute
package saml // AttributesMap is a type that provides methods for working with SAML // attributes. type AttributesMap map[string][]string // NewAttributesMap creates an attribute map given a third party assertion. func NewAttributesMap(assertion *Assertion) *AttributesMap { props := make(AttributesMap) if assertion == nil { return &props } if assertion.Subject != nil && assertion.Subject.NameID != nil { props[assertion.Subject.NameID.Format] = []string{assertion.Subject.NameID.Value} } if assertion.AttributeStatement != nil { for _, attr := range assertion.AttributeStatement.Attributes { values := []string{} for _, value := range attr.Values { values = append(values, value.Value) } key := attr.Name if key == "" { key = attr.FriendlyName } props[key] = values } return &props } return &props } // Get returns the first value of the given attribute, if any. func (a *AttributesMap) Get(name string) string { if v, ok := (map[string][]string)(*a)[name]; ok { if len(v) > 0 { return v[0] } } return "" }
package saml // AttributesMap is a type that provides methods for working with SAML // attributes. type AttributesMap map[string][]string // NewAttributesMap creates an attribute map given a third party assertion. func NewAttributesMap(assertion *Assertion) *AttributesMap { props := make(AttributesMap) if assertion == nil { return &props } if assertion.Subject != nil && assertion.Subject.NameID != nil { props[assertion.Subject.NameID.Format] = []string{assertion.Subject.NameID.Value} } if assertion.AttributeStatement != nil { for _, attr := range assertion.AttributeStatement.Attributes { values := []string{} for _, value := range attr.Values { values = append(values, value.Value) } key := attr.Name if key == "" { key = attr.FriendlyName } props[key] = values } return &props } return &props } // Get returns the first value of the given attribute, if any. func (a *AttributesMap) Get(name string) string { if v, ok := (map[string][]string)(*a)[name]; ok { return v[0] } return "" }
Fix password column for future hashing
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password', 60); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
Return early if an error occurred The subsequent Execute command won't do anything in an error state, but this makes it obvious and provides another safety check.
package medtronic import ( "fmt" "log" ) const ( maxBolus = 25000 // milliUnits ) // Bolus delivers the given amount of insulin as a bolus. func (pump *Pump) Bolus(amount Insulin) { if amount < 0 { pump.SetError(fmt.Errorf("bolus amount (%d) is negative", amount)) } if amount > maxBolus { pump.SetError(fmt.Errorf("bolus amount (%d) is too large", amount)) } if pump.Error() != nil { return } family := pump.Family() d := milliUnitsPerStroke(family) strokes := amount / d actual := strokes * d if actual != amount { log.Printf("rounding bolus from %v to %v", amount, actual) } if family <= 22 { pump.Execute(bolus, uint8(strokes)) } else { pump.Execute(bolus, marshalUint16(uint16(strokes))...) } }
package medtronic import ( "fmt" "log" ) const ( maxBolus = 25000 // milliUnits ) // Bolus delivers the given amount of insulin as a bolus. func (pump *Pump) Bolus(amount Insulin) { if amount < 0 { pump.SetError(fmt.Errorf("bolus amount (%d) is negative", amount)) } if amount > maxBolus { pump.SetError(fmt.Errorf("bolus amount (%d) is too large", amount)) } family := pump.Family() d := milliUnitsPerStroke(family) strokes := amount / d actual := strokes * d if actual != amount { log.Printf("rounding bolus from %v to %v", amount, actual) } if family <= 22 { pump.Execute(bolus, uint8(strokes)) } else { pump.Execute(bolus, marshalUint16(uint16(strokes))...) } }
Fix warnings in widget form
<?php /** * sfWidgetFormDuration is a text field that parses a duration ("1:15") into an integer * * @package limetracker * @subpackage widget * @author Michael Nutt <michael@nuttnet.net> * @version 0.1 */ class sfWidgetFormDuration extends sfWidgetFormInput { /** * Configures the current widget */ protected function configure($options=array(), $attributes=array()) { parent::configure($options, $attributes); } public function render($name, $value = null, $attributes = array(), $errors = array()) { return parent::render($name, $this->getFormattedLength($value), $attributes, $errors); } public function getFormattedLength($length=0) { $hours = (int) ($length / 3600); $minutes = (int) ($length % 3600 / 60); $seconds = (int) ($length % 60); if($seconds < 10) $seconds = "0".$seconds; if($hours > 0) { if($minutes < 10) $minutes = "0".$minutes; return $hours.":".$minutes.":".$seconds; } else { return $minutes.":".$seconds; } } }
<?php /** * sfWidgetFormDuration is a text field that parses a duration ("1:15") into an integer * * @package limetracker * @subpackage widget * @author Michael Nutt <michael@nuttnet.net> * @version 0.1 */ class sfWidgetFormDuration extends sfWidgetFormInput { /** * Configures the current widget */ protected function configure() { parent::configure($options, $attributes); } public function render($name, $value = null, $attributes = array(), $errors = array()) { return parent::render($name, $this->getFormattedLength($value), $attributes, $errors); } public function getFormattedLength($length=0) { $hours = (int) ($length / 3600); $minutes = (int) ($length % 3600 / 60); $seconds = (int) ($length % 60); if($seconds < 10) $seconds = "0".$seconds; if($hours > 0) { if($minutes < 10) $minutes = "0".$minutes; return $hours.":".$minutes.":".$seconds; } else { return $minutes.":".$seconds; } } }
Print out headers with packet data
package netflow9 import ( "encoding/hex" "fmt" ) func Dump(p *Packet) { fmt.Println("NetFlow version 9 packet") for _, ds := range p.DataFlowSets { fmt.Printf(" data set template %d, length: %d\n", ds.Header.ID, ds.Header.Length) if ds.Records == nil { fmt.Printf(" %d raw bytes:\n", len(ds.Bytes)) fmt.Println(hex.Dump(ds.Bytes)) continue } fmt.Printf(" %d records:\n", len(ds.Records)) for i, dr := range ds.Records { fmt.Printf(" record %d:\n", i) for _, f := range dr.Fields { if f.Translated != nil { if f.Translated.Name != "" { fmt.Printf(" %s: %v\n", f.Translated.Name, f.Translated.Value) } else { fmt.Printf(" %d: %v\n", f.Translated.Type, f.Bytes) } } else { fmt.Printf(" %d: %v (raw)\n", f.Type, f.Bytes) } } } } }
package netflow9 import ( "encoding/hex" "fmt" ) func Dump(p *Packet) { fmt.Println("NetFlow version 9 packet") for _, ds := range p.DataFlowSets { fmt.Println(" data set") if ds.Records == nil { fmt.Printf(" %d raw bytes:\n", len(ds.Bytes)) fmt.Println(hex.Dump(ds.Bytes)) continue } fmt.Printf(" %d records:\n", len(ds.Records)) for i, dr := range ds.Records { fmt.Printf(" record %d:\n", i) for _, f := range dr.Fields { if f.Translated != nil { if f.Translated.Name != "" { fmt.Printf(" %s: %v\n", f.Translated.Name, f.Translated.Value) } else { fmt.Printf(" %d: %v\n", f.Translated.Type, f.Bytes) } } else { fmt.Printf(" %d: %v (raw)\n", f.Type, f.Bytes) } } } } }
Fix: Remove duplicate entry in array of modules
<?php ini_set('display_errors', 1); return array( 'modules' => array( 'ZF\DevelopmentMode', 'AssetManager', 'ZfcBase', 'ZfcUser', 'ScnSocialAuth', 'EdpGithub', 'Application', 'User', 'EdpModuleLayouts', 'ZfModule', 'EdpMarkdown', ), 'module_listener_options' => array( 'config_glob_paths' => array( 'config/autoload/{,*.}{global,local}.php', ), 'module_paths' => array( './module', './vendor', ), ), );
<?php ini_set('display_errors', 1); return array( 'modules' => array( 'Application', 'ZF\DevelopmentMode', 'AssetManager', 'ZfcBase', 'ZfcUser', 'ScnSocialAuth', 'EdpGithub', 'Application', 'User', 'EdpModuleLayouts', 'ZfModule', 'EdpMarkdown', ), 'module_listener_options' => array( 'config_glob_paths' => array( 'config/autoload/{,*.}{global,local}.php', ), 'module_paths' => array( './module', './vendor', ), ), );
Fix to allow “_” (underline) in file path name
package seedu.taskmanager.logic.parser; import java.util.regex.Pattern; import seedu.taskmanager.logic.parser.ArgumentTokenizer.Prefix; /** * Contains Command Line Interface (CLI) syntax definitions common to multiple commands */ public class CliSyntax { /* Prefix definitions */ public static final Prefix PREFIX_STARTDATE = new Prefix("s/"); public static final Prefix PREFIX_ENDDATE = new Prefix("e/"); public static final Prefix PREFIX_DESCRIPTION = new Prefix("d/"); public static final Prefix PREFIX_TAG = new Prefix("#"); /* Alternative prefix definitions for natural variations of user input*/ // public static final Prefix ALTERNATIVE_PREFIX_STARTDATE = new Prefix("start on "); // public static final Prefix ALTERNATIVE_PREFIX_ENDDATE = new Prefix("end on "); // public static final Prefix ALTERNATIVE_PREFIX_DESCRIPTION = new Prefix("with description "); /* Patterns definitions */ public static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace // File Path allows numbers, "/.-", space, lowercase and uppercase letters public static final Pattern FILEPATH_ARGS_FORMAT = Pattern.compile("([ 0-9a-zA-Z/_.-])+"); }
package seedu.taskmanager.logic.parser; import java.util.regex.Pattern; import seedu.taskmanager.logic.parser.ArgumentTokenizer.Prefix; /** * Contains Command Line Interface (CLI) syntax definitions common to multiple commands */ public class CliSyntax { /* Prefix definitions */ public static final Prefix PREFIX_STARTDATE = new Prefix("s/"); public static final Prefix PREFIX_ENDDATE = new Prefix("e/"); public static final Prefix PREFIX_DESCRIPTION = new Prefix("d/"); public static final Prefix PREFIX_TAG = new Prefix("#"); /* Alternative prefix definitions for natural variations of user input*/ // public static final Prefix ALTERNATIVE_PREFIX_STARTDATE = new Prefix("start on "); // public static final Prefix ALTERNATIVE_PREFIX_ENDDATE = new Prefix("end on "); // public static final Prefix ALTERNATIVE_PREFIX_DESCRIPTION = new Prefix("with description "); /* Patterns definitions */ public static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace // File Path allows numbers, "/.-", space, lowercase and uppercase letters public static final Pattern FILEPATH_ARGS_FORMAT = Pattern.compile("([ 0-9a-zA-Z/.-])+"); }
Test for invalid token when expanding token
package com.connect_group.urlshortener; import org.junit.Test; import java.net.MalformedURLException; import java.net.URL; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; public class ShortenerServiceImplTest { @Test public void shouldConvertUrlToToken() throws MalformedURLException { ShortenerServiceImpl service = new ShortenerServiceImpl(); String shortUrl = service.shorten(new URL("http://test.com/url?param=value")); assertThat(shortUrl, equalTo("-")); } @Test public void shouldConvertTokenToUrl() throws UnrecognisedTokenException, MalformedURLException { String url = "http://test.com/url?param=value"; ShortenerServiceImpl service = new ShortenerServiceImpl(); String token = service.shorten(new URL(url)); assertThat(service.expand(token), equalTo(url)); } @Test(expected=UnrecognisedTokenException.class) public void shouldThrowException_WhenNullToken() throws UnrecognisedTokenException { new ShortenerServiceImpl().expand(null); } }
package com.connect_group.urlshortener; import org.junit.Test; import java.net.MalformedURLException; import java.net.URL; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; public class ShortenerServiceImplTest { @Test public void shouldConvertUrlToToken() throws MalformedURLException { ShortenerServiceImpl service = new ShortenerServiceImpl(); String shortUrl = service.shorten(new URL("http://test.com/url?param=value")); assertThat(shortUrl, equalTo("-")); } @Test public void shouldConvertTokenToUrl() throws UnrecognisedTokenException, MalformedURLException { String url = "http://test.com/url?param=value"; ShortenerServiceImpl service = new ShortenerServiceImpl(); String token = service.shorten(new URL(url)); assertThat(service.expand(token), equalTo(url)); } }
Add better BOSH release diff output - Ensure all jobs are compared (added, changed, or removed) - Only output property differences instead of all the BOSH release diff noise
package diff import ( "github.com/kr/pretty" "github.com/xchapter7x/enaml" ) type boshReleaseDiffer struct { release1 *boshRelease release2 *boshRelease } func (d boshReleaseDiffer) Diff() (result Result, err error) { result = Result{} var jresult Result for _, jname := range d.allJobNames() { jresult, err = d.DiffJob(jname) result.Deltas = append(result.Deltas, jresult.Deltas...) } return } func (d boshReleaseDiffer) DiffJob(job string) (result Result, err error) { result = Result{} var job1, job2 enaml.JobManifest job1 = d.release1.JobManifests[job] job2 = d.release2.JobManifests[job] result.Deltas = pretty.Diff(job1, job2) return } // allJobNames returns a union of unique job names across both BOSH releases func (d boshReleaseDiffer) allJobNames() []string { jobNamesMap := make(map[string]string) var addJobNames = func(br *boshRelease) { if br != nil { for jbname := range br.JobManifests { jobNamesMap[jbname] = jbname } } } addJobNames(d.release1) addJobNames(d.release2) var jobNames []string for jname := range jobNamesMap { jobNames = append(jobNames, jname) } return jobNames }
package diff import ( "fmt" "github.com/kr/pretty" "github.com/xchapter7x/enaml" ) type boshReleaseDiffer struct { release1 *boshRelease release2 *boshRelease } func (d boshReleaseDiffer) Diff() (result Result, err error) { result = Result{} result.Deltas = pretty.Diff(d.release1, d.release2) return } func (d boshReleaseDiffer) DiffJob(job string) (result Result, err error) { result = Result{} var ( job1, job2 enaml.JobManifest ok bool ) if job1, ok = d.release1.JobManifests[job]; !ok { err = fmt.Errorf("Couldn't find job '%s' in release 1", job) return } if job2, ok = d.release2.JobManifests[job]; !ok { err = fmt.Errorf("Couldn't find job '%s' in release 2", job) return } result.Deltas = pretty.Diff(job1, job2) return }
Use setProperty instead of handleClick to work with Thing
/** * OnOffDetail * * A bubble showing the on/off state of a thing * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; const Utils = require('../utils'); class OnOffDetail { constructor(thing, name, property) { this.thing = thing; this.name = name; this.label = property.label || 'On/Off'; this.id = `on-off-${Utils.escapeHtmlForIdClass(this.name)}`; } attach() { this.input = this.thing.element.querySelector(`#${this.id}`); const setOnOff = Utils.debounce(500, this.set.bind(this)); this.input.addEventListener('change', setOnOff); } view() { const checked = this.thing.properties[this.name]; return ` <webthing-on-off-property data-name="${Utils.escapeHtml(this.label)}" ${checked ? 'checked' : ''} id="${this.id}"> </webthing-on-off-property>`; } update() { const on = this.thing.properties[this.name]; this.input.checked = on; } set() { this.thing.setProperty(this.name, this.input.checked); } } module.exports = OnOffDetail;
/** * OnOffDetail * * A bubble showing the on/off state of a thing * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; const Utils = require('../utils'); class OnOffDetail { constructor(thing, name, property) { this.thing = thing; this.name = name; this.label = property.label || 'On/Off'; this.id = `on-off-${Utils.escapeHtmlForIdClass(this.name)}`; } attach() { this.onOffSwitch = this.thing.element.querySelector(`#${this.id}`); if (typeof this.thing.handleClick === 'function') { const handleClick = Utils.debounce( 500, this.thing.handleClick.bind(this.thing) ); this.onOffSwitch.addEventListener('change', handleClick); } } view() { const checked = this.thing.properties[this.name]; return ` <webthing-on-off-property data-name="${Utils.escapeHtml(this.label)}" ${checked ? 'checked' : ''} id="${this.id}"> </webthing-on-off-property>`; } update() { const on = this.thing.properties[this.name]; this.onOffSwitch.checked = on; } } module.exports = OnOffDetail;
Change version number to 0.1dev
""" Flask-Static --------------- Generates a static website from a Flask application. """ from setuptools import setup setup( name='Flask-Static', version='0.1dev', url='http://exyr.org/Flask-Static/', license='BSD', author='Simon Sapin', author_email='simon.sapin@exyr.org', description='Generates a static website from a Flask application', long_description=__doc__, packages=['flaskext'], namespace_packages=['flaskext'], test_suite='test_flaskstatic', zip_safe=False, platforms='any', install_requires=[ 'Flask', ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
""" Flask-Static --------------- Generates a static website from a Flask application. """ from setuptools import setup setup( name='Flask-Static', version='0.1', url='http://exyr.org/Flask-Static/', license='BSD', author='Simon Sapin', author_email='simon.sapin@exyr.org', description='Generates a static website from a Flask application', long_description=__doc__, packages=['flaskext'], namespace_packages=['flaskext'], test_suite='test_flaskstatic', zip_safe=False, platforms='any', install_requires=[ 'Flask', ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Fix compilation... forgot to 'mvn clean'
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.bootstrap; /** * A wrapper around {@link Bootstrap} just so the process will look nicely on things like jps. */ public class Elasticsearch extends Bootstrap { public static void main(String[] args) throws StartupError { Bootstrap.main(args); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.bootstrap; /** * A wrapper around {@link Bootstrap} just so the process will look nicely on things like jps. */ public class Elasticsearch extends Bootstrap { public static void main(String[] args) throws Throwable { Bootstrap.main(args); } }
fix: Fix new expectations of the password reset
from django.test import Client, TestCase from django.urls import reverse from django.contrib.auth.models import User from ddcz.models import UserProfile class PasswordResetTestCase(TestCase): fixtures = ['pages'] def setUp(self): super().setUp() self.client = Client() self.valid_password = 'xoxo' self.valid_email = 'test@example.com' self.nick = 'integration test user' self.valid_user = User.objects.create( username = self.nick, password = self.valid_password ) self.valid_profile = UserProfile.objects.create( nick_uzivatele = self.nick, email_uzivatele = self.valid_email, user = self.valid_user ) def test_sending_form(self): res = self.client.post(reverse('ddcz:password-reset'), { 'email': self.valid_email }) self.assertEquals(302, res.status_code)
from django.test import Client, TestCase from django.urls import reverse from django.contrib.auth.models import User from ddcz.models import UserProfile class PasswordResetTestCase(TestCase): fixtures = ['pages'] def setUp(self): super().setUp() self.client = Client() self.valid_password = 'xoxo' self.valid_email = 'test@example.com' self.nick = 'integration test user' self.valid_user = User.objects.create( username = self.nick, password = self.valid_password ) self.valid_profile = UserProfile.objects.create( nick_uzivatele = self.nick, email_uzivatele = self.valid_email, user = self.valid_user ) def test_sending_form(self): res = self.client.post(reverse('ddcz:password-reset'), { 'email': self.valid_email }) self.assertEquals(200, res.status_code)
Add possibility to return the event object as well
import logging from hestia.tz_utils import now from kubernetes import watch from ocular.processor import get_pod_state logger = logging.getLogger('ocular') def monitor(k8s_api, namespace, container_names, label_selector=None, return_event=False): w = watch.Watch() for event in w.stream(k8s_api.list_namespaced_pod, namespace=namespace, label_selector=label_selector): created_at = now() logger.debug("Received event: %s", event['type']) event_object = event['object'].to_dict() logger.debug("Event object: %s", event_object) pod_state = get_pod_state( event_type=event['type'], event=event_object, job_container_names=container_names, created_at=created_at) logger.debug("Pod state: %s", pod_state) if return_event: yield (event_object, pod_state) else: yield pod_state
import logging from hestia.tz_utils import now from kubernetes import watch from ocular.processor import get_pod_state logger = logging.getLogger('ocular') def monitor(k8s_api, namespace, container_names, label_selector=None): w = watch.Watch() for event in w.stream(k8s_api.list_namespaced_pod, namespace=namespace, label_selector=label_selector): created_at = now() logger.debug("Received event: %s", event['type']) event_object = event['object'].to_dict() logger.debug(event_object) yield get_pod_state( event_type=event['type'], event=event_object, job_container_names=container_names, created_at=created_at)
Revert "Only apply bindings to standalone components" This reverts commit 6a91688cb6559c995b5c9390834f9bfb6ef91e63.
(function () { var components = { 'inline-edit': 'hqwebapp/js/components/inline_edit', 'pagination': 'hqwebapp/js/components/pagination' }; _.each(components, function(moduleName, elementName) { ko.components.register(elementName, hqImport(moduleName)); }); $(function() { _.each(_.keys(components), function(elementName) { _.each($(elementName), function(el) { var $el = $(el); if (!$el.closest('.ko-template').length) { $(el).koApplyBindings(); } }); }); }); }());
(function () { // standalone components will have their own knockout bindings. Use // standalone: false if you want to mix the component into another model var components = { 'inline-edit': {path: 'hqwebapp/js/components/inline_edit', standalone: true}, 'pagination': {path: 'hqwebapp/js/components/pagination', standalone: false}, }; _.each(components, function(module, elementName) { ko.components.register(elementName, hqImport(module.path)); }); $(function() { _.each(components, function(module, elementName) { if (module.standalone){ _.each($(elementName), function(el) { var $el = $(el); if (!$el.closest('.ko-template').length) { $(el).koApplyBindings(); } }); } }); }); }());
Fix install deps Things will work only in test where cis_fake_well_known is installed otherwise, but "prod" deploys would be missing deps that it would pull (even thus `make install` otherwise works)
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() requirements = ['python-jose', 'python-jose-cryptodome', 'everett', 'boto3==1.7.67', 'boto==2.49.0', 'botocore==1.10.67', 'requests', 'pyaml'] setup_requirements = ['pytest-runner'] test_requirements = ['pytest', 'pytest-watch', 'pytest-cov', 'pytest-mock', 'moto', 'mock', 'cis_fake_well_known'] setup( name="cis_crypto", version="0.0.1", author="Andrew Krug", author_email="akrug@mozilla.com", description="Per attribute signature system for jwks sign-verify in mozilla-iam.", long_description=long_description, url="https://github.com/mozilla-iam/cis", classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: Mozilla Public License", "Operating System :: OS Independent", ], install_requires=requirements, license="Mozilla Public License 2.0", include_package_data=True, packages=find_packages(include=['cis_crypto', 'bin']), scripts=['bin/cis_crypto'], setup_requires=setup_requirements, test_suite='tests', tests_require=test_requirements, zip_safe=False )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() requirements = ['python-jose-cryptodome', 'everett', 'boto3==1.7.67', 'boto==2.49.0', 'botocore==1.10.67', 'requests', 'pyaml'] setup_requirements = ['pytest-runner'] test_requirements = ['pytest', 'pytest-watch', 'pytest-cov', 'pytest-mock', 'moto', 'mock', 'cis_fake_well_known'] setup( name="cis_crypto", version="0.0.1", author="Andrew Krug", author_email="akrug@mozilla.com", description="Per attribute signature system for jwks sign-verify in mozilla-iam.", long_description=long_description, url="https://github.com/mozilla-iam/cis", classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: Mozilla Public License", "Operating System :: OS Independent", ], install_requires=requirements, license="Mozilla Public License 2.0", include_package_data=True, packages=find_packages(include=['cis_crypto', 'bin']), scripts=['bin/cis_crypto'], setup_requires=setup_requirements, test_suite='tests', tests_require=test_requirements, zip_safe=False )
Clean up for autocomplete servlet
package com.screaminggreen.sculptor; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.datastore.Entity; import com.screaminggreen.beans.ProfessorBean; import com.screaminggreen.beans.SessionBean; import com.screaminggreen.datastore.CourseTab; import com.screaminggreen.datastore.DatastoreAPI; import com.screaminggreen.datastore.Professor; @SuppressWarnings("serial") public class SearchServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); Iterable<Entity> entities = Professor.getAllProfessors("Professor"); String json = DatastoreAPI.writeJSON(entities); resp.setStatus(200); out.println(json); out.close(); } }
package com.screaminggreen.sculptor; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.datastore.Entity; import com.screaminggreen.beans.ProfessorBean; import com.screaminggreen.beans.SessionBean; import com.screaminggreen.datastore.CourseTab; import com.screaminggreen.datastore.DatastoreAPI; import com.screaminggreen.datastore.Professor; @SuppressWarnings("serial") public class SearchServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); Iterable<Entity> entities = Professor.getAllProfessors("Professor"); String json = DatastoreAPI.writeJSON(entities); System.out.println(json); resp.setStatus(200); out.println(json); out.close(); } }
Change version 0.1 -> 0.2
""" Setup file for distutils """ from distutils.core import setup from setuptools import find_packages setup( name='python-gdrive', version='0.2', author='Tony Sanchez', author_email='mail.tsanchez@gmail.com', url='https://github.com/tsanch3z/python-gdrive', download_url='https://github.com/tsanch3z/python-gdrive/archive/master.zip', description='Gdrive REST api client', packages=find_packages(exclude=['tests']), license='GPLv2', platforms='OS Independent', classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules', 'Environment :: Web Environment', 'Development Status :: 4 - Beta' ], install_requires='requests>=2.2.1' )
""" Setup file for distutils """ from distutils.core import setup from setuptools import find_packages setup( name='python-gdrive', version='0.1', author='Tony Sanchez', author_email='mail.tsanchez@gmail.com', url='https://github.com/tsanch3z/python-gdrive', download_url='https://github.com/tsanch3z/python-gdrive/archive/master.zip', description='Gdrive REST api client', packages=find_packages(exclude=['tests']), license='GPLv2', platforms='OS Independent', classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules', 'Environment :: Web Environment', 'Development Status :: 4 - Beta' ], install_requires='requests>=2.2.1' )
Update ValueLink To Use Timepicker's ValueLink Update ValueLink to use the Timepicker's Valuelink in order to update the text in the Timepicker's Popup
let React = require("react") let cx = require("classnames") let popup = React.createFactory(require("./timepicker_popup")) let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js") let {div, input} = React.DOM export default class extends React.Component { static displayName = "Frig.friggingBootstrap.TimePicker" static defaultProps = Object.assign(require("../default_props.js")) _input() { return input(Object.assign({}, this.props.inputHtml, { valueLink: this.props.valueLink, className: cx(this.props.inputHtml.className, "form-control"), }) ) } _onTimeChange(newTime) { console.log(`New Time ${newTime}`) } render() { return div({className: cx(sizeClassNames(this.props))}, div({className: formGroupCx(this.props)}, div({}, label(this.props) ), this._input(), errorList(this.props.errors), ), popup({ valueLink: this.props.valueLink, }) ) } }
let React = require("react") let cx = require("classnames") let popup = React.createFactory(require("./timepicker_popup")) let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js") let {div, input} = React.DOM export default class extends React.Component { static displayName = "Frig.friggingBootstrap.TimePicker" static defaultProps = Object.assign(require("../default_props.js")) _input() { return input(Object.assign({}, this.props.inputHtml, { valueLink: { value: this.props.valueLink.value, requestChange: this._onTimeChange, }, className: cx(this.props.inputHtml.className, "form-control"), }) ) } _onTimeChange(newTime) { console.log(`New Time ${newTime}`) } render() { return div({className: cx(sizeClassNames(this.props))}, div({className: formGroupCx(this.props)}, div({}, label(this.props) ), this._input(), errorList(this.props.errors), ), popup() ) } }
Fix template loading in Windows
<?php use Sabre\HTTP; if (!function_exists('dd')) { function dd() { var_dump(func_get_args()); die(); } } if (!function_exists('send_response')) { function send_response($response) { HTTP\Sapi::sendResponse($response); } } if (!function_exists('register_twig')) { function register_twig($views_path) { $directory = new RecursiveDirectoryIterator($views_path); $iterator = new RecursiveIteratorIterator($directory); $regex = new RegexIterator($iterator, '/^.+\.twig$/i', RecursiveRegexIterator::GET_MATCH); $tpl_files = []; foreach ($regex as $file) { $tpl_files[str_replace([$views_path . DIRECTORY_SEPARATOR, '.twig', DIRECTORY_SEPARATOR], ['', '', '.'], $file[0])] = file_get_contents($file[0]); } $loader = new Twig_Loader_Array($tpl_files); $twig = new Twig_Environment($loader); /** * Load Twig extensions */ $twig->addExtension(new Twig_Extensions_Extension_Text()); return $twig; } }
<?php use Sabre\HTTP; if (!function_exists('dd')) { function dd() { var_dump(func_get_args()); die(); } } if (!function_exists('send_response')) { function send_response($response) { HTTP\Sapi::sendResponse($response); } } if (!function_exists('register_twig')) { function register_twig($views_path) { $directory = new RecursiveDirectoryIterator($views_path); $iterator = new RecursiveIteratorIterator($directory); $regex = new RegexIterator($iterator, '/^.+\.twig$/i', RecursiveRegexIterator::GET_MATCH); $tpl_files = []; foreach ($regex as $file) { $tpl_files[str_replace([$views_path . '/', '.twig', '/'], ['', '', '.'], $file[0])] = file_get_contents($file[0]); } $loader = new Twig_Loader_Array($tpl_files); $twig = new Twig_Environment($loader); /** * Load Twig extensions */ $twig->addExtension(new Twig_Extensions_Extension_Text()); return $twig; } }
Fix for assertIn method not being present in Python 2.6. Undo prior erroneous commit (assertIn is missing, not assertIs).
from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message self.assertIs(type(time), datetime) if sys.version_info[0] == 2: # python2.x assert type(msgId) in (str, unicode) assert type(user) in (str, unicode) assert type(text) in (str, unicode) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main()
from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message assert type(time) is datetime if sys.version_info[0] == 2: # python2.x self.assertIn(type(msgId), (str, unicode)) self.assertIn(type(user), (str, unicode)) self.assertIn(type(text), (str, unicode)) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main()
Mark event constants with annotation
<?php /* * This file is part of the HWIOAuthBundle package. * * (c) Hardware.Info <opensource@hardware.info> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace HWI\Bundle\OAuthBundle; /** * @author Marek Štípek */ final class HWIOAuthEvents { /** * @Event("HWI\Bundle\OAuthBundle\Event\GetResponseUserEvent") */ const REGISTRATION_INITIALIZE = 'hwi_oauth.registration.initialize'; /** * @Event("HWI\Bundle\OAuthBundle\Event\FormEvent") */ const REGISTRATION_SUCCESS = 'hwi_oauth.registration.success'; /** * @Event("HWI\Bundle\OAuthBundle\Event\GetResponseUserEvent") */ const REGISTRATION_COMPLETED = 'hwi_oauth.registration.completed'; /** * @Event("HWI\Bundle\OAuthBundle\Event\GetResponseUserEvent") */ const CONNECT_INITIALIZE = 'hwi_oauth.connect.initialize'; /** * @Event("HWI\Bundle\OAuthBundle\Event\GetResponseUserEvent") */ const CONNECT_CONFIRMED = 'hwi_oauth.connect.confirmed'; /** * @Event("HWI\Bundle\OAuthBundle\Event\FilterUserResponseEvent") */ const CONNECT_COMPLETED = 'hwi_oauth.connect.completed'; }
<?php /* * This file is part of the HWIOAuthBundle package. * * (c) Hardware.Info <opensource@hardware.info> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace HWI\Bundle\OAuthBundle; /** * @author Marek Štípek */ final class HWIOAuthEvents { const REGISTRATION_INITIALIZE = 'hwi_oauth.registration.initialize'; const REGISTRATION_SUCCESS = 'hwi_oauth.registration.success'; const REGISTRATION_COMPLETED = 'hwi_oauth.registration.completed'; const CONNECT_INITIALIZE = 'hwi_oauth.connect.initialize'; const CONNECT_CONFIRMED = 'hwi_oauth.connect.confirmed'; const CONNECT_COMPLETED = 'hwi_oauth.connect.completed'; }
Revert "Set credentials file according to documentation" This reverts commit 0bf81f4fb9d34633bea1e88877d67a9a2caf554e. The point of this is to allow me to use a separate account to avoid corrupting my event stream. GitHub.connect() does the standard handling for those who are not me.
package org.kohsuke.github; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.junit.Before; import org.kohsuke.randname.RandomNameGenerator; import java.io.FileInputStream; import java.util.Properties; /** * @author Kohsuke Kawaguchi */ public abstract class AbstractGitHubApiTestBase extends Assert { protected GitHub gitHub; @Before public void setUp() throws Exception { Properties props = new Properties(); java.io.File f = new java.io.File(System.getProperty("user.home"), ".github.kohsuke2"); if (f.exists()) { FileInputStream in = new FileInputStream(f); try { props.load(in); gitHub = GitHub.connect(props.getProperty("login"),props.getProperty("oauth")); } finally { IOUtils.closeQuietly(in); } } else { gitHub = GitHub.connect(); } } protected static final RandomNameGenerator rnd = new RandomNameGenerator(); }
package org.kohsuke.github; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.junit.Before; import org.kohsuke.randname.RandomNameGenerator; import java.io.FileInputStream; import java.util.Properties; /** * @author Kohsuke Kawaguchi */ public abstract class AbstractGitHubApiTestBase extends Assert { protected GitHub gitHub; @Before public void setUp() throws Exception { Properties props = new Properties(); java.io.File f = new java.io.File(System.getProperty("user.home"), ".github"); if (f.exists()) { FileInputStream in = new FileInputStream(f); try { props.load(in); gitHub = GitHub.connect(props.getProperty("login"),props.getProperty("oauth")); } finally { IOUtils.closeQuietly(in); } } else { gitHub = GitHub.connect(); } } protected static final RandomNameGenerator rnd = new RandomNameGenerator(); }
Revert "Py 2.6 support is back" This reverts commit 463c1ab6a7f5a7909b967e0dfa0320a77e166b95.
from pyramid.interfaces import ( ISessionFactory, ) from .interfaces import ( IAuthService, IAuthSourceService, ) def int_or_none(x): return int(x) if x is not None else x def kw_from_settings(settings, from_prefix='authsanity.'): return { k.replace(from_prefix, ''): v for k, v in settings.items() if k.startswith(from_prefix) } def add_vary_callback(vary_by): def vary_add(request, response): vary = set(response.vary if response.vary is not None else []) vary |= set(vary_by) response.vary = list(vary) return vary_add def _find_services(request): sourcesvc = request.find_service(IAuthSourceService) authsvc = request.find_service(IAuthService) return (sourcesvc, authsvc) def _session_registered(request): registry = request.registry factory = registry.queryUtility(ISessionFactory) return (False if factory is None else True)
from pyramid.interfaces import ( ISessionFactory, ) from .interfaces import ( IAuthService, IAuthSourceService, ) def int_or_none(x): return int(x) if x is not None else x def kw_from_settings(settings, from_prefix='authsanity.'): return dict((k.replace(from_prefix, ''), v) for (k, v) in settings.items() if k.startswith(from_prefix)) def add_vary_callback(vary_by): def vary_add(request, response): vary = set(response.vary if response.vary is not None else []) vary |= set(vary_by) response.vary = list(vary) return vary_add def _find_services(request): sourcesvc = request.find_service(IAuthSourceService) authsvc = request.find_service(IAuthService) return (sourcesvc, authsvc) def _session_registered(request): registry = request.registry factory = registry.queryUtility(ISessionFactory) return (False if factory is None else True)