text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use events in connect middleware
var React = require('react'); var urllite = require('urllite'); var renderResponseToString = require('../renderResponseToString'); var connectMiddleware = function(Router) { return function(req, res, next) { // Get the part of the URL we care about. // TODO: Allow this to be mounted at a different base and strip that from pathname var parsed = urllite(req.url); var url = parsed.pathname + parsed.search + parsed.hash; var rreq = Router.dispatch(url) .on('error', function(err) { // The React router doesn't want to handle it. That's okay, let // something else. if (err.name === 'Unhandled') return next(); // Uh oh. A real error. return next(err); }) .on('end', function() { var contentType = rreq.contentType(); // Guess from contentType if not present res.statusCode = rres._notFound ? 404 : 200; res.setHeader('Content-Type', contentType); res.end(renderResponseToString(rreq)); }); }; }; module.exports = connectMiddleware;
var React = require('react'); var urllite = require('urllite'); var renderResponseToString = require('../renderResponseToString'); var connectMiddleware = function(Router) { return function(req, res, next) { // Get the part of the URL we care about. // TODO: Allow this to be mounted at a different base and strip that from pathname var parsed = urllite(req.url); var url = parsed.pathname + parsed.search + parsed.hash; Router.dispatch(url, function(err, rres) { if (err) { // The React router doesn't want to handle it. That's okay, let // something else. if (err.name === 'Unhandled') return next(); // Uh oh. A real error. return next(err); } var contentType = rres.contentType(); // Guess from contentType if not present res.statusCode = rres._notFound ? 404 : 200; res.setHeader('Content-Type', contentType); res.end(renderResponseToString(rres)); }); }; }; module.exports = connectMiddleware;
Support -a command line arguments For supporting and commandline arugment to pass to the binary there is a new '-a' option. Also my editor autoformats to gofmt so these files are cleaned up with the standarde format.
/* Fresh is a command line tool that builds and (re)starts your web application everytime you save a go or template file. If the web framework you are using supports the Fresh runner, it will show build errors on your browser. It currently works with Traffic (https://github.com/pilu/traffic), Martini (https://github.com/codegangsta/martini) and gocraft/web (https://github.com/gocraft/web). Fresh will watch for file events, and every time you create/modifiy/delete a file it will build and restart the application. If `go build` returns an error, it will logs it in the tmp folder. Traffic (https://github.com/pilu/traffic) already has a middleware that shows the content of that file if it is present. This middleware is automatically added if you run a Traffic web app in dev mode with Fresh. */ package main import ( "flag" "fmt" "os" "github.com/pilu/fresh/runner" ) func main() { configPath := flag.String("c", "", "config file path") flag.Parse() if *configPath != "" { if _, err := os.Stat(*configPath); err != nil { fmt.Printf("Can't find config file `%s`\n", *configPath) os.Exit(1) } else { os.Setenv("RUNNER_CONFIG_PATH", *configPath) } } runner.Start() }
/* Fresh is a command line tool that builds and (re)starts your web application everytime you save a go or template file. If the web framework you are using supports the Fresh runner, it will show build errors on your browser. It currently works with Traffic (https://github.com/pilu/traffic), Martini (https://github.com/codegangsta/martini) and gocraft/web (https://github.com/gocraft/web). Fresh will watch for file events, and every time you create/modifiy/delete a file it will build and restart the application. If `go build` returns an error, it will logs it in the tmp folder. Traffic (https://github.com/pilu/traffic) already has a middleware that shows the content of that file if it is present. This middleware is automatically added if you run a Traffic web app in dev mode with Fresh. */ package main import ( "flag" "fmt" "github.com/lateefj/fresh/runner" "os" ) func main() { configPath := flag.String("c", "", "config file path") flag.Parse() if *configPath != "" { if _, err := os.Stat(*configPath); err != nil { fmt.Printf("Can't find config file `%s`\n", *configPath) os.Exit(1) } else { os.Setenv("RUNNER_CONFIG_PATH", *configPath) } } runner.Start() }
Add an util funcion for mocking options
try: from urllib.parse import urlencode except ImportError: from urllib import urlencode import tornado.testing from tornado.options import options import celery import mock from flower.app import Flower from flower.urls import handlers from flower.events import Events from flower.urls import settings from flower import command # side effect - define options class AsyncHTTPTestCase(tornado.testing.AsyncHTTPTestCase): def get_app(self): capp = celery.Celery() events = Events(capp) app = Flower(capp=capp, events=events, options=options, handlers=handlers, **settings) app.delay = lambda method, *args, **kwargs: method(*args, **kwargs) return app def get(self, url, **kwargs): return self.fetch(url, **kwargs) def post(self, url, **kwargs): if 'body' in kwargs and isinstance(kwargs['body'], dict): kwargs['body'] = urlencode(kwargs['body']) return self.fetch(url, method='POST', **kwargs) def mock_option(self, name, value): return mock.patch.object(options.mockable(), name, value)
try: from urllib.parse import urlencode except ImportError: from urllib import urlencode import tornado.testing import tornado.options import celery from flower.app import Flower from flower.urls import handlers from flower.events import Events from flower.urls import settings from flower import command # side effect - define options class AsyncHTTPTestCase(tornado.testing.AsyncHTTPTestCase): def get_app(self): capp = celery.Celery() events = Events(capp) app = Flower(capp=capp, events=events, options=tornado.options.options, handlers=handlers, **settings) app.delay = lambda method, *args, **kwargs: method(*args, **kwargs) return app def get(self, url, **kwargs): return self.fetch(url, **kwargs) def post(self, url, **kwargs): if 'body' in kwargs and isinstance(kwargs['body'], dict): kwargs['body'] = urlencode(kwargs['body']) return self.fetch(url, method='POST', **kwargs)
Fix quick union functions issue Missing counter Find function should return position of element Decrement counter in union
#!/usr/bin/env python # -*- coding: utf-8 -*- class WeightedQuickUnion(object): def __init__(self, data=None): self.id = data self.weight = [1] * len(data) self.count = len(data) def count(self): return self.count def find(self, val): p = val while self.id[p] != p: p = self.id[p] return p def union(self, p, q): p_root = self.find(p) q_root = self.find(q) if p_root == q_root: return self.id[q_root] = p_root self.count -= 1 def is_connected(self, p, q): return self.find(p) == self.find(q)
#!/usr/bin/env python # -*- coding: utf-8 -*- class WeightedQuickUnion(object): def __init__(self): self.id = [] self.weight = [] def find(self, val): p = val while self.id[p] != p: p = self.id[p] return self.id[p] def union(self, p, q): p_root = self.find(p) q_root = self.find(q) if p_root == q_root: return self.id[q_root] = p_root def is_connected(self, p, q): return self.find(p) == self.find(q)
Make pushover message more generic
<?php namespace ScottRobertson\Scrutiny\Reporter; class Pushover extends Base { private $token; private $user; public $pushover; public function __construct($token, $user, array $subscribe = array('down', 'recovery')) { // Subscribe to events $this->subscribe($subscribe); $this->token = $token; $this->user = $user; $this->pushover = new \Scottymeuk\Pushover\Client( array( 'token' => $this->token ) ); } public function report($service) { $this->pushover->title = $service->getMessageFromEvent(); $this->pushover->message = $service->getName() . ' returned ' . $service->getData('code'); $this->pushover->timestamp = $service->getTime(); $this->pushover->url = $service->getData('url'); return $this->pushover->push($this->user); } }
<?php namespace ScottRobertson\Scrutiny\Reporter; class Pushover extends Base { private $token; private $user; public $pushover; public function __construct($token, $user, array $subscribe = array('down', 'recovery')) { // Subscribe to events $this->subscribe($subscribe); $this->token = $token; $this->user = $user; $this->pushover = new \Scottymeuk\Pushover\Client( array( 'token' => $this->token ) ); } public function report($service) { $this->pushover->title = $service->getMessageFromEvent(); $this->pushover->message = $service->getData('url') . ' returned ' . $service->getData('code'); $this->pushover->timestamp = $service->getTime(); $this->pushover->url = $service->getData('url'); return $this->pushover->push($this->user); } }
Disable the YUICompressor and closure compiler tests They're annoying because the fail on Travis half of the time.
var vows = require('vows'), assert = require('assert'), AssetGraph = require('../lib/AssetGraph'); vows.describe('transforms.compressJavaScript').addBatch(function () { var test = {}; // The YUICompressor and ClosureCompiler tests fail intermittently on Travis [undefined, 'uglifyJs'/*, 'yuicompressor', 'closurecompiler'*/].forEach(function (compressorName) { test[String(compressorName)] = { topic: function () { var assetGraph = new AssetGraph(); assetGraph.addAsset(new AssetGraph.JavaScript({text: "var foo = 123;"})); assetGraph.compressJavaScript({type: 'JavaScript'}, compressorName).run(this.callback); }, 'should yield a compressed JavaScript': function (assetGraph) { var javaScripts = assetGraph.findAssets({type: 'JavaScript'}); assert.equal(javaScripts.length, 1); assert.matches(javaScripts[0].text, /^var foo=123;?\n?$/); } }; }); return test; }())['export'](module);
var vows = require('vows'), assert = require('assert'), AssetGraph = require('../lib/AssetGraph'); vows.describe('transforms.compressJavaScript').addBatch(function () { var test = {}; [undefined, 'uglifyJs', 'yuicompressor', 'closurecompiler'].forEach(function (compressorName) { test[String(compressorName)] = { topic: function () { var assetGraph = new AssetGraph(); assetGraph.addAsset(new AssetGraph.JavaScript({text: "var foo = 123;"})); assetGraph.compressJavaScript({type: 'JavaScript'}, compressorName).run(this.callback); }, 'should yield a compressed JavaScript': function (assetGraph) { var javaScripts = assetGraph.findAssets({type: 'JavaScript'}); assert.equal(javaScripts.length, 1); assert.matches(javaScripts[0].text, /^var foo=123;?\n?$/); } }; }); return test; }())['export'](module);
Add a TODO for diamondash metric snapshot request auth in diamondash proxy view
from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods from django.views.decorators.csrf import csrf_exempt from go.dashboard import client @login_required @csrf_exempt @require_http_methods(['GET']) def diamondash_api_proxy(request): """ Proxies client snapshot requests to diamondash. NOTE: This proxy is a fallback for dev purposes only. A more sensible proxying solution should be used in production (eg. haproxy). """ api = client.get_diamondash_api() _, url = request.path.split('/diamondash/api', 1) response = api.raw_request(request.method, url, content=request.body) # TODO for the case of snapshot requests, ensure the widgets requested are # allowed for the given account return HttpResponse( response['content'], status=response['code'], content_type='application/json')
from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods from django.views.decorators.csrf import csrf_exempt from go.dashboard import client @login_required @csrf_exempt @require_http_methods(['GET']) def diamondash_api_proxy(request): """ Proxies client snapshot requests to diamondash. NOTE: This proxy is a fallback for dev purposes only. A more sensible proxying solution should be used in production (eg. haproxy). """ api = client.get_diamondash_api() _, url = request.path.split('/diamondash/api', 1) response = api.raw_request(request.method, url, content=request.body) return HttpResponse( response['content'], status=response['code'], content_type='application/json')
Test line end carriages redo.
import moment from 'moment'; import { Paginator } from '@/lib/pagination'; import template from './outdated-queries.html'; function OutdatedQueriesCtrl($scope, $http, $timeout) { $scope.autoUpdate = true; this.queries = new Paginator([], { itemsPerPage: 50 }); const refresh = () => { if ($scope.autoUpdate) { $scope.refresh_time = moment().add(1, 'minutes'); $http.get('/api/admin/queries/outdated').success((data) => { this.queries.updateRows(data.queries); $scope.updatedAt = data.updated_at * 1000.0; }); } const timer = $timeout(refresh, 59 * 1000); $scope.$on('$destroy', () => { if (timer) { $timeout.cancel(timer); } }); }; refresh(); } export default function init(ngModule) { ngModule.component('outdatedQueriesPage', { template, controller: OutdatedQueriesCtrl, }); return { '/admin/queries/outdated': { template: '<outdated-queries-page></outdated-queries-page>', title: 'Outdated Queries', }, }; }
import moment from 'moment'; import { Paginator } from '@/lib/pagination'; import template from './outdated-queries.html'; function OutdatedQueriesCtrl($scope, $http, $timeout) { $scope.autoUpdate = true; this.queries = new Paginator([], { itemsPerPage: 50 }); const refresh = () => { if ($scope.autoUpdate) { $scope.refresh_time = moment().add(1, 'minutes'); $http.get('/api/admin/queries/outdated').success((data) => { this.queries.updateRows(data.queries); $scope.updatedAt = data.updated_at * 1000.0; }); } const timer = $timeout(refresh, 59 * 1000); $scope.$on('$destroy', () => { if (timer) { $timeout.cancel(timer); } }); }; refresh(); } export default function init(ngModule) { ngModule.component('outdatedQueriesPage', { template, controller: OutdatedQueriesCtrl, }); return { '/admin/queries/outdated': { template: '<outdated-queries-page></outdated-queries-page>', title: 'Outdated Queries', }, }; }
Add nullable to some fields
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddB3ServerTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { \Schema::create('b3servers', function (Blueprint $table){ $table->increments('id'); $table->string('name'); $table->string('rcon')->nullable(); $table->string('identifier'); $table->string('host')->nullable(); $table->integer('port')->nullable(); $table->json('dbSettings'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { \Schema::dropIfExists('b3servers'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddB3ServerTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { \Schema::create('b3servers', function (Blueprint $table){ $table->increments('id'); $table->string('name'); $table->string('rcon'); $table->string('identifier'); $table->string('host'); $table->integer('port'); $table->json('dbSettings'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { \Schema::dropIfExists('b3servers'); } }
Fix broken alembic revision generation
"""empty message Revision ID: 2507366cb6f2 Revises: 2a31d97fa618 Create Date: 2013-04-30 00:11:14.194453 """ # revision identifiers, used by Alembic. revision = '2507366cb6f2' down_revision = '2a31d97fa618' from os.path import abspath, dirname, join import sys from alembic import op import sqlalchemy as sa parentdir = dirname(dirname(dirname(abspath(__file__)))) sys.path.insert(0,parentdir) from models.person import Person from utils.nlp.utils.translit import translit person_t = sa.sql.table( 'person', sa.sql.column('id', sa.Integer), sa.sql.column('name', sa.Unicode(20)), sa.sql.column('name_en', sa.String(80)) ) def upgrade(): people = Person.query.all() for person in people: name_en = translit(person.name, 'ko', 'en', 'name') op.execute(person_t.update().\ where(person_t.c.id == person.id).\ values({'name_en': op.inline_literal(name_en)}) ) def downgrade(): op.execute(person_t.update().\ values({'name_en': op.inline_literal('')}) )
"""empty message Revision ID: 2507366cb6f2 Revises: 2a31d97fa618 Create Date: 2013-04-30 00:11:14.194453 """ # revision identifiers, used by Alembic. revision = '2507366cb6f2' down_revision = '2a31d97fa618' from alembic import op import sqlalchemy as sa from models.person import Person from utils.nlp.utils.translit import translit person_t = sa.sql.table( 'person', sa.sql.column('id', sa.Integer), sa.sql.column('name', sa.Unicode(20)), sa.sql.column('name_en', sa.String(80)) ) def upgrade(): people = Person.query.all() for person in people: name_en = translit(person.name, 'ko', 'en', 'name') op.execute(person_t.update().\ where(person_t.c.id == person.id).\ values({'name_en': op.inline_literal(name_en)}) ) def downgrade(): op.execute(person_t.update().\ values({'name_en': op.inline_literal('')}) )
Add pointerLock() custom element support. Increase readability.
import THREE from 'three'; export default function pointerLock( controls, element = document.body ) { const hasPointerLock = ( 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document ); if ( !hasPointerLock ) { return; } const dispatcher = new THREE.EventDispatcher(); function onPointerLockChange() { controls.enabled = ( element === document.pointerLockElement || element === document.mozPointerLockElement || element === document.webkitPointerLockElement ); dispatcher.dispatchEvent({ type: 'change', enabled: controls.enabled }); } function onPointerLockError() { dispatcher.dispatchEvent({ type: 'error' }); } document.addEventListener( 'pointerlockchange', onPointerLockChange ); document.addEventListener( 'mozpointerlockchange', onPointerLockChange ); document.addEventListener( 'webkitpointerlockchange', onPointerLockChange ); document.addEventListener( 'pointerlockerror', onPointerLockError ); document.addEventListener( 'mozpointerlockerror', onPointerLockError ); document.addEventListener( 'webkitpointerlockerror', onPointerLockError ); element.requestPointerLock = ( element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock ); document.addEventListener( 'click', () => element.requestPointerLock() ); return dispatcher; }
import THREE from 'three'; export default function pointerLock( controls ) { const hasPointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; if ( !hasPointerLock ) { return; } const element = document.body; const dispatcher = new THREE.EventDispatcher(); function onPointerLockChange() { if ( document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element ) { controls.enabled = true; } else { controls.enabled = false; } dispatcher.dispatchEvent({ type: 'change', enabled: controls.enabled }); } function onPointerLockError() { dispatcher.dispatchEvent({ type: 'error' }); } document.addEventListener( 'pointerlockchange', onPointerLockChange ); document.addEventListener( 'mozpointerlockchange', onPointerLockChange ); document.addEventListener( 'webkitpointerlockchange', onPointerLockChange ); document.addEventListener( 'pointerlockerror', onPointerLockError ); document.addEventListener( 'mozpointerlockerror', onPointerLockError ); document.addEventListener( 'webkitpointerlockerror', onPointerLockError ); element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; document.addEventListener( 'click', () => element.requestPointerLock() ); return dispatcher; }
Add second jasmine spec for bootstrap toggle spec
describe('bootstrap toggle', function() { var header; beforeEach(function() { setFixtures('<li class="dropdown" id="menuOrgs">'+ '<a class="dropdown-toggle" href="#" data-toggle ="dropdown">Organisations</a>' + '<ul class="dropdown-menu">' + ' <li><a href="/organization_reports/without_users">Without Users</a></li>' + '</ul>' + '</li>'); link = $('a')[0]; }); describe('when clicking on the parent', function() { it('pops up a list', function() { link.click(); expect($('li#menuOrgs')).toHaveClass('open'); link.click(); expect($('li#menuOrgs')).not.toHaveClass('open'); }); }); });
describe('bootstrap toggle', function() { var header; beforeEach(function() { setFixtures('<li class="dropdown" id="menuOrgs">'+ '<a class="dropdown-toggle" href="#">Organisations</a>' + '<ul class="dropdown-menu">' + ' <li><a href="/organization_reports/without_users">Without Users</a></li>' + '</ul>' + '</li>'); link = $('a')[0]; }); describe('when clicking on the parent', function() { it('pops up a list', function() { link.click(); expect($('li#menuOrgs').first()).toHaveClass('open'); }); }); });
Make length optional. Set up defaults.
import string import random import argparse def passgen(length=12): """Generate a strong password with *length* characters""" pool = string.ascii_uppercase + string.ascii_lowercase + string.digits return ''.join(random.SystemRandom().choice(pool) for _ in range(length)) def main(): parser = argparse.ArgumentParser("Generate strong random password.") parser.add_argument("-l", "--length", help="the number of characters to generate", type=int, default=12) parser.add_argument("-n", "--number", help="how many passwords to generate", type=int, default=10) args = parser.parse_args() for _ in range(args.number): print passgen(args.length)
import string import random import argparse def passgen(length=8): """Generate a strong password with *length* characters""" pool = string.ascii_uppercase + string.ascii_lowercase + string.digits return ''.join(random.SystemRandom().choice(pool) for _ in range(length)) def main(): parser = argparse.ArgumentParser("Generate strong random password.") parser.add_argument("length", help="the number of characters to generate", type=int) parser.add_argument("-n", "--number", help="how many passwords to generate", type=int) args = parser.parse_args() for _ in range(args.number): print passgen(args.length)
Change variable name defining path to ChromeDriver executable 1. Why is this change necessary? Current environment variable in ChromeDriver.php uses '.', whilst valid according to the specification, this will not work using a bash shell (probably the most commonly used) 2. How does it address the issue? '.' replaced with '_'. This is usable in bash (including cygwin) Original code still there, only attempts new variable if original does not exist 3. What are the side effects? None, previous name will still work, new name only used if original name does not exist
<?php // Copyright 2004-present Facebook. 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. namespace Facebook\WebDriver\Chrome; use Facebook\WebDriver\Remote\Service\DriverService; class ChromeDriverService extends DriverService { /** * The environment variable storing the path to the chrome driver executable. * @deprecated Use ChromeDriverService::CHROME_DRIVER_EXECUTABLE */ const CHROME_DRIVER_EXE_PROPERTY = 'webdriver.chrome.driver'; // The environment variable storing the path to the chrome driver executable const CHROME_DRIVER_EXECUTABLE = 'WEBDRIVER_CHROME_DRIVER'; /** * @return static */ public static function createDefaultService() { $exe = getenv(self::CHROME_DRIVER_EXECUTABLE) ?: getenv(self::CHROME_DRIVER_EXE_PROPERTY); $port = 9515; // TODO: Get another port if the default port is used. $args = ['--port=' . $port]; return new static($exe, $port, $args); } }
<?php // Copyright 2004-present Facebook. 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. namespace Facebook\WebDriver\Chrome; use Facebook\WebDriver\Remote\Service\DriverService; class ChromeDriverService extends DriverService { // The environment variable storing the path to the chrome driver executable. const CHROME_DRIVER_EXE_PROPERTY = 'webdriver.chrome.driver'; /** * @return static */ public static function createDefaultService() { $exe = getenv(self::CHROME_DRIVER_EXE_PROPERTY); $port = 9515; // TODO: Get another port if the default port is used. $args = ["--port=$port"]; $service = new static($exe, $port, $args); return $service; } }
Update SelectionButtons to new interface Version 2.0.0 of the govuk_frontend_toolkit deprecated the old interface to SelectionButtons. This now uses the new style.
$(document).ready(function() { $('.print-link a').attr('target', '_blank'); var $searchFocus = $('.js-search-focus'); $searchFocus.each(function(i, el){ if($(el).val() !== ''){ $(el).addClass('focus'); } }); $searchFocus.on('focus', function(e){ $(e.target).addClass('focus'); }); $searchFocus.on('blur', function(e){ if($(e.target).val() === ''){ $(e.target).removeClass('focus'); } }); if (window.GOVUK) { if (GOVUK.userSatisfaction){ var currentURL = window.location.pathname; function stringContains(str, substr) { return str.indexOf(substr) > -1; } // We don't want the satisfaction survey appearing for users who // have completed a transaction as they may complete the survey with // the department's transaction in mind as opposed to the GOV.UK content. if (!stringContains(currentURL, "/done") && !stringContains(currentURL, "/transaction-finished") && !stringContains(currentURL, "/driving-transaction-finished")) { GOVUK.userSatisfaction.randomlyShowSurveyBar(); } } } // for radio buttons and checkboxes var $buttons = $("label.selectable input[type='radio'], label.selectable input[type='checkbox']"); new GOVUK.SelectionButtons($buttons); });
$(document).ready(function() { $('.print-link a').attr('target', '_blank'); var $searchFocus = $('.js-search-focus'); $searchFocus.each(function(i, el){ if($(el).val() !== ''){ $(el).addClass('focus'); } }); $searchFocus.on('focus', function(e){ $(e.target).addClass('focus'); }); $searchFocus.on('blur', function(e){ if($(e.target).val() === ''){ $(e.target).removeClass('focus'); } }); if (window.GOVUK) { if (GOVUK.userSatisfaction){ var currentURL = window.location.pathname; function stringContains(str, substr) { return str.indexOf(substr) > -1; } // We don't want the satisfaction survey appearing for users who // have completed a transaction as they may complete the survey with // the department's transaction in mind as opposed to the GOV.UK content. if (!stringContains(currentURL, "/done") && !stringContains(currentURL, "/transaction-finished") && !stringContains(currentURL, "/driving-transaction-finished")) { GOVUK.userSatisfaction.randomlyShowSurveyBar(); } } } // for radio buttons and checkboxes var $buttons = $("label.selectable input[type='radio'], label.selectable input[type='checkbox']"); GOVUK.selectionButtons($buttons); });
Clean up include dir code
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Gregory Oschwald # Copyright (c) 2013 Gregory Oschwald # # License: MIT # """This module exports the Perl plugin class.""" import shlex from SublimeLinter.lint import Linter, util class Perl(Linter): """Provides an interface to perl -c.""" syntax = ('modernperl', 'perl') executable = 'perl' regex = r'(?P<message>.+?) at .+? line (?P<line>\d+)(, near "(?P<near>.+?)")?' error_stream = util.STREAM_STDERR def cmd(self): """ Return the command line to execute. Overridden so we can add include paths based on the 'include_dirs' settings. """ command = [self.executable_path, '-c'] include_dirs = self.get_view_settings().get('include_dirs', []) for e in include_dirs: command.append('-I') command.append(shlex.quote(e)) return command
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Gregory Oschwald # Copyright (c) 2013 Gregory Oschwald # # License: MIT # """This module exports the Perl plugin class.""" import shlex from SublimeLinter.lint import Linter, util class Perl(Linter): """Provides an interface to perl -c.""" syntax = ('modernperl', 'perl') executable = 'perl' base_cmd = ('perl -c') regex = r'(?P<message>.+?) at .+? line (?P<line>\d+)(, near "(?P<near>.+?)")?' error_stream = util.STREAM_STDERR def cmd(self): """ Return the command line to execute. Overridden so we can add include paths based on the 'include_dirs' settings. """ full_cmd = self.base_cmd settings = self.get_view_settings() include_dirs = settings.get('include_dirs', []) if include_dirs: full_cmd += ' ' . join([' -I ' + shlex.quote(include) for include in include_dirs]) return full_cmd
Add format parameter to strf functions
import time import datetime def get_current_utc(time_format="%Y-%m-%d %H:%M:%S"): """ @return a string representation of the current time in UTC. """ return time.strftime(time_format, time.gmtime()) def today_strf(format="%d/%m/%Y"): t = datetime.date.today() return t.strftime(format) def tomorrow_strf(format="%d/%m/%Y"): t = datetime.date.today() + datetime.timedelta(days=1) return t.strftime(format) def yesterday_strf(format="%d/%m/%Y"): t = datetime.date.today() - datetime.timedelta(days=1) return t.strftime(format) def seconds_to_milliseconds_timestamp(seconds_timestamp): return int(round(seconds_timestamp * 1000)) def current_milliseconds_timestamp(): return seconds_to_milliseconds_timestamp(time.time()) def datetime_to_milliseconds_timestamp(datetime_obj): seconds_timestamp = time.mktime(datetime_obj.timetuple()) return seconds_to_milliseconds_timestamp(seconds_timestamp)
import time import datetime def get_current_utc(time_format="%Y-%m-%d %H:%M:%S"): """ @return a string representation of the current time in UTC. """ return time.strftime(time_format, time.gmtime()) def today_strf(): t = datetime.date.today() return t.strftime("%d/%m/%Y") def tomorrow_strf(): t = datetime.date.today() + datetime.timedelta(days=1) return t.strftime("%d/%m/%Y") def yesterday_strf(): t = datetime.date.today() - datetime.timedelta(days=1) return t.strftime("%d/%m/%Y") def seconds_to_milliseconds_timestamp(seconds_timestamp): return int(round(seconds_timestamp * 1000)) def current_milliseconds_timestamp(): return seconds_to_milliseconds_timestamp(time.time()) def datetime_to_milliseconds_timestamp(datetime_obj): seconds_timestamp = time.mktime(datetime_obj.timetuple()) return seconds_to_milliseconds_timestamp(seconds_timestamp)
Remove http_server from nodeca context.
"use strict"; // stdlib var Fs = require('fs'); // nodeca var NLib = require('nlib'); // 3rd-party var StaticLulz = require('static-lulz'); var FsTools = NLib.Vendor.FsTools; var Async = NLib.Vendor.Async; module.exports = NLib.Application.create({ root: __dirname, name: 'nodeca.core', bootstrap: function (nodeca, callback) { // empty bootstrap... for now.. callback(); } }); global.nodeca.hooks.init.after('bundles', function (next) { nodeca.runtime.assets_server = new StaticLulz(); FsTools.walk(nodeca.runtime.assets_path, function (file, stats, next_file) { // Fill in Static lulz with files and data Async.waterfall([ Async.apply(Fs.readFile, file), function (buffer, callback) { var rel_path = file.replace(nodeca.runtime.assets_path, ''); nodeca.runtime.assets_server.add(rel_path, buffer); callback(); } ], next_file); }, next); }); global.nodeca.hooks.init.after('initialization', function (next) { var http_server = connect.createServer(); next(); }); //////////////////////////////////////////////////////////////////////////////// // vim:ts=2:sw=2 ////////////////////////////////////////////////////////////////////////////////
"use strict"; // stdlib var Fs = require('fs'); // nodeca var NLib = require('nlib'); // 3rd-party var StaticLulz = require('static-lulz'); var FsTools = NLib.Vendor.FsTools; var Async = NLib.Vendor.Async; module.exports = NLib.Application.create({ root: __dirname, name: 'nodeca.core', bootstrap: function (nodeca, callback) { // empty bootstrap... for now.. callback(); } }); global.nodeca.hooks.init.after('bundles', function (next) { nodeca.runtime.assets_server = new StaticLulz(); FsTools.walk(nodeca.runtime.assets_path, function (file, stats, next_file) { // Fill in Static lulz with files and data Async.waterfall([ Async.apply(Fs.readFile, file), function (buffer, callback) { var rel_path = file.replace(nodeca.runtime.assets_path, ''); nodeca.runtime.assets_server.add(rel_path, buffer); callback(); } ], next_file); }, next); }); global.nodeca.hooks.init.after('initialization', function (next) { nodeca.runtime.http_server = connect.createServer(); next(); }); //////////////////////////////////////////////////////////////////////////////// // vim:ts=2:sw=2 ////////////////////////////////////////////////////////////////////////////////
TST: Use matplotlib image_comparison to actually compare plot output
import os import unittest from matplotlib.pyplot import Artist, savefig from matplotlib.testing.decorators import image_comparison from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries # If set to True, generate images rather than perform tests (all tests will pass!) GENERATE_BASELINE = False BASELINE_DIR = os.path.join(os.path.dirname(__file__), 'baseline_images', 'test_plotting') def save_baseline_image(filename): """ save a baseline image """ savefig(os.path.join(BASELINE_DIR, filename)) @image_comparison(baseline_images=['poly_plot'], extensions=['png']) def test_poly_plot(): """ Test plotting a simple series of polygons """ t1 = Polygon([(0, 0), (1, 0), (1, 1)]) t2 = Polygon([(1, 0), (2, 1), (2, 1)]) polys = GeoSeries([t1, t2]) ax = polys.plot() assert isinstance(ax, Artist) if GENERATE_BASELINE: save_baseline_image('poly_plot.png') if __name__ == '__main__': import nose nose.runmodule(argv=['-s', '--with-doctest'])
from contextlib import contextmanager import os import tempfile import unittest from matplotlib.pyplot import Artist, savefig from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries @contextmanager def get_tempfile(): f, path = tempfile.mkstemp() try: yield path finally: try: os.remove(path) except: pass class TestSeriesPlot(unittest.TestCase): def setUp(self): self.t1 = Polygon([(0, 0), (1, 0), (1, 1)]) self.t2 = Polygon([(1, 0), (2, 1), (2, 1)]) self.polys = GeoSeries([self.t1, self.t2]) def test_poly_plot(self): """ Test plotting a simple series of polygons """ ax = self.polys.plot() self.assertIsInstance(ax, Artist) with get_tempfile() as file: savefig(file) if __name__ == '__main__': unittest.main()
MNT: Add StatusBase to top-level API.
import logging logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) from . import * # Signals from .signal import (Signal, EpicsSignal, EpicsSignalRO) # Positioners from .positioner import Positioner from .epics_motor import EpicsMotor from .pv_positioner import (PVPositioner, PVPositionerPC) from .pseudopos import (PseudoPositioner, PseudoSingle) # Devices from .scaler import EpicsScaler from .device import (Device, Component, DynamicDeviceComponent) from .ophydobj import StatusBase from .mca import EpicsMCA, EpicsDXP # Areadetector-related from .areadetector import * from ._version import get_versions from .commands import (mov, movr, set_pos, wh_pos, set_lm, log_pos, log_pos_diff, log_pos_mov) __version__ = get_versions()['version'] del get_versions
import logging logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) from . import * # Signals from .signal import (Signal, EpicsSignal, EpicsSignalRO) # Positioners from .positioner import Positioner from .epics_motor import EpicsMotor from .pv_positioner import (PVPositioner, PVPositionerPC) from .pseudopos import (PseudoPositioner, PseudoSingle) # Devices from .scaler import EpicsScaler from .device import (Device, Component, DynamicDeviceComponent) from .mca import EpicsMCA, EpicsDXP # Areadetector-related from .areadetector import * from ._version import get_versions from .commands import (mov, movr, set_pos, wh_pos, set_lm, log_pos, log_pos_diff, log_pos_mov) __version__ = get_versions()['version'] del get_versions
Add dynamic prefix for windows/mac shortcuts
import { saveAs } from 'file-saver'; import codemirror from 'codemirror'; import isEqual from 'lodash.isequal'; const mac = isEqual(codemirror.keyMap.default, codemirror.keyMap.macDefault); const pre = mac ? 'Cmd-' : 'Ctrl-'; export const Tags = { STRONG: '**', ITALIC: '_', }; function escapeRegExp(string) { return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'); } export function addOrRemoveTag(tag, selection) { const regex = new RegExp(`^${escapeRegExp(tag)}([^]+?)${escapeRegExp(tag)}$`); const matches = selection.match(regex, 'gi'); if (null !== matches) { return matches[1]; } return `${tag}${selection}${tag}`; } const extraKeys = {}; extraKeys[`${pre}Z`] = (cm) => { cm.undo(); }; extraKeys[`${pre}B`] = (cm) => { cm.replaceSelection(addOrRemoveTag(Tags.STRONG, cm.getSelection()), 'around'); }; extraKeys[`${pre}I`] = (cm) => { cm.replaceSelection(addOrRemoveTag(Tags.ITALIC, cm.getSelection()), 'around'); }; extraKeys[`${pre}S`] = (cm) => { saveAs(new Blob([cm.getValue()], { type: 'text/plain' }), 'monod.md'); }; export default extraKeys;
import { saveAs } from 'file-saver'; export const Tags = { STRONG: '**', ITALIC: '_', }; function escapeRegExp(string) { return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'); } export function addOrRemoveTag(tag, selection) { const regex = new RegExp(`^${escapeRegExp(tag)}([^]+?)${escapeRegExp(tag)}$`); const matches = selection.match(regex, 'gi'); if (null !== matches) { return matches[1]; } return `${tag}${selection}${tag}`; } const extraKeys = { 'Cmd-Z': (cm) => { cm.undo(); }, 'Cmd-B': (cm) => { cm.replaceSelection(addOrRemoveTag(Tags.STRONG, cm.getSelection()), 'around'); }, 'Cmd-I': (cm) => { cm.replaceSelection(addOrRemoveTag(Tags.ITALIC, cm.getSelection()), 'around'); }, 'Cmd-S': (cm) => { saveAs(new Blob([cm.getValue()], { type: 'text/plain' }), 'monod.md'); }, }; export default extraKeys;
Fix the name of the protected field that holds connection parameters. This has been recently changed in Predis (sorry for that), we won't modify the names of public or protected fields anymore until v0.8.
<?php /* * This file is part of the SncRedisBundle package. * * (c) Henrik Westphal <henrik.westphal@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Snc\RedisBundle\Client\Predis\Network; use Predis\Commands\ICommand; use Predis\ResponseError; use Predis\Network\StreamConnection; use Snc\RedisBundle\Logger\RedisLogger; /** * LoggingStreamConnection */ class LoggingStreamConnection extends StreamConnection { /** * @var RedisLogger */ protected $logger; /** * Sets the logger * * @param RedisLogger $logger A RedisLogger instance */ public function setLogger(RedisLogger $logger = null) { $this->logger = $logger; } /** * {@inheritdoc} */ public function executeCommand(ICommand $command) { $startTime = microtime(true); $result = parent::executeCommand($command); $duration = (microtime(true) - $startTime) * 1000; if (null !== $this->logger) { $error = $result instanceof ResponseError ? (string) $result : false; $this->logger->logCommand((string) $command, $duration, $this->parameters->alias, $error); } return $result; } }
<?php /* * This file is part of the SncRedisBundle package. * * (c) Henrik Westphal <henrik.westphal@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Snc\RedisBundle\Client\Predis\Network; use Predis\Commands\ICommand; use Predis\ResponseError; use Predis\Network\StreamConnection; use Snc\RedisBundle\Logger\RedisLogger; /** * LoggingStreamConnection */ class LoggingStreamConnection extends StreamConnection { /** * @var RedisLogger */ protected $logger; /** * Sets the logger * * @param RedisLogger $logger A RedisLogger instance */ public function setLogger(RedisLogger $logger = null) { $this->logger = $logger; } /** * {@inheritdoc} */ public function executeCommand(ICommand $command) { $startTime = microtime(true); $result = parent::executeCommand($command); $duration = (microtime(true) - $startTime) * 1000; if (null !== $this->logger) { $error = $result instanceof ResponseError ? (string) $result : false; $this->logger->logCommand((string) $command, $duration, $this->_params->alias, $error); } return $result; } }
feat: Change to json:api content type
const express = require('express'); const HTTPStatus = require('http-status-codes'); const scraper = require('./app/routes/scraper'); const handleErrorResponse = require('./app/errorResponse'); const app = express(); // This middleware will be executed for every request to the app // The api produces application/json only app.use((req, res, next) => { res.header('Content-Type', 'application/vnd.api+json'); res.header('Content-Language', 'en'); next(); }); app.use('/', scraper); // Final catch any route middleware used to raise 404 app.get('*', (req, res, next) => { const err = new Error(); err.statusCode = HTTPStatus.NOT_FOUND; next(err); }); // Error response handler app.use(handleErrorResponse); app.listen(3000, () => { console.log('Junkan server is running on port 3000!'); }); module.exports = app;
const express = require('express'); const HTTPStatus = require('http-status-codes'); const scraper = require('./app/routes/scraper'); const handleErrorResponse = require('./app/errorResponse'); const app = express(); // This middleware will be executed for every request to the app // The api produces application/json only app.use((req, res, next) => { res.header('Content-Type', 'application/json'); res.header('Content-Language', 'en'); next(); }); app.use('/', scraper); // Final catch any route middleware used to raise 404 app.get('*', (req, res, next) => { const err = new Error(); err.statusCode = HTTPStatus.NOT_FOUND; next(err); }); // Error response handler app.use(handleErrorResponse); app.listen(3000, () => { console.log('Junkan server is running on port 3000!'); }); module.exports = app;
Add classical_transport to init file
# 'physics' is a tentative name for this subpackage. Another # possibility is 'plasma'. The organization is to be decided by v0.1. from .parameters import Alfven_speed, ion_sound_speed, thermal_speed, kappa_thermal_speed, gyrofrequency, gyroradius, plasma_frequency, Debye_length, Debye_number, inertial_length, magnetic_pressure, magnetic_energy_density, upper_hybrid_frequency, lower_hybrid_frequency from .quantum import deBroglie_wavelength, thermal_deBroglie_wavelength, Fermi_energy, Thomas_Fermi_length from .relativity import Lorentz_factor from .transport import Coulomb_logarithm, classical_transport from .distribution import Maxwellian_1D, Maxwellian_velocity_3D, Maxwellian_speed_1D, Maxwellian_speed_3D,kappa_velocity_3D, kappa_velocity_1D from .dielectric import cold_plasma_permittivity_LRP, cold_plasma_permittivity_SDP
# 'physics' is a tentative name for this subpackage. Another # possibility is 'plasma'. The organization is to be decided by v0.1. from .parameters import Alfven_speed, ion_sound_speed, thermal_speed, kappa_thermal_speed, gyrofrequency, gyroradius, plasma_frequency, Debye_length, Debye_number, inertial_length, magnetic_pressure, magnetic_energy_density, upper_hybrid_frequency, lower_hybrid_frequency from .quantum import deBroglie_wavelength, thermal_deBroglie_wavelength, Fermi_energy, Thomas_Fermi_length from .relativity import Lorentz_factor from .transport import Coulomb_logarithm from .distribution import Maxwellian_1D, Maxwellian_velocity_3D, Maxwellian_speed_1D, Maxwellian_speed_3D,kappa_velocity_3D, kappa_velocity_1D from .dielectric import cold_plasma_permittivity_LRP, cold_plasma_permittivity_SDP
Change setSize() callee so that camera get new size too
import {Video} from 'kaleidoscopejs'; import {ContainerPlugin, Mediator, Events} from 'clappr'; export default class Video360 extends ContainerPlugin { constructor(container) { super(container); Mediator.on(`${this.options.playerId}:${Events.PLAYER_RESIZE}`, this.updateSize, this); let {height, width, autoplay} = container.options; container.playback.el.setAttribute('crossorigin', 'anonymous'); this.viewer = new Video({height: isNaN(height) ? 300 : height, width: isNaN(width) ? 400 : width, container: this.container.el, source: this.container.playback.el}); this.viewer.render(); } get name() { return 'Video360'; } updateSize() { setTimeout(() => this.viewer.setSize({height: this.container.$el.height(), width: this.container.$el.width()}) , 250) } }
import {Video} from 'kaleidoscopejs'; import {ContainerPlugin, Mediator, Events} from 'clappr'; export default class Video360 extends ContainerPlugin { constructor(container) { super(container); Mediator.on(`${this.options.playerId}:${Events.PLAYER_RESIZE}`, this.updateSize, this); let {height, width, autoplay} = container.options; container.playback.el.setAttribute('crossorigin', 'anonymous'); this.viewer = new Video({height: isNaN(height) ? 300 : height, width: isNaN(width) ? 400 : width, container: this.container.el, source: this.container.playback.el}); this.viewer.render(); } get name() { return 'Video360'; } updateSize() { setTimeout(() => this.viewer.renderer.setSize({height: this.container.$el.height(), width: this.container.$el.width()}) , 250) } }
Add timestamp and newline to log messages
import os import datetime from django.conf import settings from django.core.management.base import BaseCommand, CommandError from pontoon.administration.views import _update_from_repository from pontoon.base.models import Project class Command(BaseCommand): help = 'Update all projects from their repositories and store changes to the database' def handle(self, *args, **options): for project in Project.objects.all(): try: repository_type = project.repository_type repository_url = project.repository repository_path_master = os.path.join(settings.MEDIA_ROOT, repository_type, project.name) _update_from_repository( project, repository_type, repository_url, repository_path_master) now = datetime.datetime.now() self.stdout.write('[%s]: Successfully updated project "%s"\n' % (now, project)) except Exception as e: now = datetime.datetime.now() raise CommandError('[%s]: UpdateProjectsFromRepositoryError: %s\n' % (now, unicode(e)))
import os from django.conf import settings from django.core.management.base import BaseCommand, CommandError from pontoon.administration.views import _update_from_repository from pontoon.base.models import Project class Command(BaseCommand): help = 'Update all projects from their repositories and store changes to the database' def handle(self, *args, **options): for project in Project.objects.all(): try: repository_type = project.repository_type repository_url = project.repository repository_path_master = os.path.join(settings.MEDIA_ROOT, repository_type, project.name) _update_from_repository( project, repository_type, repository_url, repository_path_master) self.stdout.write('Successfully updated project "%s"' % project) except Exception as e: raise CommandError('UpdateProjectsFromRepositoryError: %s' % unicode(e))
Convert comment stats to new UF Convert comment stats to new UF
<?php /*-------------------------------------------------------+ | PHP-Fusion Content Management System | Copyright (C) PHP-Fusion Inc | http://www.php-fusion.co.uk/ +--------------------------------------------------------+ | Filename: user_comments-stat_include.php | Author: PHP-Fusion Development Team +--------------------------------------------------------+ | This program is released as free software under the | Affero GPL license. You can redistribute it and/or | modify it under the terms of this license which you | can read by viewing the included agpl.txt or online | at www.gnu.org/licenses/agpl.html. Removal of this | copyright header is strictly prohibited without | written permission from the original author(s). +--------------------------------------------------------*/ if (!defined("IN_FUSION")) { die("Access Denied"); } if ($profile_method == "input") { $user_fields = ''; if (defined('ADMIN_PANEL')) { $user_fields = "<div class='well m-t-5 text-center'>".$locale['uf_comments-stat']."</div>"; } } elseif ($profile_method == "display") { $user_fields = array('title'=>$locale['uf_comments-stat'], 'value'=>number_format(dbcount("(comment_id)", DB_COMMENTS, "comment_name='".$user_data['user_id']."'")).""); } elseif ($profile_method == "validate_insert") { //Nothing here } elseif ($profile_method == "validate_update") { //Nothing here } ?>
<?php /*-------------------------------------------------------+ | PHP-Fusion Content Management System | Copyright (C) PHP-Fusion Inc | http://www.php-fusion.co.uk/ +--------------------------------------------------------+ | Filename: user_comments-stat_include.php | Author: Digitanium +--------------------------------------------------------+ | This program is released as free software under the | Affero GPL license. You can redistribute it and/or | modify it under the terms of this license which you | can read by viewing the included agpl.txt or online | at www.gnu.org/licenses/agpl.html. Removal of this | copyright header is strictly prohibited without | written permission from the original author(s). +--------------------------------------------------------*/ if (!defined("IN_FUSION")) { die("Access Denied"); } if ($profile_method == "input") { //Nothing here } elseif ($profile_method == "display") { echo "<tr>\n"; echo "<td class='tbl1'>".$locale['uf_comments-stat']."</td>\n"; echo "<td align='right' class='tbl1'>".number_format(dbcount("(comment_id)", DB_COMMENTS, "comment_name='".$user_data['user_id']."'"))."</td>\n"; echo "</tr>\n"; } elseif ($profile_method == "validate_insert") { //Nothing here } elseif ($profile_method == "validate_update") { //Nothing here } ?>
Change Ribots database version from 2 to 1
package com.vikashkothary.life.data.local; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import javax.inject.Inject; import javax.inject.Singleton; import com.vikashkothary.life.injection.ApplicationContext; @Singleton public class DbOpenHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "ribots.db"; public static final int DATABASE_VERSION = 1; @Inject public DbOpenHelper(@ApplicationContext Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onConfigure(SQLiteDatabase db) { super.onConfigure(db); //Uncomment line below if you want to enable foreign keys //db.execSQL("PRAGMA foreign_keys=ON;"); } @Override public void onCreate(SQLiteDatabase db) { db.beginTransaction(); try { db.execSQL(Db.RibotProfileTable.CREATE); //Add other tables here db.setTransactionSuccessful(); } finally { db.endTransaction(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
package com.vikashkothary.life.data.local; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import javax.inject.Inject; import javax.inject.Singleton; import com.vikashkothary.life.injection.ApplicationContext; @Singleton public class DbOpenHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "ribots.db"; public static final int DATABASE_VERSION = 2; @Inject public DbOpenHelper(@ApplicationContext Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onConfigure(SQLiteDatabase db) { super.onConfigure(db); //Uncomment line below if you want to enable foreign keys //db.execSQL("PRAGMA foreign_keys=ON;"); } @Override public void onCreate(SQLiteDatabase db) { db.beginTransaction(); try { db.execSQL(Db.RibotProfileTable.CREATE); //Add other tables here db.setTransactionSuccessful(); } finally { db.endTransaction(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
Add missing [] from url
'use strict'; var express = require('express'), request = require('superagent'), app = express(), config = require('./config'); app.get('*', function(req, res){ var endpoint = config[req.url]; if (req.url === '/') { res.redirect('http://redhat.com/events'); return; } if (req.url === '/forum') { res.redirect('http://www.redhat.com/en/about/events?f[0]=field_event_type%3A8101&rset1_format=list'); return; } if (endpoint === undefined) { res.redirect('/forum'); return; } res.writeHead(200, { 'Content-Type' : 'text/html' }); request .get(endpoint) .pipe(res); }); app.listen(8000);
'use strict'; var express = require('express'), request = require('superagent'), app = express(), config = require('./config'); app.get('*', function(req, res){ var endpoint = config[req.url]; if (req.url === '/') { res.redirect('http://redhat.com/events'); return; } if (req.url === '/forum') { res.redirect('http://www.redhat.com/en/about/events?f0=field_event_type%3A8101&rset1_format=list&f0=field_event_type%3A8101'); return; } if (endpoint === undefined) { res.redirect('/forum'); return; } res.writeHead(200, { 'Content-Type' : 'text/html' }); request .get(endpoint) .pipe(res); }); app.listen(8000);
Change LQR gain element printing Change printing of LQR gain elements for easier copying.
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import scipy import control from dtk.bicycle import benchmark_state_space_vs_speed, benchmark_matrices def compute_whipple_lqr_gain(velocity): _, A, B = benchmark_state_space_vs_speed(*benchmark_matrices(), velocity) Q = np.diag([1e5, 1e3, 1e3, 1e2]) R = np.eye(2) gains = [control.lqr(Ai, Bi, Q, R)[0] for Ai, Bi in zip(A, B)] return gains if __name__ == '__main__': import sys v_low = 0 # m/s if len(sys.argv) > 1: v_high = int(sys.argv[1]) else: v_high = 1 # m/s velocities = [v_low, v_high] gains = compute_whipple_lqr_gain(velocities) for v, K in zip(velocities, gains): print('computed LQR controller feedback gain for v = {}'.format(v)) K = -K for r in range(K.shape[0]): row = ', '.join(str(elem) for elem in K[r, :]) if r != K.shape[0] - 1: row += ',' print(row) print()
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import scipy import control from dtk.bicycle import benchmark_state_space_vs_speed, benchmark_matrices def compute_whipple_lqr_gain(velocity): _, A, B = benchmark_state_space_vs_speed(*benchmark_matrices(), velocity) Q = np.diag([1e5, 1e3, 1e3, 1e2]) R = np.eye(2) gains = [control.lqr(Ai, Bi, Q, R)[0] for Ai, Bi in zip(A, B)] return gains if __name__ == '__main__': import sys v_low = 0 # m/s if len(sys.argv) > 1: v_high = int(sys.argv[1]) else: v_high = 1 # m/s velocities = [v_low, v_high] gains = compute_whipple_lqr_gain(velocities) for v, K in zip(velocities, gains): print('computed LQR controller feedback gain for v = {}'.format(v)) print(-K) print()
PY-22460: Check variable before accessing it
# coding=utf-8 import os from unittest import main from _jb_runner_tools import jb_start_tests, jb_doc_args from teamcity import unittestpy if __name__ == '__main__': path, targets, additional_args = jb_start_tests() args = ["python -m unittest"] if path: discovery_args = ["discover", "-s"] # Unittest does not support script directly, but it can use "discover" to find all tests in some folder # filtering by script assert os.path.exists(path), "{0}: No such file or directory".format(path) if os.path.isfile(path): discovery_args += [os.path.dirname(path), "-p", os.path.basename(path)] else: discovery_args.append(path) additional_args = discovery_args + additional_args elif targets: additional_args += targets args += additional_args jb_doc_args("unittests", args) main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner())
# coding=utf-8 import os from unittest import main from _jb_runner_tools import jb_start_tests, jb_doc_args from teamcity import unittestpy if __name__ == '__main__': path, targets, additional_args = jb_start_tests() args = ["python -m unittest"] if path: discovery_args = ["discover", "-s"] # Unittest does not support script directly, but it can use "discover" to find all tests in some folder # filtering by script assert os.path.exists(path), "{0}: No such file or directory".format(path) if os.path.isfile(path): discovery_args += [os.path.dirname(path), "-p", os.path.basename(path)] else: discovery_args.append(path) additional_args = discovery_args + additional_args else: additional_args += targets args += additional_args jb_doc_args("unittests", args) main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner())
Fix pin input name on authentication challenge page
<? require_once "record.inc"; print $_lib['sess']->doctype ?> <head> <title>Empatix - Altinn lønnslipper</title> <? includeinc('head') ?> </head> <body> <? print $_lib['message']->get() ?> <? print $authentication_challenge_message ?> <? $target_page = $_POST['request_type'] == 'feedback' ? 'altinnsalary.show4' : 'altinnsalary.list'?> <form name="altinnsalary_search" action="<? print $_lib['sess']->dispatch ?>t=<? print $target_page ?>" method="post"> <input type="hidden" name="request_receivers_reference" value='<?print $_POST['request_receivers_reference']; ?>'> <? print $_lib['form3']->text(array('name'=>'user_pin_code', 'width'=>'10' , 'value'=>'')) ?> <? if($_POST['request_type'] == 'feedback'){ print $_lib['form3']->submit(array('name'=>'action_soap4', 'value'=>'Get Feedback')); }elseif($_POST['request_type'] == 'archive'){ print $_lib['form3']->submit(array('name'=>'action_soap5', 'value'=>'Archive Report')); } ?> </form> </body> </html>
<? require_once "record.inc"; print $_lib['sess']->doctype ?> <head> <title>Empatix - Altinn lønnslipper</title> <? includeinc('head') ?> </head> <body> <? print $_lib['message']->get() ?> <? print $authentication_challenge_message ?> <? $target_page = $_POST['request_type'] == 'feedback' ? 'altinnsalary.show4' : 'altinnsalary.list'?> <form name="altinnsalary_search" action="<? print $_lib['sess']->dispatch ?>t=<? print $target_page ?>" method="post"> <input type="hidden" name="request_receivers_reference" value='<?print $_POST['request_receivers_reference']; ?>'> <? print $_lib['form3']->text(array('field'=>'user_pin_code', 'width'=>'10' , 'value'=>'')) ?> <? if($_POST['request_type'] == 'feedback'){ print $_lib['form3']->submit(array('name'=>'action_soap4', 'value'=>'Get Feedback')); }elseif($_POST['request_type'] == 'archive'){ print $_lib['form3']->submit(array('name'=>'action_soap5', 'value'=>'Archive Report')); } ?> </form> </body> </html>
[jquery] Add assertion to validate HTML is correct. This requires the nodes.js version of jquery. Talk to Luke if you are having issues installing it. (imported from commit 86dc91a9a41b2ef9c2dbcc4fb0085109250d7af7)
var assert = require('assert'); add_dependencies({ _: 'third/underscore/underscore', Dict: 'js/dict', Handlebars: 'handlebars', templates: 'js/templates', muting: 'js/muting', narrow: 'js/narrow', hashchange: 'js/hashchange' }); set_global('recent_subjects', new global.Dict()); set_global('unread', {}); set_global('$', function () {}); var stream_list = require('js/stream_list.js'); global.$ = require('jquery'); global.use_template('sidebar_subject_list'); (function test_build_subject_list() { var stream = "devel"; var active_topic = "testing"; var max_topics = 5; var topics = [ {subject: "coding"} ]; global.recent_subjects.set("devel", topics); global.unread.num_unread_for_subject = function () { return 1; }; var topic_html = stream_list._build_subject_list(stream, active_topic, max_topics); global.write_test_output("test_build_subject_list", topic_html); var topic = $(topic_html).find('a').text().trim(); assert.equal(topic, 'coding'); }());
var assert = require('assert'); add_dependencies({ _: 'third/underscore/underscore', Dict: 'js/dict', Handlebars: 'handlebars', templates: 'js/templates', muting: 'js/muting', narrow: 'js/narrow', hashchange: 'js/hashchange' }); set_global('recent_subjects', new global.Dict()); set_global('unread', {}); set_global('$', function () {}); var stream_list = require('js/stream_list.js'); global.use_template('sidebar_subject_list'); (function test_build_subject_list() { var stream = "devel"; var active_topic = "testing"; var max_topics = 5; var topics = [ {subject: "coding"} ]; global.recent_subjects.set("devel", topics); global.unread.num_unread_for_subject = function () { return 1; }; var topic_html = stream_list._build_subject_list(stream, active_topic, max_topics); global.write_test_output("test_build_subject_list", topic_html); }());
Add cors header for browser testing
const _ = require('lodash'); const router = require('express').Router(); router.get('/cookie', (req, res) => { const data = JSON.stringify(req.headers); let response = ''; response += 'HTTP/1.1 200 OK\r\n'; response += 'Connection: close\r\n'; response += `Content-Length: ${data.length}\r\n`; response += 'Content-Type: application/json\r\n'; response += `Cookie: ${_.repeat('a', req.query.length)}\r\n`; response += 'Date: Wed, 30 Nov 2016 20:19:57 GMT\r\n\r\n'; response += data; res.socket.end(response); res.socket.destroy(); }); router.get('/content-length', (req, res) => { let response = ''; response += 'HTTP/1.1 200 OK\r\n'; response += 'Connection: close\r\n'; response += 'Content-Length: 3\r\n'; response += 'Access-Control-Allow-Origin: *\r\n'; response += 'Content-Type: text/plain\r\n'; response += 'Date: Wed, 30 Nov 2016 20:19:57 GMT\r\n\r\n'; response += 'abcdefghijklmnopqrstuvwxyz'; res.socket.end(response); res.socket.destroy(); }); module.exports = router;
const _ = require('lodash'); const router = require('express').Router(); router.get('/cookie', (req, res) => { const data = JSON.stringify(req.headers); let response = ''; response += 'HTTP/1.1 200 OK\r\n'; response += 'Connection: close\r\n'; response += `Content-Length: ${data.length}\r\n`; response += 'Content-Type: application/json\r\n'; response += `Cookie: ${_.repeat('a', req.query.length)}\r\n`; response += 'Date: Wed, 30 Nov 2016 20:19:57 GMT\r\n\r\n'; response += data; res.socket.end(response); res.socket.destroy(); }); router.get('/content-length', (req, res) => { let response = ''; response += 'HTTP/1.1 200 OK\r\n'; response += 'Connection: close\r\n'; response += 'Content-Length: 3\r\n'; response += 'Content-Type: text/plain\r\n'; response += 'Date: Wed, 30 Nov 2016 20:19:57 GMT\r\n\r\n'; response += 'abcdefghijklmnopqrstuvwxyz'; res.socket.end(response); res.socket.destroy(); }); module.exports = router;
Change default 'tint' to 'normal' to solve console warning
import React, { PureComponent } from 'react'; import cx from 'classnames'; import PropTypes from 'prop-types'; import Box from '../box'; import theme from './theme.css'; class LoadingBar extends PureComponent { render() { const { className, color, size, tint, ...others } = this.props; const classNames = cx( theme['loading-bar'], theme[`is-${color}`], theme[`is-${size}`], theme[`is-${tint}`], className, ); return ( <Box data-teamleader-ui="loading-bar" className={classNames} {...others}> <div className={theme['loading-bar-indicator']} /> </Box> ); } } LoadingBar.propTypes = { /** A class name for the wrapper to add custom classes */ className: PropTypes.string, /** The color of the components */ color: PropTypes.oneOf(['aqua', 'gold', 'mint', 'neutral', 'ruby', 'teal', 'violet']), /** Size of the component */ size: PropTypes.oneOf(['small', 'medium', 'large']), /** The tint of the components color */ tint: PropTypes.oneOf(['lightest', 'light', 'normal', 'dark', 'darkest']), }; LoadingBar.defaultProps = { color: 'mint', size: 'small', tint: 'normal', }; export default LoadingBar;
import React, { PureComponent } from 'react'; import cx from 'classnames'; import PropTypes from 'prop-types'; import Box from '../box'; import theme from './theme.css'; class LoadingBar extends PureComponent { render() { const { className, color, size, tint, ...others } = this.props; const classNames = cx( theme['loading-bar'], theme[`is-${color}`], theme[`is-${size}`], theme[`is-${tint}`], className, ); return ( <Box data-teamleader-ui="loading-bar" className={classNames} {...others}> <div className={theme['loading-bar-indicator']} /> </Box> ); } } LoadingBar.propTypes = { /** A class name for the wrapper to add custom classes */ className: PropTypes.string, /** The color of the components */ color: PropTypes.oneOf(['aqua', 'gold', 'mint', 'neutral', 'ruby', 'teal', 'violet']), /** Size of the component */ size: PropTypes.oneOf(['small', 'medium', 'large']), /** The tint of the components color */ tint: PropTypes.oneOf(['lightest', 'light', 'normal', 'dark', 'darkest']), }; LoadingBar.defaultProps = { color: 'mint', size: 'small', tint: 'neutral', }; export default LoadingBar;
Change version to dev version
__author__ = 'matth' from distutils.core import setup from setuptools import find_packages setup( name='py-exe-builder', version='0.2.dev1', packages = find_packages(), license='Apache License, Version 2.0', description='Uses py2exe to create small exe stubs that leverage a full python installation, rather than packing the required pyc files in to the executable.', long_description=open('README.md').read(), url='http://www.j5int.com/', author='j5 International', author_email='support@j5int.com', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: Apache Software License', 'Environment :: Win32 (MS Windows)', 'Intended Audience :: Developers', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python', 'Programming Language :: Python :: 2 :: Only', 'Topic :: Software Development :: Libraries :: Python Modules', ], install_requires = ["py2exe"], )
__author__ = 'matth' from distutils.core import setup from setuptools import find_packages setup( name='py-exe-builder', version='0.1', packages = find_packages(), license='Apache License, Version 2.0', description='Uses py2exe to create small exe stubs that leverage a full python installation, rather than packing the required pyc files in to the executable.', long_description=open('README.md').read(), url='http://www.j5int.com/', author='j5 International', author_email='support@j5int.com', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: Apache Software License', 'Environment :: Win32 (MS Windows)', 'Intended Audience :: Developers', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python', 'Programming Language :: Python :: 2 :: Only', 'Topic :: Software Development :: Libraries :: Python Modules', ], install_requires = ["py2exe"], )
Fix swapped test group names
<?php /** * @category Mad * @package Mad_Task * @copyright (c) 2007-2009 Maintainable Software, LLC * @license http://opensource.org/licenses/bsd-license.php BSD */ /** * Built-in framework tasks for testing. * * @category Mad * @package Mad_Task * @copyright (c) 2007-2009 Maintainable Software, LLC * @license http://opensource.org/licenses/bsd-license.php BSD */ class Mad_Task_BuiltinSet_Testing extends Mad_Task_Set { /** * Test all units and functionals */ public function test() { chdir(MAD_ROOT . '/test'); passthru('phpunit AllTests'); } /** * Run the unit tests in test/unit */ public function test_units() { chdir(MAD_ROOT . '/test'); passthru('phpunit --group unit AllTests'); } /** * Run the functional tests in test/functional */ public function test_functionals() { chdir(MAD_ROOT . '/test'); passthru('phpunit --group functional AllTests'); } }
<?php /** * @category Mad * @package Mad_Task * @copyright (c) 2007-2009 Maintainable Software, LLC * @license http://opensource.org/licenses/bsd-license.php BSD */ /** * Built-in framework tasks for testing. * * @category Mad * @package Mad_Task * @copyright (c) 2007-2009 Maintainable Software, LLC * @license http://opensource.org/licenses/bsd-license.php BSD */ class Mad_Task_BuiltinSet_Testing extends Mad_Task_Set { /** * Test all units and functionals */ public function test() { chdir(MAD_ROOT . '/test'); passthru('phpunit AllTests'); } /** * Run the unit tests in test/unit */ public function test_units() { chdir(MAD_ROOT . '/test'); passthru('phpunit --group functional AllTests'); } /** * Run the functional tests in test/functional */ public function test_functionals() { chdir(MAD_ROOT . '/test'); passthru('phpunit --group unit AllTests'); } }
Fix code snippet codetype so it passes in correctly
import React from 'react'; import Highlight, { defaultProps } from 'prism-react-renderer'; import darkTheme from 'prism-react-renderer/themes/duotoneDark'; const InlineCode = ({ children, className, additionalPreClasses, theme }) => { className = className ? className : ''; const language = className.replace(/language-/, ''); return ( <Highlight {...defaultProps} code={children} language={language} theme={theme || darkTheme} > {({ className, style, tokens, getLineProps, getTokenProps }) => ( <pre className={`docs-code sprk-u-Measure ${className} ${additionalPreClasses}`} style={{ ...style }} > {tokens.map((line, i) => ( <div key={i} {...getLineProps({ line, key: i })}> {line.map((token, key) => ( <span key={key} {...getTokenProps({ token, key })} /> ))} </div> ))} </pre> )} </Highlight> ); }; export default InlineCode;
import React from 'react'; import Highlight, { defaultProps } from 'prism-react-renderer'; import darkTheme from 'prism-react-renderer/themes/duotoneDark'; const InlineCode = ({ children, className, additionalPreClasses, theme }) => { className = className ? '' : className; const language = className.replace(/language-/, ''); return ( <Highlight {...defaultProps} code={children} language={language} theme={theme || darkTheme} > {({ className, style, tokens, getLineProps, getTokenProps }) => ( <pre className={`docs-code sprk-u-Measure ${className} ${additionalPreClasses}`} style={{ ...style }} > {tokens.map((line, i) => ( <div key={i} {...getLineProps({ line, key: i })}> {line.map((token, key) => ( <span key={key} {...getTokenProps({ token, key })} /> ))} </div> ))} </pre> )} </Highlight> ); }; export default InlineCode;
Fix store not updating, because incorrect event string This was hard to track down :<
import _ from 'underscore'; import BaseStore from 'stores/BaseStore'; import Dispatcher from 'dispatchers/Dispatcher'; import Store from 'stores/Store'; import AllocationConstants from 'constants/AllocationConstants'; import AllocationCollection from 'collections/AllocationCollection'; import stores from 'stores'; let AllocationStore = BaseStore.extend({ collection: AllocationCollection }); let store = new AllocationStore(); Dispatcher.register(function(dispatch) { var actionType = dispatch.action.actionType; var payload = dispatch.action.payload; var options = dispatch.action.options || options; switch (actionType) { case AllocationConstants.CREATE_ALLOCATION: store.add(payload.allocation); break; default: return true; } if (!options.silent) { store.emitChange(); } return true; }); export default store;
import _ from 'underscore'; import BaseStore from 'stores/BaseStore'; import Dispatcher from 'dispatchers/Dispatcher'; import Store from 'stores/Store'; import AllocationConstants from 'constants/ResourceRequestConstants'; import AllocationCollection from 'collections/AllocationCollection'; import stores from 'stores'; let AllocationStore = BaseStore.extend({ collection: AllocationCollection }); let store = new AllocationStore(); Dispatcher.register(function(dispatch) { var actionType = dispatch.action.actionType; var payload = dispatch.action.payload; var options = dispatch.action.options || options; switch (actionType) { case AllocationConstants.CREATE_ALLOCATION: store.add(payload.allocation); break; default: return true; } if (!options.silent) { store.emitChange(); } return true; }); export default store;
Set default log level to error
const winston = require('winston'); const { format, transports, createLogger } = winston; let logLevel = process.env.LOG_LEVEL; if (!logLevel) { switch (process.env.NODE_ENV) { case 'development': logLevel = 'debug'; break; case 'test': logLevel = 'emerg'; break; case 'default': case 'production': default: logLevel = 'error'; } } const addType = format.printf((log) => { if (log.stack || log.level === 'error') { log.type = 'error'; } else { log.type = 'log'; } return log; }); const colorize = process.env.NODE_ENV !== 'production'; let formater; if (process.env.NODE_ENV === 'test') { formater = format.combine( format.prettyPrint({ depth: 1, colorize }), ); } else { formater = format.combine( format.errors({ stack: true }), format.timestamp(), addType, format.prettyPrint({ depth: 3, colorize }), ); } const logger = createLogger({ levels: winston.config.syslog.levels, format: formater, transports: [ new transports.Console({ level: logLevel, handleExceptions: true, }), ], exitOnError: false, }); module.exports = logger;
const winston = require('winston'); const { format, transports, createLogger } = winston; let logLevel = process.env.LOG_LEVEL; if (!logLevel) { switch (process.env.NODE_ENV) { case 'default': case 'development': logLevel = 'debug'; break; case 'test': logLevel = 'emerg'; break; case 'production': default: logLevel = 'info'; } } const addType = format.printf((log) => { if (log.stack || log.level === 'error') { log.type = 'error'; } else { log.type = 'log'; } return log; }); const colorize = process.env.NODE_ENV !== 'production'; let formater; if (process.env.NODE_ENV === 'test') { formater = format.combine( format.prettyPrint({ depth: 1, colorize }), ); } else { formater = format.combine( format.errors({ stack: true }), format.timestamp(), addType, format.prettyPrint({ depth: 3, colorize }), ); } const logger = createLogger({ levels: winston.config.syslog.levels, format: formater, transports: [ new transports.Console({ level: logLevel, handleExceptions: true, }), ], exitOnError: false, }); module.exports = logger;
Fix KeyError in Provide personal data form
from django.core.urlresolvers import reverse from django.forms import model_to_dict from django.http.response import HttpResponseRedirect, HttpResponse from django.shortcuts import render from common.models import Student from sell.forms import PersonalDataForm def index(request): return HttpResponseRedirect(reverse('sell.views.personal_data')) def personal_data(request): if request.method == 'POST': form = PersonalDataForm(request.POST) if form.is_valid(): request.session['personal_data'] = model_to_dict(form.save(commit=False)) return HttpResponseRedirect(reverse('sell.views.books')) else: if 'personal_data' in request.session: form = PersonalDataForm(instance=Student(**request.session['personal_data'])) else: form = PersonalDataForm() return render(request, 'sell/personal_data.html', {'form': form}) def books(request): return HttpResponse("Hello, world!")
from django.core.urlresolvers import reverse from django.forms import model_to_dict from django.http.response import HttpResponseRedirect, HttpResponse from django.shortcuts import render from common.models import Student from sell.forms import PersonalDataForm def index(request): return HttpResponseRedirect(reverse('sell.views.personal_data')) def personal_data(request): if request.method == 'POST': form = PersonalDataForm(request.POST) if form.is_valid(): request.session['personal_data'] = model_to_dict(form.save(commit=False)) return HttpResponseRedirect(reverse('sell.views.books')) else: if request.session['personal_data']: form = PersonalDataForm(instance=Student(**request.session['personal_data'])) else: form = PersonalDataForm() return render(request, 'sell/personal_data.html', {'form': form}) def books(request): return HttpResponse("Hello, world!")
Add a minimum cython-sgio version to the dependencies. This makes sure that only the _fixed_ cython-sgio version is used.
# SPDX-FileCopyrightText: 2014 The python-scsi Authors # # SPDX-License-Identifier: LGPL-2.1-or-later # coding: utf-8 from setuptools import find_packages, setup import setuptools_scm # noqa: F401 # Ensure it's present. setup( packages=find_packages(exclude=["tests"]), python_requires='~=3.7', extras_require={ 'dev': [ 'isort', 'mypy', 'pre-commit', 'pytest', 'pytest-mypy', 'setuptools>=42', 'setuptools_scm[toml]>=3.4', 'wheel', ], 'iscsi': ['cython-iscsi'], 'sgio': ['cython-sgio>=1.1.2'], }, )
# SPDX-FileCopyrightText: 2014 The python-scsi Authors # # SPDX-License-Identifier: LGPL-2.1-or-later # coding: utf-8 from setuptools import find_packages, setup import setuptools_scm # noqa: F401 # Ensure it's present. setup( packages=find_packages(exclude=["tests"]), python_requires='~=3.7', extras_require={ 'dev': [ 'isort', 'mypy', 'pre-commit', 'pytest', 'pytest-mypy', 'setuptools>=42', 'setuptools_scm[toml]>=3.4', 'wheel', ], 'iscsi': ['cython-iscsi'], 'sgio': ['cython-sgio'], }, )
Store temporary test directories in test path.
import os import shutil import unittest from stash import Stash class StashTestCase(unittest.TestCase): """Base class for test cases that test stash functionality. This base class makes sure that all unit tests are executed in a sandbox environment. """ PATCHES_PATH = os.path.join('test', '.patches') REPOSITORY_URI = os.path.join('test', '.repo') @classmethod def setUpClass(cls): """Makes sure that stash will look for patches in the patches path in the test directory, and that the repository directory exists. """ if not os.path.exists(cls.REPOSITORY_URI): os.mkdir(cls.REPOSITORY_URI) if not os.path.exists(cls.PATCHES_PATH): os.mkdir(cls.PATCHES_PATH) Stash.PATCHES_PATH = cls.PATCHES_PATH @classmethod def tearDownClass(cls): """Cleans up the temporary patches path used for the unit tests.""" if os.path.exists(cls.PATCHES_PATH): shutil.rmtree(cls.PATCHES_PATH) # Clean up the temporary repository. if os.path.exists(cls.REPOSITORY_URI): shutil.rmtree(cls.REPOSITORY_URI)
import os import shutil import subprocess import unittest from stash import Stash class StashTestCase(unittest.TestCase): """Base class for test cases that test stash functionality. This base class makes sure that all unit tests are executed in a sandbox environment. """ PATCHES_PATH = '.patches' REPOSITORY_URI = '.repo' @classmethod def setUpClass(cls): """Makes sure that stash will look for patches in the patches path in the test directory, and that the repository directory exists. """ if not os.path.exists(cls.REPOSITORY_URI): os.mkdir(cls.REPOSITORY_URI) if not os.path.exists(cls.PATCHES_PATH): os.mkdir(cls.PATCHES_PATH) Stash.PATCHES_PATH = cls.PATCHES_PATH @classmethod def tearDownClass(cls): """Cleans up the temporary patches path used for the unit tests.""" if os.path.exists(cls.PATCHES_PATH): shutil.rmtree(cls.PATCHES_PATH) # Clean up the temporary repository. if os.path.exists(cls.REPOSITORY_URI): shutil.rmtree(cls.REPOSITORY_URI)
Switch InstantShare test to use Sinon infrastructure as per review comment
/* global sinon, Event, InstantShareApp, chai */ describe("InstantShareApp", function() { "use strict"; var expect = chai.expect; var xhr, request; beforeEach(function() { xhr = sinon.useFakeXMLHttpRequest(); request = undefined; xhr.onCreate = function (req) { request = req; }; }); afterEach(function() { xhr.restore(); }); // XXX error behavior! describe("click event on the call button", function() { it("should post an xhr request with an empty object to the " + "instant-share pingback API", function() { var instantShareApp = new InstantShareApp(); instantShareApp.start(); var event = new Event('click'); document.querySelector("#instant-share-call a") .dispatchEvent(event); expect(request.method.toLowerCase()).to.equal("post"); expect(request.async).to.equal(true); expect(request.url).to.equal(window.location); expect(request.requestBody).to.equal(JSON.stringify({})); }); }); });
/* global sinon, Event, InstantShareApp */ describe("InstantShareApp", function() { "use strict"; var sandbox, xhr; beforeEach(function() { sandbox = sinon.sandbox.create(); xhr = { open: sinon.spy(), setRequestHeader: function() {}, send: function() {} }; sandbox.stub(window, "XMLHttpRequest").returns(xhr); }); afterEach(function() { sandbox.restore(); }); describe("click event on the call button", function() { it("should post an xhr request to the instant-share ping back API", function() { var instantShareApp = new InstantShareApp(); instantShareApp.start(); var event = new Event('click'); document.querySelector("#instant-share-call a") .dispatchEvent(event); sinon.assert.calledOnce(xhr.open); sinon.assert.calledWithExactly(xhr.open, "POST", window.location, true); }); }); });
Append event merging on splash_events
import datetime from django.shortcuts import render from apps.splash.models import SplashEvent, SplashYear def index(request): # I'm really sorry ... splash_year = SplashYear.objects.get(start_date__gt=str(datetime.date.today() - datetime.timedelta(180))) splash_year.events = _merge_events(splash_year.splash_events.all()) return render(request, 'splash/base.html', {'splash_year': splash_year }) # And I'm really sorry for this ... def _merge_events(splash_events): events = [] for event in splash_events: if len(events) > 0 and event.start_time.strftime('%d-%m') == events[-1][0].start_time.strftime('%d-%m'): events[-1].append(event) else: events.append([event]) return events
import datetime from django.shortcuts import render from apps.splash.models import SplashEvent, SplashYear def index(request): # I'm really sorry ... splash_year = SplashYear.objects.get(start_date__gt=str(datetime.date.today() - datetime.timedelta(180))) return render(request, 'splash/base.html', {'splash_year': splash_year }) # And I'm really sorry for this ... def _merge_events(splash_events): events = [] for event in splash_events: if len(events) > 0 and event.start_time.strftime('%d-%m') == events[-1][0].start_time.strftime('%d-%m'): events[-1].append(event) else: events.append([event]) return events
Tag provisioning instances to make them easier to identify
# trigger-provision.py <indexer-provision.sh | web-server-provision.sh> import boto3 from datetime import datetime, timedelta import sys import os.path provisioners = sys.argv[1:] ec2 = boto3.resource('ec2') client = boto3.client('ec2') script = '' for provisioner in provisioners: script += open(provisioner).read() + '\n' user_data = '''#!/usr/bin/env bash cat > ~ubuntu/provision.sh <<"FINAL" {script} FINAL chmod +x ~ubuntu/provision.sh sudo -i -u ubuntu ~ubuntu/provision.sh '''.format(script=script) # ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20160815 (ami-f701cb97) image_id = 'ami-f701cb97' launch_spec = { 'ImageId': image_id, 'KeyName': 'Main Key Pair', 'SecurityGroups': ['indexer'], 'UserData': user_data, 'InstanceType': 'c3.2xlarge', 'BlockDeviceMappings': [], 'TagSpecifications': [{ 'ResourceType': 'instance', 'Tags': [{ 'Key': 'provisioner', 'Value': sys.argv[1], }], }], } client.run_instances(MinCount=1, MaxCount=1, **launch_spec)
# trigger-provision.py <indexer-provision.sh | web-server-provision.sh> import boto3 from datetime import datetime, timedelta import sys import os.path provisioners = sys.argv[1:] ec2 = boto3.resource('ec2') client = boto3.client('ec2') script = '' for provisioner in provisioners: script += open(provisioner).read() + '\n' user_data = '''#!/usr/bin/env bash cat > ~ubuntu/provision.sh <<"FINAL" {script} FINAL chmod +x ~ubuntu/provision.sh sudo -i -u ubuntu ~ubuntu/provision.sh '''.format(script=script) # ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20160815 (ami-f701cb97) image_id = 'ami-f701cb97' launch_spec = { 'ImageId': image_id, 'KeyName': 'Main Key Pair', 'SecurityGroups': ['indexer'], 'UserData': user_data, 'InstanceType': 'c3.2xlarge', 'BlockDeviceMappings': [] } client.run_instances(MinCount=1, MaxCount=1, **launch_spec)
Remove list-parsing code from schema registry config parser
package com.homeadvisor.kafdrop.config; import org.hibernate.validator.constraints.NotBlank; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; @Configuration public class SchemaRegistryConfiguration { @Component @ConfigurationProperties(prefix = "schemaregistry") public static class SchemaRegistryProperties { @NotBlank private String connect; public String getConnect() { return connect; } public void setConnect(String connect) { this.connect = connect; } } }
package com.homeadvisor.kafdrop.config; import org.hibernate.validator.constraints.NotBlank; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; @Configuration public class SchemaRegistryConfiguration { @Component @ConfigurationProperties(prefix = "schemaregistry") public static class SchemaRegistryProperties { public static final Pattern CONNECT_SEPARATOR = Pattern.compile("\\s*,\\s*"); @NotBlank private String connect; public String getConnect() { return connect; } public void setConnect(String connect) { this.connect = connect; } public List<String> getConnectList() { return CONNECT_SEPARATOR.splitAsStream(this.connect) .map(String::trim) .filter(s -> s.length() > 0) .collect(Collectors.toList()); } } }
Put auth middleware further down the chain This is because otherwise it wouldn't catch the requester events
import thunk from 'redux-thunk' import createLogger from 'redux-logger' import { browserHistory } from 'react-router' import { syncHistory } from 'react-router-redux' import { combineReducers, compose, createStore, applyMiddleware } from 'redux' import { autoRehydrate } from 'redux-persist' import { analytics, authentication, requester, uploader } from './middleware' import * as reducers from './reducers' const reducer = combineReducers(reducers) const reduxRouterMiddleware = browserHistory ? syncHistory(browserHistory) : null let store = null if (typeof window !== 'undefined') { const logger = createLogger({ collapsed: true, predicate: () => ENV.APP_DEBUG }) store = compose( autoRehydrate(), applyMiddleware( thunk, reduxRouterMiddleware, uploader, requester, authentication, analytics, logger ), )(createStore)(reducer, window.__INITIAL_STATE__ || {}) } else { store = compose( applyMiddleware(thunk, uploader, requester, analytics), )(createStore)(reducer, {}) } export default store
import thunk from 'redux-thunk' import createLogger from 'redux-logger' import { browserHistory } from 'react-router' import { syncHistory } from 'react-router-redux' import { combineReducers, compose, createStore, applyMiddleware } from 'redux' import { autoRehydrate } from 'redux-persist' import { analytics, authentication, requester, uploader } from './middleware' import * as reducers from './reducers' const reducer = combineReducers(reducers) const reduxRouterMiddleware = browserHistory ? syncHistory(browserHistory) : null let store = null if (typeof window !== 'undefined') { const logger = createLogger({ collapsed: true, predicate: () => ENV.APP_DEBUG }) store = compose( autoRehydrate(), applyMiddleware( thunk, authentication, reduxRouterMiddleware, uploader, requester, analytics, logger ), )(createStore)(reducer, window.__INITIAL_STATE__ || {}) } else { store = compose( applyMiddleware(thunk, uploader, requester, analytics), )(createStore)(reducer, {}) } export default store
Make the findbugs checker happy
package com.rollbar.jvmti; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * CacheFrame is a frame generated from the native interface to hold a method and a list of local * variables for later use. */ public final class CacheFrame { private Method method; private final LocalVariable[] locals; /** * Constructor with the method and list of local variables. */ public CacheFrame(Method method, LocalVariable[] locals) { this.method = method; this.locals = Arrays.copyOf(locals, locals.length); } /** * Getter. * * @return the method that generated this frame. */ public Method getMethod() { return method; } /** * Getter. * * @return the local variables for this frame. */ public Map<String, Object> getLocals() { if (locals == null || locals.length == 0) { return Collections.emptyMap(); } Map<String, Object> localsMap = new HashMap<>(); for (LocalVariable localVariable : locals) { if (localVariable != null) { localsMap.put(localVariable.getName(), localVariable.getValue()); } } return localsMap; } @Override public String toString() { return "CacheFrame{" + ", locals=" + Arrays.toString(locals) + '}'; } }
package com.rollbar.jvmti; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * CacheFrame is a frame generated from the native interface to hold a method and a list of local * variables for later use. */ public final class CacheFrame { private Method method; private final LocalVariable[] locals; /** * Constructor with the method and list of local variables. */ public CacheFrame(Method method, LocalVariable[] locals) { this.method = method; this.locals = locals; } /** * Getter. * * @return the method that generated this frame. */ public Method getMethod() { return method; } /** * Getter. * * @return the local variables for this frame. */ public Map<String, Object> getLocals() { if (locals == null || locals.length == 0) { return Collections.emptyMap(); } Map<String, Object> localsMap = new HashMap<>(); for (LocalVariable localVariable : locals) { if (localVariable != null) { localsMap.put(localVariable.getName(), localVariable.getValue()); } } return localsMap; } @Override public String toString() { return "CacheFrame{" + ", locals=" + Arrays.toString(locals) + '}'; } }
Add a function for commands to process parameters
# The purpose of this file is to provide base classes with the needed functions # already defined; this allows us to guarantee that any exceptions raised # during function calls are a problem with the module and not just that the # particular function isn't defined. class Module(object): def hook(self, base): self.ircd = base return self class Mode(object): def hook(self, base): self.ircd = base return self def prefixSymbol(self): return None def checkSet(self, channel, param): return True def checkUnset(self, channel, param): return True def onJoin(self, channel, user, params): return "pass" def onMessage(self, sender, target, message): return ["pass"] def onPart(self, channel, user, reason): pass def onTopicChange(self, channel, user, topic): pass def commandData(self, command, *args): pass def Command(object): def hook(self, base): self.ircd = base return self def onUse(self, user, params): pass def processParams(self, user, params): return { "user": user, "params": params }
# The purpose of this file is to provide base classes with the needed functions # already defined; this allows us to guarantee that any exceptions raised # during function calls are a problem with the module and not just that the # particular function isn't defined. class Module(object): def hook(self, base): self.ircd = base return self class Mode(object): def hook(self, base): self.ircd = base return self def prefixSymbol(self): return None def checkSet(self, channel, param): return True def checkUnset(self, channel, param): return True def onJoin(self, channel, user, params): return "pass" def onMessage(self, sender, target, message): return ["pass"] def onPart(self, channel, user, reason): pass def onTopicChange(self, channel, user, topic): pass def commandData(self, command, *args): pass def Command(object): def hook(self, base): self.ircd = base return self def onUse(self, user, params): pass
Make browserify case work both for npm and bower.
// Renamed functions dc.abstractBubbleChart = dc.bubbleMixin; dc.baseChart = dc.baseMixin; dc.capped = dc.capMixin; dc.colorChart = dc.colorMixin; dc.coordinateGridChart = dc.coordinateGridMixin; dc.marginable = dc.marginMixin; dc.stackableChart = dc.stackMixin; return dc;} if(typeof define === "function" && define.amd) { define(["d3", "crossfilter"], _dc); } else if(typeof module === "object" && module.exports) { var _d3 = require('d3'); var _crossfilter = require('crossfilter'); // When using npm + browserify, 'crossfilter' is a function, // since package.json specifies index.js as main function, and it // does special handling. When using bower + browserify, // there's no main in bower.json (in fact, there's no bower.json), // so we need to fix it. if (typeof _crossfilter !== "function") { _crossfilter = _crossfilter.crossfilter; } module.exports = _dc(_d3, _crossfilter); } else { this.dc = _dc(d3, crossfilter); } } )();
// Renamed functions dc.abstractBubbleChart = dc.bubbleMixin; dc.baseChart = dc.baseMixin; dc.capped = dc.capMixin; dc.colorChart = dc.colorMixin; dc.coordinateGridChart = dc.coordinateGridMixin; dc.marginable = dc.marginMixin; dc.stackableChart = dc.stackMixin; return dc;} if(typeof define === "function" && define.amd) { define(["d3", "crossfilter"], _dc); } else if(typeof module === "object" && module.exports) { // When using window global, window.crossfilter is a function // When using require, the value will be an object with 'crossfilter' // field, so we need to access it here. module.exports = _dc(require('d3'), require('crossfilter').crossfilter); } else { this.dc = _dc(d3, crossfilter); } } )();
Add some feedback to theGitGo
'use strict' module.exports = { global: { timeLimit: Infinity }, machine: { startState: 'done', done: null }, viewer: { title: 'Getting an existing repository', steps: {}, feedback: { null: { done: 'Your repository now contains the file <code>hello.txt</code>; typing <code>git log</code> will show its history.' } } }, repo: { commits: [ { msg: 'Initial commit', files: [] }, { msg: 'Add hello.txt', files: [{ src: 'hello.txt', template: { greeting: 'Hello, world!' } }] }, { msg: 'Update hello.txt', files: [{ src: 'hello.txt', template: { greeting: 'Hello, Git!' } }] } ] } }
'use strict' module.exports = { global: { timeLimit: Infinity }, machine: { startState: 'done', done: null }, viewer: { title: 'Getting an existing repository', steps: {}, feedback: {} }, repo: { commits: [ { msg: 'Initial commit', files: [] }, { msg: 'Add hello.txt', files: [{ src: 'hello.txt', template: { greeting: 'Hello, world!' } }] }, { msg: 'Update hello.txt', files: [{ src: 'hello.txt', template: { greeting: 'Hello, Git!' } }] } ] } }
Set content type to string
package issue import "net/http" type HttpBody struct { ContentEncoding string `json:"contentEncoding"` Content string `json:"content"` } type HttpEntity struct { Status string `json:"status"` Header http.Header `json:"header"` Body *HttpBody `json:"body,omitempty"` } type HttpTransaction struct { Id int `json:"id,omitempty"` Url string `json:"url"` Params []string `json:"params,omitempty"` Method string `json:"method"` Request *HttpEntity `json:"request,omitempty"` Response *HttpEntity `json:"response,omitempty"` } type Vector struct { Url string `json:"url,omitempty" description:"where this issue is happened"` HttpTransactions []*HttpTransaction `json:"httpTransactions,omitempty" bson:"httpTransactions"` } type Vectors []*Vector
package issue import "net/http" type HttpBody struct { ContentEncoding string `json:"contentEncoding"` Content []byte `json:"content,string"` } type HttpEntity struct { Status string `json:"status"` Header http.Header `json:"header"` Body *HttpBody `json:"body,omitempty"` } type HttpTransaction struct { Id int `json:"id,omitempty"` Url string `json:"url"` Params []string `json:"params,omitempty"` Method string `json:"method"` Request *HttpEntity `json:"request,omitempty"` Response *HttpEntity `json:"response,omitempty"` } type Vector struct { Url string `json:"url,omitempty" description:"where this issue is happened"` HttpTransactions []*HttpTransaction `json:"httpTransactions,omitempty" bson:"httpTransactions"` } type Vectors []*Vector
0.1.8: Remove unnecessary strip, add finally for release tagger
# -*- coding: utf-8 -*- from malibu import command # noqa from malibu import config # noqa from malibu import database # noqa from malibu import design # noqa from malibu import text # noqa from malibu import util # noqa import subprocess __git_label__ = '' try: __git_label__ = subprocess.check_output( [ 'git', 'rev-parse', '--short', 'HEAD' ]) except (subprocess.CalledProcessError, IOError): __git_label__ = 'RELEASE' finally: __git_label__ = __git_label__.decode('utf-8').strip() __version__ = '0.1.8-7' __release__ = '{}-{}'.format(__version__, __git_label__) __doc__ = """ malibu is a collection of classes and utilities that make writing code a little bit easier and a little less tedious. The whole point of this library is to have a small codebase that could be easily reused across projects with nice, easily loadable chunks that can be used disjointly. """
# -*- coding: utf-8 -*- from malibu import command # noqa from malibu import config # noqa from malibu import database # noqa from malibu import design # noqa from malibu import text # noqa from malibu import util # noqa import subprocess __git_label__ = '' try: __git_label__ = subprocess.check_output( [ 'git', 'rev-parse', '--short', 'HEAD' ]) except (subprocess.CalledProcessError, IOError): __git_label__ = 'RELEASE' __version__ = '0.1.8-7' __release__ = '{}-{}'.format(__version__, __git_label__).strip('\n') __doc__ = """ malibu is a collection of classes and utilities that make writing code a little bit easier and a little less tedious. The whole point of this library is to have a small codebase that could be easily reused across projects with nice, easily loadable chunks that can be used disjointly. """
Remove mixer from the Backend API as it is independent
import logging from .current_playlist import CurrentPlaylistController from .library import LibraryController, BaseLibraryProvider from .playback import PlaybackController, BasePlaybackProvider from .stored_playlists import (StoredPlaylistsController, BaseStoredPlaylistsProvider) logger = logging.getLogger('mopidy.backends.base') class Backend(object): #: The current playlist controller. An instance of #: :class:`mopidy.backends.base.CurrentPlaylistController`. current_playlist = None #: The library controller. An instance of # :class:`mopidy.backends.base.LibraryController`. library = None #: The playback controller. An instance of #: :class:`mopidy.backends.base.PlaybackController`. playback = None #: The stored playlists controller. An instance of #: :class:`mopidy.backends.base.StoredPlaylistsController`. stored_playlists = None #: List of URI prefixes this backend can handle. uri_handlers = []
import logging from .current_playlist import CurrentPlaylistController from .library import LibraryController, BaseLibraryProvider from .playback import PlaybackController, BasePlaybackProvider from .stored_playlists import (StoredPlaylistsController, BaseStoredPlaylistsProvider) logger = logging.getLogger('mopidy.backends.base') class Backend(object): #: The current playlist controller. An instance of #: :class:`mopidy.backends.base.CurrentPlaylistController`. current_playlist = None #: The library controller. An instance of # :class:`mopidy.backends.base.LibraryController`. library = None #: The sound mixer. An instance of :class:`mopidy.mixers.BaseMixer`. mixer = None #: The playback controller. An instance of #: :class:`mopidy.backends.base.PlaybackController`. playback = None #: The stored playlists controller. An instance of #: :class:`mopidy.backends.base.StoredPlaylistsController`. stored_playlists = None #: List of URI prefixes this backend can handle. uri_handlers = []
Add the FocSITE annotation in the predefined fields factory
package com.foc.desc.parsers.predefinedFields; import java.util.HashMap; public class FocPredefinedFieldFactory { private HashMap<String, IFocPredefinedFieldType> map = null; private FocPredefinedFieldFactory(){ map = new HashMap<String, IFocPredefinedFieldType>(); put(new FTypeCODE()); put(new FTypeNAME()); put(new FTypeEXTERNAL_CODE()); put(new FTypeDESCRIPTION()); put(new FTypeCOMPANY()); put(new FTypeSITE()); put(new FTypeDATE()); put(new FTypeORDER()); put(new FTypeNOT_COMPLETED_YET()); put(new FTypeDEPRECATED()); put(new FTypeIS_SYSTEM()); } public void put(IFocPredefinedFieldType type) { map.put(type.getTypeName(), type); } public IFocPredefinedFieldType get(String typeName) { return map != null ? map.get(typeName) : null; } private static FocPredefinedFieldFactory instance = null; public static FocPredefinedFieldFactory getInstance(){ if(instance == null){ instance = new FocPredefinedFieldFactory(); } return instance; }; }
package com.foc.desc.parsers.predefinedFields; import java.util.HashMap; public class FocPredefinedFieldFactory { private HashMap<String, IFocPredefinedFieldType> map = null; private FocPredefinedFieldFactory(){ map = new HashMap<String, IFocPredefinedFieldType>(); put(new FTypeCODE()); put(new FTypeNAME()); put(new FTypeEXTERNAL_CODE()); put(new FTypeDESCRIPTION()); put(new FTypeCOMPANY()); put(new FTypeDATE()); put(new FTypeORDER()); put(new FTypeNOT_COMPLETED_YET()); put(new FTypeDEPRECATED()); put(new FTypeIS_SYSTEM()); } public void put(IFocPredefinedFieldType type) { map.put(type.getTypeName(), type); } public IFocPredefinedFieldType get(String typeName) { return map != null ? map.get(typeName) : null; } private static FocPredefinedFieldFactory instance = null; public static FocPredefinedFieldFactory getInstance(){ if(instance == null){ instance = new FocPredefinedFieldFactory(); } return instance; }; }
Rename `r` variable to `o` ...for `output`, which means we can use `r` for `*http.Request`.
package main import ( _ "expvar" "net/http" "os" "github.com/bmizerany/pat" "github.com/codegangsta/negroni" "github.com/meatballhat/negroni-logrus" "github.com/unrolled/render" ) func main() { Run() } func Run() { m := pat.New() n := negroni.New(negroni.NewRecovery(), negroni.NewStatic(http.Dir("assets"))) l := negronilogrus.NewMiddleware() o := render.New(render.Options{ Layout: "layout", }) n.Use(l) n.UseHandler(m) m.Get("/debug/vars", http.DefaultServeMux) m.Get("/", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { o.HTML(w, http.StatusOK, "index", "world") })) var addr string if len(os.Getenv("PORT")) > 0 { addr = ":" + os.Getenv("PORT") } else { addr = ":3000" } l.Logger.Infof("Listening on %s", addr) l.Logger.Fatal(http.ListenAndServe(addr, n)) }
package main import ( _ "expvar" "net/http" "os" "github.com/bmizerany/pat" "github.com/codegangsta/negroni" "github.com/meatballhat/negroni-logrus" "github.com/unrolled/render" ) func main() { Run() } func Run() { m := pat.New() n := negroni.New(negroni.NewRecovery(), negroni.NewStatic(http.Dir("assets"))) l := negronilogrus.NewMiddleware() r := render.New(render.Options{ Layout: "layout", }) n.Use(l) n.UseHandler(m) m.Get("/debug/vars", http.DefaultServeMux) m.Get("/", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { r.HTML(w, http.StatusOK, "index", "world") })) var addr string if len(os.Getenv("PORT")) > 0 { addr = ":" + os.Getenv("PORT") } else { addr = ":3000" } l.Logger.Infof("Listening on %s", addr) l.Logger.Fatal(http.ListenAndServe(addr, n)) }
Change test template assertion order to be consistent
from tests import ScraperTest from recipe_scrapers.template import Template class TestTemplateScraper(ScraperTest): scraper_class = Template def test_host(self): self.assertEqual("example.com", self.harvester_class.host()) def test_author(self): self.assertEqual("", self.harvester_class.author()) def test_title(self): self.assertEqual("", self.harvester_class.title()) def test_total_time(self): self.assertEqual(0, self.harvester_class.total_time()) def test_yields(self): self.assertEqual("", self.harvester_class.yields()) def test_image(self): self.assertEqual("", self.harvester_class.image()) def test_ingredients(self): self.assertCountEqual([], self.harvester_class.ingredients()) def test_instructions(self): self.assertEqual("", self.harvester_class.instructions()) def test_ratings(self): self.assertEqual(0, self.harvester_class.ratings())
from tests import ScraperTest from recipe_scrapers.template import Template class TestTemplateScraper(ScraperTest): scraper_class = Template def test_host(self): self.assertEqual("example.com", self.harvester_class.host()) def test_author(self): self.assertEqual("", self.harvester_class.author()) def test_title(self): self.assertEqual(self.harvester_class.title(), "") def test_total_time(self): self.assertEqual(0, self.harvester_class.total_time()) def test_yields(self): self.assertEqual("", self.harvester_class.yields()) def test_image(self): self.assertEqual("", self.harvester_class.image()) def test_ingredients(self): self.assertCountEqual([], self.harvester_class.ingredients()) def test_instructions(self): self.assertEqual("", self.harvester_class.instructions()) def test_ratings(self): self.assertEqual(0, self.harvester_class.ratings())
Test HTML handling in markdown
from django.test import TestCase from django.template import Context, Template class BlogTemplatetagsTestCase(TestCase): def test_md_as_html5(self): body = """# H1 heading **Paragraph** text <strong>html markup works</strong> ## H2 heading ~~~~{.python} if True: print("Some <b>Python</b> code in markdown") ~~~~ 1 First 2. Second * sub 3. Last""" expected = """<h1>H1 heading</h1> <p><strong>Paragraph</strong> text <strong>html markup works</strong></p> <h2>H2 heading</h2> <pre><code class="python">if True: print(&quot;Some &lt;b&gt;Python&lt;/b&gt; code in markdown&quot;) </code></pre> <p>1 First 2. Second * sub 3. Last</p>""" out = Template( "{% load markdown %}" "{{ body|md_as_html5 }}" ).render(Context({'body': body})) self.assertEqual(out, expected)
from django.test import TestCase from django.template import Context, Template class BlogTemplatetagsTestCase(TestCase): def test_md_as_html5(self): body = """# H1 heading **Paragraph** text ## H2 heading ~~~~{.python} if True: print("Some Python code in markdown") ~~~~ 1 First 2. Second * sub 3. Last""" expected = """<h1>H1 heading</h1> <p><strong>Paragraph</strong> text</p> <h2>H2 heading</h2> <pre><code class="python">if True: print(&quot;Some Python code in markdown&quot;) </code></pre> <p>1 First 2. Second * sub 3. Last</p>""" out = Template( "{% load markdown %}" "{{ body|md_as_html5 }}" ).render(Context({'body': body})) self.assertEqual(out, expected)
Fix file extension in file input
import React from 'react'; import style from './style.css'; import Modal from 'react-modal'; import H1 from '../h1'; import ControllButton from '../controllButton'; import SelectedPrinters from '../selectedPrinters'; let fileInput; function extractFileNameFromPath(path) {{ } return path.match(/[^\/\\]+$/); } function confirmButtonstate() { if (fileInput) { if (fileInput.value) { return false; } } return true; } function onUploadButtonClick(confirm) { if (fileInput && fileInput.value) { confirm(fileInput.files); } } const FileUploadModal = ({ isOpen, children, close, confirm, isUploadingFile, selectedPrinters }) => ( <Modal isOpen={isOpen} className={style.modal} overlayClassName={style.modalOverlay} onRequestClose={() => { close(); }}> <H1>File upload</H1> { isUploadingFile && <span>this is a loading spinner for now</span> } <SelectedPrinters selectedPrinters={selectedPrinters} /> <span className={style.fileName}>{fileInput && extractFileNameFromPath(fileInput.value)}</span> <ControllButton onClick={() => { fileInput.click(); }}>Load file</ControllButton> <input type="file" hidden open ref={(input) => { fileInput = input; }} accept=".gco"/> <ControllButton disabled={confirmButtonstate()} onClick={() => { onUploadButtonClick(confirm); }}>Upload</ControllButton> </Modal> ); export default FileUploadModal;
import React from 'react'; import style from './style.css'; import Modal from 'react-modal'; import H1 from '../h1'; import ControllButton from '../controllButton'; import SelectedPrinters from '../selectedPrinters'; let fileInput; function extractFileNameFromPath(path) {{ } return path.match(/[^\/\\]+$/); } function confirmButtonstate() { if (fileInput) { if (fileInput.value) { return false; } } return true; } function onUploadButtonClick(confirm) { if (fileInput && fileInput.value) { confirm(fileInput.files); } } const FileUploadModal = ({ isOpen, children, close, confirm, isUploadingFile, selectedPrinters }) => ( <Modal isOpen={isOpen} className={style.modal} overlayClassName={style.modalOverlay} onRequestClose={() => { close(); }}> <H1>File upload</H1> { isUploadingFile && <span>this is a loading spinner for now</span> } <SelectedPrinters selectedPrinters={selectedPrinters} /> <span className={style.fileName}>{fileInput && extractFileNameFromPath(fileInput.value)}</span> <ControllButton onClick={() => { fileInput.click(); }}>Load file</ControllButton> <input type="file" hidden open ref={(input) => { fileInput = input; }} accept=".gcode"/> <ControllButton disabled={confirmButtonstate()} onClick={() => { onUploadButtonClick(confirm); }}>Upload</ControllButton> </Modal> ); export default FileUploadModal;
Refactor RegisterView as subclass of LoginView They share much of the work, they should share the code as well
from django.shortcuts import render from django.views.generic.edit import FormView from . import forms # Create your views here. def logout(request): return render(request, 'passwordless/logout.html') def authn(request, token): return render(request, 'passwordless/authn.html') class LoginView(FormView): template_name = 'passwordless/login.html' form_class = forms.LoginForm success_url = '/' def form_valid(self, form): form.send_email() return super().form_valid(form) class RegisterView(LoginView): template_name = 'passwordless/register.html' form_class = forms.RegistrationForm def form_valid(self, form): form.create_user() return super().form_valid(form)
from django.shortcuts import render from django.views.generic.edit import FormView from . import forms # Create your views here. def logout(request): return render(request, 'passwordless/logout.html') def authn(request, token): return render(request, 'passwordless/authn.html') class LoginView(FormView): template_name = 'passwordless/login.html' form_class = forms.LoginForm success_url = '/' def form_valid(self, form): form.send_email() return super().form_valid(form) class RegisterView(FormView): template_name = 'passwordless/register.html' form_class = forms.RegistrationForm success_url = '/' def form_valid(self, form): form.create_user() form.send_email() return super().form_valid(form)
Correct again the pip URL
#!/usr/bin/env python """ setup.py file for afnumpy """ from distutils.core import setup from afnumpy import __version__ setup (name = 'afnumpy', version = __version__, author = "Filipe Maia", author_email = "filipe.c.maia@gmail.com", url = 'https://github.com/FilipeMaia/afnumpy', download_url = 'https://github.com/FilipeMaia/afnumpy/archive/'+__version__+'.tar.gz', keywords = ['arrayfire', 'numpy', 'GPU'], description = """A GPU-ready drop-in replacement for numpy""", packages = ["afnumpy", "afnumpy/core", "afnumpy/lib", "afnumpy/linalg"], install_requires=['arrayfire', 'numpy'], )
#!/usr/bin/env python """ setup.py file for afnumpy """ from distutils.core import setup from afnumpy import __version__ setup (name = 'afnumpy', version = __version__, author = "Filipe Maia", author_email = "filipe.c.maia@gmail.com", url = 'https://github.com/FilipeMaia/afnumpy', download_url = 'https://github.com/FilipeMaia/afnumpy/archive/'+__version__, keywords = ['arrayfire', 'numpy', 'GPU'], description = """A GPU-ready drop-in replacement for numpy""", packages = ["afnumpy", "afnumpy/core", "afnumpy/lib", "afnumpy/linalg"], install_requires=['arrayfire', 'numpy'], )
Throw a error instead of just logging it
resetDatabase = function (options) { if (process.env.NODE_ENV !== 'development' || !(process.env.IS_MIRROR || process.env.VELOCITY_TEST_PACKAGES) ) { throw new Error( 'resetDatabase is not allowed outside of a mirror. ' + 'Something has gone wrong.' ); } options = options || {}; var excludedCollections = ['system.indexes']; if (options.excludedCollections) { excludedCollections = excludedCollections.concat(options.excludedCollections); } var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db; var getCollections = Meteor.wrapAsync(db.collections, db); var collections = getCollections(); var appCollections = _.reject(collections, function (col) { return col.collectionName.indexOf('velocity') === 0 || excludedCollections.indexOf(col.collectionName) !== -1; }); _.each(appCollections, function (appCollection) { var remove = Meteor.wrapAsync(appCollection.remove, appCollection); remove({}); }); };
resetDatabase = function (options) { if (process.env.NODE_ENV !== 'development' || !(process.env.IS_MIRROR || process.env.VELOCITY_TEST_PACKAGES) ) { console.error( 'resetDatabase is not allowed outside of a mirror. ' + 'Something has gone wrong.' ); return; } options = options || {}; var excludedCollections = ['system.indexes']; if (options.excludedCollections) { excludedCollections = excludedCollections.concat(options.excludedCollections); } var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db; var getCollections = Meteor.wrapAsync(db.collections, db); var collections = getCollections(); var appCollections = _.reject(collections, function (col) { return col.collectionName.indexOf('velocity') === 0 || excludedCollections.indexOf(col.collectionName) !== -1; }); _.each(appCollections, function (appCollection) { var remove = Meteor.wrapAsync(appCollection.remove, appCollection); remove({}); }); };
Fix style for expected autoloader class
<?php /** * Generated autoloader for Zend\Di */ namespace ZendTest\Di\Generated; use function spl_autoload_register; use function spl_autoload_unregister; class Autoloader { private $registered = false; private $classmap = [ 'FooClass' => 'FooClass.php', 'Bar\\Class' => 'Bar/Class.php', ]; public function register() : void { if (! $this->registered) { spl_autoload_register($this); $this->registered = true; } } public function unregister() : void { if ($this->registered) { spl_autoload_unregister($this); $this->registered = false; } } public function load(string $class) : void { if (isset($this->classmap[$class])) { include __DIR__ . '/' . $this->classmap[$class]; } } public function __invoke(string $class) : void { $this->load($class); } }
<?php /** * Generated autoloader for Zend\Di */ namespace ZendTest\Di\Generated; use function spl_autoload_register; use function spl_autoload_unregister; class Autoloader { private $registered = false; private $classmap = [ 'FooClass' => 'FooClass.php', 'Bar\\Class' => 'Bar/Class.php', ]; public function register(): void { if (!$this->registered) { spl_autoload_register($this); $this->registered = true; } } public function unregister(): void { if ($this->registered) { spl_autoload_unregister($this); $this->registered = false; } } public function load(string $class): void { if (isset($this->classmap[$class])) { include __DIR__ . '/' . $this->classmap[$class]; } } public function __invoke(string $class): void { $this->load($class); } }
Remove line that causes a form feed upon every call to PrintController.output_epl.
# -*- coding: utf-8 -*- import logging import simplejson import os import base64 import openerp from ..helpers.zebra import zebra class PrintController(openerp.addons.web.http.Controller): _cp_path = '/printer_proxy' @openerp.addons.web.http.jsonrequest def output(self, request, format="epl2", **kwargs): '''Print the passed-in data. Corresponds to "printer_proxy.print"''' if format.lower() == "epl2": return self.output_epl2(request, **kwargs) return {'success': False, 'error': "Format '%s' not recognized" % format} def output_epl2(self, request, printer_name='zebra_python_unittest', data=[], raw=False, test=False): '''Print the passed-in EPL2 data.''' printer = zebra(printer_name) for datum in data: if not raw: datum = base64.b64decode(datum) printer.output(datum) return {'success': True}
# -*- coding: utf-8 -*- import logging import simplejson import os import base64 import openerp from ..helpers.zebra import zebra class PrintController(openerp.addons.web.http.Controller): _cp_path = '/printer_proxy' @openerp.addons.web.http.jsonrequest def output(self, request, format="epl2", **kwargs): '''Print the passed-in data. Corresponds to "printer_proxy.print"''' if format.lower() == "epl2": return self.output_epl2(request, **kwargs) return {'success': False, 'error': "Format '%s' not recognized" % format} def output_epl2(self, request, printer_name='zebra_python_unittest', data=[], raw=False, test=False): '''Print the passed-in EPL2 data.''' printer = zebra(printer_name) printer.setup(direct_thermal=True) for datum in data: if not raw: datum = base64.b64decode(datum) printer.output(datum) return {'success': True}
Disable bulk upload by not advertising it It has been reported broken on many instances. Disable it for now until it can be fixed. Signed-off-by: Vincent Petry <87e1f221a672a14a323e57bb65eaea19d3ed3804@nextcloud.com>
<?php /** * @copyright Copyright (c) 2016, ownCloud GmbH * * @author Thomas Müller <thomas.mueller@tmit.eu> * @author Louis Chemineau <louis@chmn.me> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OCA\DAV; use OCP\Capabilities\ICapability; class Capabilities implements ICapability { public function getCapabilities() { return [ 'dav' => [ 'chunking' => '1.0', // disabled because of https://github.com/nextcloud/desktop/issues/4243 // 'bulkupload' => '1.0', ] ]; } }
<?php /** * @copyright Copyright (c) 2016, ownCloud GmbH * * @author Thomas Müller <thomas.mueller@tmit.eu> * @author Louis Chemineau <louis@chmn.me> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OCA\DAV; use OCP\Capabilities\ICapability; class Capabilities implements ICapability { public function getCapabilities() { return [ 'dav' => [ 'chunking' => '1.0', 'bulkupload' => '1.0', ] ]; } }
Implement the ICWD interface in the main panel
package beaform.gui.main; import java.awt.BorderLayout; import java.awt.Component; import javax.swing.JPanel; import javax.swing.JScrollPane; import beaform.gui.InterchangableWindowDisplayer; import beaform.gui.debug.DebugUtilities; /** * This class represents the main panel where all views will work in. * * @author Steven Post * */ public final class MainPanel extends JPanel implements InterchangableWindowDisplayer { private static final long serialVersionUID = 1207348877338520359L; /** An inner panel for the actual content */ private final JPanel panel = new JPanel(new BorderLayout()); private final JScrollPane scrollPane = new JScrollPane(this.panel); public MainPanel() { super(new BorderLayout()); this.add(this.scrollPane); } @Override public void replaceActiveWindow(final Component comp) { if (this.panel.getComponentCount() > 0) { this.panel.remove(0); } this.panel.add(comp); this.panel.revalidate(); } public void enableDebugBorders() { DebugUtilities.drawBorders(this.panel); } }
package beaform.gui.main; import java.awt.BorderLayout; import java.awt.Component; import javax.swing.JPanel; import javax.swing.JScrollPane; import beaform.gui.debug.DebugUtilities; /** * This class represents the main panel where all views will work in. * * @author Steven Post * */ public final class MainPanel extends JPanel { private static final long serialVersionUID = 1207348877338520359L; /** An inner panel for the actual content */ private final JPanel panel = new JPanel(new BorderLayout()); private final JScrollPane scrollPane = new JScrollPane(this.panel); public MainPanel() { super(new BorderLayout()); this.add(this.scrollPane); } public void replaceActiveWindow(final Component comp) { if (this.panel.getComponentCount() > 0) { this.panel.remove(0); } this.panel.add(comp); this.panel.revalidate(); } public void enableDebugBorders() { DebugUtilities.drawBorders(this.panel); } }
Change version to prevent unleash from choking.
#!/usr/bin/env python # coding=utf8 import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='legitfs', version='0.3.dev1', description='A read-only FUSE-based filesystem allowing you to browse ' 'git repositories', long_description=read('README.rst'), keywords='git,fuse,filesystem,fs,read-only,readonly,legit,legitfs', author='Marc Brinkmann', author_email='git@marcbrinkmann.de', url='http://github.com/mbr/legitfs', license='MIT', packages=find_packages(exclude=['tests']), install_requires=['dulwich', 'fusepy', 'click', 'logbook'], entry_points={ 'console_scripts': [ 'legitfs = legitfs.cli:main', ] } )
#!/usr/bin/env python # coding=utf8 import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='legitfs', version='0.3dev', description='A read-only FUSE-based filesystem allowing you to browse ' 'git repositories', long_description=read('README.rst'), keywords='git,fuse,filesystem,fs,read-only,readonly,legit,legitfs', author='Marc Brinkmann', author_email='git@marcbrinkmann.de', url='http://github.com/mbr/legitfs', license='MIT', packages=find_packages(exclude=['tests']), install_requires=['dulwich', 'fusepy', 'click', 'logbook'], entry_points={ 'console_scripts': [ 'legitfs = legitfs.cli:main', ] } )
Send button component when clicked This allows a parent component to set properties on the button that it can then access in the click event. E.g.: `{{mdl-button action=toggleProperty propertyToToggle=myProp}}` Then in the parent component: ``` actions: { toggleProperty(button) { this.toggleProperty(button.get('propertyToToggle')); } } ```
// import Ember from 'ember'; import BaseComponent from './-base-toplevel-component'; import RippleSupport from '../mixins/ripple-support'; import layout from '../templates/components/mdl-button'; import computed from 'ember-new-computed'; export default BaseComponent.extend(RippleSupport, { primaryClassName: 'button', tagName: 'button', icon: null, isColored: true, isRaised: false, isFloating: false, isMiniFab: false, isAccent: false, _mdlComponent: null, 'for': null, _isIconMode: computed('icon', 'isFloating', { get() { return !this.get('isFloating') && this.get('icon'); } }), attributeBindings: ['disabled', 'for'], classNameBindings: [ 'isMiniFab:mdl-button--mini-fab', 'isAccent:mdl-button--accent', 'isRaised:mdl-button--raised', '_isIconMode:mdl-button--icon', 'isColored:mdl-button--colored', 'isFloating:mdl-button--fab'], layout, didInsertElement() { this._super(...arguments); let mdlbtn = new window.MaterialButton(this.get('element')); this.set('_mdlComponent', mdlbtn); }, click() { this.sendAction(this); } });
// import Ember from 'ember'; import BaseComponent from './-base-toplevel-component'; import RippleSupport from '../mixins/ripple-support'; import layout from '../templates/components/mdl-button'; import computed from 'ember-new-computed'; export default BaseComponent.extend(RippleSupport, { primaryClassName: 'button', tagName: 'button', icon: null, isColored: true, isRaised: false, isFloating: false, isMiniFab: false, isAccent: false, _mdlComponent: null, 'for': null, _isIconMode: computed('icon', 'isFloating', { get() { return !this.get('isFloating') && this.get('icon'); } }), attributeBindings: ['disabled', 'for'], classNameBindings: [ 'isMiniFab:mdl-button--mini-fab', 'isAccent:mdl-button--accent', 'isRaised:mdl-button--raised', '_isIconMode:mdl-button--icon', 'isColored:mdl-button--colored', 'isFloating:mdl-button--fab'], layout, didInsertElement() { this._super(...arguments); let mdlbtn = new window.MaterialButton(this.get('element')); this.set('_mdlComponent', mdlbtn); }, click() { this.sendAction(); } });
Integrate new packages. The code does not compile.
/* * Copyright (c) 2012 Malhar, Inc. * All Rights Reserved. */ package com.malhartech.stream.kafka; import com.malhartech.api.Sink; import com.malhartech.dag.Stream; import com.malhartech.dag.StreamConfiguration; import com.malhartech.dag.StreamContext; import com.malhartech.dag.Tuple; import kafka.javaapi.producer.Producer; /** * * @author Chetan Narsude <chetan@malhar-inc.com> */ public class KafkaOutputStream implements Stream, Sink { @Override public void setup(StreamConfiguration config) { Producer producer; throw new UnsupportedOperationException("Not supported yet."); } @Override public void setContext(StreamContext context) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void teardown() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void doSomething(Tuple t) { throw new UnsupportedOperationException("Not supported yet."); } @Override public StreamContext getContext() { throw new UnsupportedOperationException("Not supported yet."); } public boolean hasFinished() { throw new UnsupportedOperationException("Not supported yet."); } public void activate() { throw new UnsupportedOperationException("Not supported yet."); } }
/* * Copyright (c) 2012 Malhar, Inc. * All Rights Reserved. */ package com.malhartech.stream.kafka; import com.malhartech.dag.Sink; import com.malhartech.dag.Stream; import com.malhartech.dag.StreamConfiguration; import com.malhartech.dag.StreamContext; import com.malhartech.dag.Tuple; import kafka.javaapi.producer.Producer; /** * * @author Chetan Narsude <chetan@malhar-inc.com> */ public class KafkaOutputStream implements Stream, Sink { @Override public void setup(StreamConfiguration config) { Producer producer; throw new UnsupportedOperationException("Not supported yet."); } @Override public void setContext(StreamContext context) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void teardown() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void doSomething(Tuple t) { throw new UnsupportedOperationException("Not supported yet."); } @Override public StreamContext getContext() { throw new UnsupportedOperationException("Not supported yet."); } public boolean hasFinished() { throw new UnsupportedOperationException("Not supported yet."); } public void activate() { throw new UnsupportedOperationException("Not supported yet."); } }
Remove the other bit of ES6
'use strict' var IS_BROWSER = require('is-browser'); if (!IS_BROWSER) { var wtfnode = require('wtfnode'); } var Suite = require('./lib/suite'); var defaultSuite = new Suite(); defaultSuite.addLogging(); defaultSuite.addExit(); var runTriggered = false; function it(name, fn, options) { defaultSuite.addTest(name, fn, options); if (!runTriggered) { runTriggered = true; setTimeout(function () { defaultSuite.run().done(function () { if (!IS_BROWSER) { setTimeout(function () { wtfnode.dump(); }, 5000).unref() } }); }, 0); } } function run(fn, options) { defaultSuite.addCode(fn, options); } module.exports = it module.exports.run = run; module.exports.disableColors = defaultSuite.disableColors.bind(defaultSuite); module.exports.on = defaultSuite.on.bind(defaultSuite); module.exports.Suite = Suite;
'use strict' var IS_BROWSER = require('is-browser'); if (!IS_BROWSER) { var wtfnode = require('wtfnode'); } var Suite = require('./lib/suite'); var defaultSuite = new Suite(); defaultSuite.addLogging(); defaultSuite.addExit(); var runTriggered = false; function it(name, fn, options) { defaultSuite.addTest(name, fn, options); if (!runTriggered) { runTriggered = true; setTimeout(function () { defaultSuite.run().done(function () { if (!IS_BROWSER) { setTimeout(() => { wtfnode.dump(); }, 5000).unref() } }); }, 0); } } function run(fn, options) { defaultSuite.addCode(fn, options); } module.exports = it module.exports.run = run; module.exports.disableColors = defaultSuite.disableColors.bind(defaultSuite); module.exports.on = defaultSuite.on.bind(defaultSuite); module.exports.Suite = Suite;
Add config merging for laravel 5
<?php namespace Alexsoft\LaravelHashids; use Hashids\Hashids; use Illuminate\Support\ServiceProvider; class LaravelHashidsServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('alexsoft/laravel-hashids'); } /** * Register the service provider. * * @return void */ public function register() { $this->app->bind('Hashids\HashGenerator', function($app) { return new Hashids( $app['config']['app.key'], $app['config']['laravel-hashids::length'], $app['config']['laravel-hashids::alphabet'] ); }); $this->mergeConfigFrom('laravel-hashids', __DIR__.'/config/config.php'); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['laravel-hashids']; } }
<?php namespace Alexsoft\LaravelHashids; use Hashids\Hashids; use Illuminate\Support\ServiceProvider; class LaravelHashidsServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('alexsoft/laravel-hashids'); } /** * Register the service provider. * * @return void */ public function register() { $this->app->bind('Hashids\HashGenerator', function($app) { return new Hashids( $app['config']['app.key'], $app['config']['laravel-hashids::length'], $app['config']['laravel-hashids::alphabet'] ); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['laravel-hashids']; } }
Add Record Logic to Recall Responses
var FileSystem = require('fs'); var RequestHash = require('./request_hash'); var CacheClient = function(cacheDir) { this.cacheDir = cacheDir; } CacheClient.prototype.isCached = function (request) { var self = this; var mode = FileSystem.F_OK | FileSystem.R_OK | FileSystem.W_OK; var error; try { error = FileSystem.accessSync(self.path(request), mode); return true; } catch (error) { return false; } } CacheClient.prototype.fetch = function (request) { var self = this; return new Promise(function(resolve, reject) { FileSystem.readFile(self.path(request), function (err, data) { if (err) { reject(err); } else { resolve(data); } }); }); } CacheClient.prototype.record = function (request, response) { var self = this; return new Promise(function(resolve, reject) { FileSystem.writeFile(self.path(request), response, function (err) { if (err) { reject(err); } else { resolve(response); } }); }); } CacheClient.prototype.path = function (request) { var requestHash = new RequestHash(request).toString(); return this.cacheDir + '/' + requestHash; } module.exports = CacheClient
var FileSystem = require('fs'); var RequestHash = require('./request_hash'); var CacheClient = function(cacheDir) { this.cacheDir = cacheDir; } CacheClient.prototype.isCached = function (request) { var self = this; return new Promise(function(resolve, reject) { var mode = FileSystem.F_OK | FileSystem.R_OK | FileSystem.W_OK; FileSystem.access(self.path(request), mode, function (error) { if (error) { // No Access, File Does Not Exist. resolve(false); } else { // File Exists and is accessable. resolve(true); } }); }); } CacheClient.prototype.fetch = function (request) { var self = this; return new Promise(function(resolve, reject) { FileSystem.readFile(self.path(request), function (err, data) { if (err) { reject(err); } else { resolve(data); } }); }); } CacheClient.prototype.path = function (request) { var requestHash = new RequestHash(request).toString(); return this.cacheDir + '/' + requestHash; } module.exports = CacheClient
Switch to a uniquely random set of numbers, so there are no winners drawn twice
<?php namespace Raffle; class RandomService { /** * Base URL */ const BASE_URL = 'http://www.random.org/integer-sets/?sets=1&min=%d&max=%d&num=%d&order=random&format=plain&rnd=new'; /** * Retrieve a block of random numbers. * * @param int $min Minimum amount. * @param int $max Maximum amount. * @param int $count How many numbers. * @return array */ public function getRandomNumbers($min, $max, $count) { // Construct the URL $url = sprintf(self::BASE_URL, $min, $max, $count); // Fetch the numbers $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($ch); // Decode data and return return explode(" ", trim($data)); } }
<?php namespace Raffle; class RandomService { /** * Base URL */ const BASE_URL = 'http://www.random.org/integers/?min=%d&max=%d&num=%d&col=1&base=10&format=plain&rnd=new'; /** * Retrieve a block of random numbers. * * @param int $min Minimum amount. * @param int $max Maximum amount. * @param int $count How many numbers. * @return array */ public function getRandomNumbers($min, $max, $count) { // Construct the URL $url = sprintf(self::BASE_URL, $min, $max, $count); // Fetch the numbers $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($ch); // Decode data and return return explode("\n", trim($data)); } }
Update to current valid strikethrough tags The `strike` tag is no longer a valid HTML tag. See https://www.w3schools.com/tags/tag_strike.asp Two very similar tags are its replacement, `s` and `del` -- and `del` has a corresponding `ins` tag. See https://www.w3schools.com/tags/tag_del.asp and https://www.w3schools.com/tags/tag_s.asp So take out the old `strike` tag and add in `s`, `del` and `ins`.
import sanitizeHtml from 'sanitize-html'; import { Utils } from '../modules'; import { throwError } from './errors.js'; Utils.sanitize = function(s) { return sanitizeHtml(s, { allowedTags: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 's', 'del', 'ins', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre', 'img' ] }); }; Utils.performCheck = (operation, user, checkedObject, context, documentId, operationName, collectionName) => { if (!operation) { throwError({ id: 'app.no_permissions_defined', data: { documentId, operationName } }); } if (!checkedObject) { throwError({ id: 'app.document_not_found', data: { documentId, operationName } }); } if (!operation(user, checkedObject, context)) { throwError({ id: 'app.operation_not_allowed', data: { documentId, operationName } }); } }; export { Utils };
import sanitizeHtml from 'sanitize-html'; import { Utils } from '../modules'; import { throwError } from './errors.js'; Utils.sanitize = function(s) { return sanitizeHtml(s, { allowedTags: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre', 'img' ] }); }; Utils.performCheck = (operation, user, checkedObject, context, documentId, operationName, collectionName) => { if (!operation) { throwError({ id: 'app.no_permissions_defined', data: { documentId, operationName } }); } if (!checkedObject) { throwError({ id: 'app.document_not_found', data: { documentId, operationName } }); } if (!operation(user, checkedObject, context)) { throwError({ id: 'app.operation_not_allowed', data: { documentId, operationName } }); } }; export { Utils };
Remove client cert stuff that never mattered
if (Meteor.isServer) { Meteor.startup(function () { // Validate that the config file contains the data we need. validateSettings(); // Create our DNS zone for PowerDNS, if necessary. mysqlQuery = createWrappedQuery(); createDomainIfNeeded(mysqlQuery); Router.map(function() { this.route('register', { path: '/register', where: 'server', action: function() { doRegister(this.request, this.response); } }); this.route('update', { path: '/update', where: 'server', action: function() { doUpdate(this.request, this.response); } }); }); }); }
if (Meteor.isServer) { Meteor.startup(function () { // Validate that the config file contains the data we need. validateSettings(); // Create our DNS zone for PowerDNS, if necessary. mysqlQuery = createWrappedQuery(); createDomainIfNeeded(mysqlQuery); Router.map(function() { this.route('register', { path: '/register', where: 'server', action: function() { doRegister(this.request, this.response); } }); var clientCertificateAuth = Meteor.npmRequire('client-certificate-auth'); function checkAuth(cert) { console.log(cert.fingerprint); } WebApp.connectHandlers.use(clientCertificateAuth(checkAuth)); this.route('update', { path: '/update', where: 'server', action: function() { doUpdate(this.request, this.response); } }); }); }); }
Add minimized version of updated script.
melange.templates.inherit(function(){function f(){var a={mapTypeId:google.maps.MapTypeId.ROADMAP,mapTypeControl:true,panControl:true,zoomControl:true};a=new google.maps.Map(jQuery("#"+d)[0],a);var e=new google.maps.LatLng(b,c);a.setZoom(g);a.setCenter(e);marker=new google.maps.Marker({position:e,draggable:false});marker.setMap(a)}var d="profile_map",b=0,c=0,g=13;jQuery(function(){b=jQuery("#latitude").text();c=jQuery("#longitude").text();if(b!==""&&c!==""){jQuery("#gsoc_profile_show-contact-info-private").append("<div id='"+ d+'\' style="width: 100%"></div>');melange.loadGoogleApi("maps","3",{other_params:"sensor=false"},f)}})});
melange.templates.inherit(function(){function k(){c=jQuery(d).text();e=jQuery(f).text()}function l(){var a={mapTypeId:google.maps.MapTypeId.ROADMAP,mapTypeControl:true,panControl:true,zoomControl:true},g=m,h=false;b=new google.maps.Map(jQuery("#"+i)[0],a);if(jQuery(d).text()!==""&&jQuery(f).text()!==""){k();g=n;h=true}a=new google.maps.LatLng(c,e);b.setZoom(g);b.setCenter(a);j=new google.maps.Marker({position:a,draggable:false});h&&j.setMap(b)}var b,j,c=0,e=0,m=1,n=13,i="profile_map",d="#latitude", f="#longitude";jQuery(function(){jQuery("#gsoc_profile_show-contact-info-private").append("<div id='"+i+'\' style="width: 100%"></div>');melange.loadGoogleApi("maps","3",{other_params:"sensor=false"},l)})});
Fix with platform dependent line separator
package org.extendedCLI.ioAdapters; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; @SuppressWarnings("javadoc") public class PrintWriterAdapterTest { private OutputStream output; private PrintWriterAdapter printStreamAdapter; @Before public void setUp() { output = new ByteArrayOutputStream(); printStreamAdapter = new PrintWriterAdapter(new PrintWriter(output)); } @Test public void testPrintlnPrintsToStdOut() { final String lineBreaker = System.getProperty("line.separator"); final String expected = "test"; printStreamAdapter.println(expected); printStreamAdapter.flush(); assertEquals(expected + lineBreaker, output.toString()); } @Test public final void testPrintPrintsToStdOut() { final String expected = "test"; printStreamAdapter.print(expected); printStreamAdapter.flush(); assertEquals(expected, output.toString()); } }
package org.extendedCLI.ioAdapters; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; @SuppressWarnings("javadoc") public class PrintWriterAdapterTest { private OutputStream output; private PrintWriterAdapter printStreamAdapter; @Before public void setUp() { output = new ByteArrayOutputStream(); printStreamAdapter = new PrintWriterAdapter(new PrintWriter(output)); } @Test public void testPrintlnPrintsToStdOut() { final String expected = "test"; printStreamAdapter.println(expected); printStreamAdapter.flush(); assertEquals(expected + "\r\n", output.toString()); } @Test public final void testPrintPrintsToStdOut() { final String expected = "test"; printStreamAdapter.print(expected); printStreamAdapter.flush(); assertEquals(expected, output.toString()); } }
Add interface for Datastore items
/* * Copyright 2020 Google 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 * * https: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.google.vinet.data; /** * Any class that can be stored and loaded from Datastore. The implementing class must also provide * a constructor for loading an object from a Datastore entity. */ public interface Datastoreable { /** * Store this class instance to Datastore. <<<<<<< HEAD * * @throws IllegalArgumentException If the entity was incomplete. * @throws java.util.ConcurrentModificationException If the entity group to which the entity belongs was modified concurrently. * @throws com.google.appengine.api.datastore.DatastoreFailureException If any other datastore error occurs. ======= >>>>>>> Add interface for Datastore items */ void toDatastore(); }
/* * Copyright 2020 Google 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 * * https: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.google.vinet.data; /** * Any class that can be stored and loaded from Datastore. The implementing class must also provide * a constructor for loading an object from a Datastore entity. */ public interface Datastoreable { /** * Store this class instance to Datastore. * * @throws IllegalArgumentException If the entity was incomplete. * @throws java.util.ConcurrentModificationException If the entity group to which the entity belongs was modified concurrently. * @throws com.google.appengine.api.datastore.DatastoreFailureException If any other datastore error occurs. */ void toDatastore(); }
Update default options to match new queue-promise API
// @flow import mixin from "merge-descriptors"; import EventEmitter from "events"; import SpiderQueue from "./queue/promise"; import SpiderRouter from "./routing/router"; import SpiderRequest from "./routing/request"; import SpiderResponse from "./routing/response"; /** * @param {string} base * @param {Object} options * @return {Object} */ function createCrawler(base: string, options: Object = {}): Object { if (typeof base !== "string") { throw new Error(`Base must be a string, not ${typeof base}`); } const config: Object = { interval: 250, concurrent: 10, ...options }; const crawler: Object = { base: base, opts: config, req: SpiderRequest, res: SpiderResponse }; // Glues all the components together: mixin(crawler, SpiderQueue, false); mixin(crawler, SpiderRouter, false); mixin(crawler, EventEmitter.prototype, false); return crawler; } module.exports = createCrawler; module.exports.request = SpiderRequest; module.exports.response = SpiderResponse;
// @flow import mixin from "merge-descriptors"; import EventEmitter from "events"; import SpiderQueue from "./queue/promise"; import SpiderRouter from "./routing/router"; import SpiderRequest from "./routing/request"; import SpiderResponse from "./routing/response"; /** * @param {string} base * @param {Object} options * @return {Object} */ function createCrawler(base: string, options: Object = {}): Object { if (typeof base !== "string") { throw new Error(`Base must be a string, not ${typeof base}`); } const config: Object = { interval: 250, concurrency: 10, ...options }; const crawler: Object = { base: base, opts: config, req: SpiderRequest, res: SpiderResponse }; // Glues all the components together: mixin(crawler, SpiderQueue, false); mixin(crawler, SpiderRouter, false); mixin(crawler, EventEmitter.prototype, false); return crawler; } module.exports = createCrawler; module.exports.request = SpiderRequest; module.exports.response = SpiderResponse;
Remove scipy and numpy deps
from setuptools import setup from codecs import open from os import path # Open up settings here = path.abspath(path.dirname(__file__)) about = {} with open(path.join(here, "README.rst"), encoding="utf-8") as file: long_description = file.read() with open(path.join(here, "malaffinity", "__about__.py")) as file: exec(file.read(), about) settings = { "name": about["__title__"], "version": about["__version__"], "description": about["__summary__"], "long_description": long_description, "url": about["__uri__"], "author": about["__author__"], "author_email": about["__email__"], "license": about["__license__"], "classifiers": [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Topic :: Software Development", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3" ], "keywords": "affinity mal myanimelist", "packages": ["malaffinity"], "install_requires": [ "bs4", "requests" ] } setup( **settings )
from setuptools import setup from codecs import open from os import path # Open up settings here = path.abspath(path.dirname(__file__)) about = {} with open(path.join(here, "README.rst"), encoding="utf-8") as file: long_description = file.read() with open(path.join(here, "malaffinity", "__about__.py")) as file: exec(file.read(), about) settings = { "name": about["__title__"], "version": about["__version__"], "description": about["__summary__"], "long_description": long_description, "url": about["__uri__"], "author": about["__author__"], "author_email": about["__email__"], "license": about["__license__"], "classifiers": [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Topic :: Software Development", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3" ], "keywords": "affinity mal myanimelist", "packages": ["malaffinity"], "install_requires": [ "bs4", "numpy", "requests", "scipy" # I tried getting rid of this, but numpy is shit so [](#yuishrug) ] } setup( **settings )
Add guidelines for connecting to mongolab
var express = require('express'); var mongoose = require('mongoose'); var app = express(); // ======================================== // Connect to local mongodb named "bolt" // Uncomment line 9 to use a local database // Be sure to re-comment line 9 when submitting PR // mongoose.connect('mongodb://localhost/bolt'); // ======================================== // ======================================== // Connect to mongolab database // Please replace this line with your own // mongolab link mongoose.connect('mongodb://heroku_l3g4r0kp:61docmam4tnk026c51bhc5hork@ds029605.mongolab.com:29605/heroku_l3g4r0kp'); // ======================================== require('./config/middleware.js')(app, express); require('./config/routes.js')(app, express); // start listening to requests on port 8000 var port = Number(process.env.PORT || 8000); app.listen(port, function () { console.log(`server listening on port ${port}`); }); // export our app for testing and flexibility, required by index.js module.exports = app; //test
var express = require('express'); var mongoose = require('mongoose'); var app = express(); // connect to mongo database named "bolt" // uncomment this line to use a local database // be sure to re-comment this line when submitting PR // mongoose.connect('mongodb://localhost/bolt'); mongoose.connect('mongodb://heroku_l3g4r0kp:61docmam4tnk026c51bhc5hork@ds029605.mongolab.com:29605/heroku_l3g4r0kp'); require('./config/middleware.js')(app, express); require('./config/routes.js')(app, express); // start listening to requests on port 8000 var port = Number(process.env.PORT || 8000); app.listen(port, function () { console.log(`server listening on port ${port}`); }); // export our app for testing and flexibility, required by index.js module.exports = app; //test
Correct version for deploy to GAE
//Command to run test version: //goapp serve app.yaml //Command to deploy/update application: //goapp deploy -application golangnode0 -version 0 package main import ( "fmt" "net/http" ) func helloWorld(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") } func startPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, test application started.\n - /helloworld - show title page\n - /showinfo - show information about this thing") } func showInfo(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Inforamtion page for test project.\nLanguage - Go\nPlatform - Google Application Engine") } func init() { http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) //Wrong code for App Enine - server cant understand what it need to show //http.ListenAndServe(":80", nil) } /* func main() { fmt.Println("Hello, test server started on 80 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing") http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) http.ListenAndServe(":8080", nil) } */
//Command to run test version: //goapp serve app.yaml //Command to deploy/update application: //goapp deploy -application golangnode0 -version 0 package main import ( "fmt" "net/http" ) func helloWorld(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") } func startPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, test application started.\n - /helloworld - show title page\n - /showinfo - show information about this thing") } func showInfo(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Inforamtion page for test project.\nLanguage - Go\nPlatform - Google Application Engine") } func init() { http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) //Wrong code for App Enine - server cant understand what it need to show //http.ListenAndServe(":80", nil) } /* func main() { fmt.Println("Hello, test server started on 80 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing") http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) http.ListenAndServe(":80", nil) } */
Fix "split" title when it's more than 2 words
var fs = require('fs'); var path = require('path'); var handlebars = require('handlebars'); function compileTemplate(hbsFile) { var src = fs.readFileSync(path.join(__dirname, '..', 'templates', hbsFile)); return handlebars.compile(src.toString()); } var galleryTemplate = compileTemplate('gallery.hbs'); exports.gallery = function(list, active, title, css) { var links = list.map(function(item) { return { name: item.name, url: item.name + '.html', active: (item === active) }; }); var titleParts = title.split(' '); return galleryTemplate({ css: css, links: links, gallery: active, title: titleParts[0], subtitle: titleParts.slice(1).join(' ') }); };
var fs = require('fs'); var path = require('path'); var handlebars = require('handlebars'); function compileTemplate(hbsFile) { var src = fs.readFileSync(path.join(__dirname, '..', 'templates', hbsFile)); return handlebars.compile(src.toString()); } var galleryTemplate = compileTemplate('gallery.hbs'); exports.gallery = function(list, active, title, css) { var links = list.map(function(item) { return { name: item.name, url: item.name + '.html', active: (item === active) }; }); var titleParts = title.split(' '); return galleryTemplate({ css: css, links: links, gallery: active, title: titleParts[0], subtitle: titleParts.slice(1) }); };
Fix printing of payment methods
<?php namespace Scat; class Payment extends \Model { public static $methods= array( 'cash' => "Cash", 'change' => "Change", 'credit' => "Credit Card", 'square' => "Square", 'stripe' => "Stripe", 'gift' => "Gift Card", 'check' => "Check", 'dwolla' => "Dwolla", 'paypal' => "PayPal", 'amazon' => "Amazon Pay", 'eventbrite' => "Eventbrite", 'discount' => "Discount", 'bad' => "Bad Debt", 'donation' => "Donation", 'withdrawal' => "Withdrawal", 'internal' => "Internal", ); function pretty_method() { switch ($this->method) { case 'credit': return 'Paid by ' . $this->cc_type . ' ending in ' . $this->cc_lastfour; case 'discount': return sprintf("Discount (%d%%)", $this->discount); case 'change': return 'Change'; default: return 'Paid by ' . self::$methods[$this->method]; } } }
<?php namespace Scat; class Payment extends \Model { public static $methods= array( 'cash' => "Cash", 'change' => "Change", 'credit' => "Credit Card", 'square' => "Square", 'stripe' => "Stripe", 'gift' => "Gift Card", 'check' => "Check", 'dwolla' => "Dwolla", 'paypal' => "PayPal", 'amazon' => "Amazon Pay", 'eventbrite' => "Eventbrite", 'discount' => "Discount", 'bad' => "Bad Debt", 'donation' => "Donation", 'withdrawal' => "Withdrawal", 'internal' => "Internal", ); function pretty_method() { switch ($this->method) { case 'credit': return 'Paid by ' . $this->cc_type . ' ending in ' . $this->cc_lastfour; case 'discount': return sprintf("Discount (%d%%)", $this->discount); case 'change': return 'Change'; default: return 'Paid by ' . $this::methods($this->method); } } }
Make a -1 value for "No"
var helpful_yes = document.querySelector( '.helpful_yes' ); var helpful_no = document.querySelector( '.helpful_no' ); var helpful_text = document.querySelector( '.helpful__question' ); function thanks(){ helpful_text.innerHTML = "Thanks for your response and helping us improve our content."; helpful_no.remove(); helpful_yes.remove(); } AddEvent( helpful_yes, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful', eventAction: window.location.href, eventLabel: 'helpful: yes', eventValue: 1 }); }); AddEvent( helpful_no, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful', eventAction: window.location.href, eventLabel: 'helpful: no', eventValue: -1 }); });
var helpful_yes = document.querySelector( '.helpful_yes' ); var helpful_no = document.querySelector( '.helpful_no' ); var helpful_text = document.querySelector( '.helpful__question' ); function thanks(){ helpful_text.innerHTML = "Thanks for your response and helping us improve our content."; helpful_no.remove(); helpful_yes.remove(); } AddEvent( helpful_yes, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful', eventAction: window.location.href, eventLabel: 'helpful: yes', eventValue: 1 }); }); AddEvent( helpful_no, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful', eventAction: window.location.href, eventLabel: 'helpful: no', eventValue: 0 }); });
Add the sitemap overlay route
<?php defined('C5_EXECUTE') or die("Access Denied."); /** * @var $router \Concrete\Core\Routing\Router */ $router->all('/arrange_blocks/', 'Page\ArrangeBlocks::arrange'); $router->all('/check_in/{cID}/{token}', 'Page::exitEditMode'); $router->all('/create/{ptID}', 'Page::create'); $router->all('/create/{ptID}/{parentID}', 'Page::create'); $router->all('/get_json', 'Page::getJSON'); $router->all('/multilingual/assign', 'Page\Multilingual::assign'); $router->all('/multilingual/create_new', 'Page\Multilingual::create_new'); $router->all('/multilingual/ignore', 'Page\Multilingual::ignore'); $router->all('/multilingual/unmap', 'Page\Multilingual::unmap'); $router->all('/select_sitemap', 'Page\SitemapSelector::view'); $router->all('/sitemap_data', 'Page\SitemapData::view'); $router->all('/sitemap_overlay', '\Concrete\Controller\Element\Dashboard\Sitemap\SitemapOverlay::view');
<?php defined('C5_EXECUTE') or die("Access Denied."); /** * @var $router \Concrete\Core\Routing\Router */ $router->all('/arrange_blocks/', 'Page\ArrangeBlocks::arrange'); $router->all('/check_in/{cID}/{token}', 'Page::exitEditMode'); $router->all('/create/{ptID}', 'Page::create'); $router->all('/create/{ptID}/{parentID}', 'Page::create'); $router->all('/get_json', 'Page::getJSON'); $router->all('/multilingual/assign', 'Page\Multilingual::assign'); $router->all('/multilingual/create_new', 'Page\Multilingual::create_new'); $router->all('/multilingual/ignore', 'Page\Multilingual::ignore'); $router->all('/multilingual/unmap', 'Page\Multilingual::unmap'); $router->all('/select_sitemap', 'Page\SitemapSelector::view'); $router->all('/sitemap_data', 'Page\SitemapData::view');
Remove name param from constructor Break QueryBuilder::forge() method instantiating objects.
<?php namespace App\Models; class Player extends \Pragma\ORM\Model { const GENOME_HOST = 0; const GENOME_NORMAL = 1; const GENOME_RESISTANT = 2; private $name; private $keyId; private $genome; private $role; private $paralysed; private $mutated; private $alive; public function __construct() { return parent::__construct('player'); } public function setGenome($genome) { if (!in_array($genome, [self::GENOME_HOST, self::GENOME_RESISTANT, self::GENOME_NORMAL])) { $genome = self::GENOME_NORMAL; } $this->genome = $genome; } public function mutate() { if ($this->genome != self::GENOME_RESISTANT) { $this->mutated = 1; } return $this->mutated; } public function cure() { if ($this->genome != self::GENOME_HOST) { $this->mutated = 0; } return !$this->mutated; } }
<?php namespace App\Models; class Player extends \Pragma\ORM\Model { const GENOME_HOST = 0; const GENOME_NORMAL = 1; const GENOME_RESISTANT = 2; private $name; private $keyId; private $genome; private $role; private $paralysed; private $mutated; private $alive; public function __construct($name) { return parent::__construct('player'); $this->name = $name; } public function setGenome($genome) { if (!in_array($genome, [self::GENOME_HOST, self::GENOME_RESISTANT, self::GENOME_NORMAL])) { $genome = self::GENOME_NORMAL; } $this->genome = $genome; } public function mutate() { if ($this->genome != self::GENOME_RESISTANT) { $this->mutated = 1; } return $this->mutated; } public function cure() { if ($this->genome != self::GENOME_HOST) { $this->mutated = 0; } return !$this->mutated; } }
Set the version 1.9 of phantomjs as the 2 is not compatible yet
var isbin = require('isbin'); var logger = require('chip')(); var prequire = require('parent-require'); module.exports = function(launchPhantom){ 'use strict'; isbin('phantomjs', function(exists) { if (!exists){ try{ launchPhantom(prequire('phantomjs').path); } catch(e){ var npm = require('npm'); npm.load(npm.config, function (err) { if (err) { logger.error(err); } npm.commands.install(['phantomjs@1.9.19'], function (err) { if (err) { logger.error(err); } launchPhantom(prequire('phantomjs').path); }); npm.on('log', function (message) { logger.info(message); }); }); } } else { launchPhantom(); } }); };
var isbin = require('isbin'); var logger = require('chip')(); var prequire = require('parent-require'); module.exports = function(launchPhantom){ 'use strict'; isbin('phantomjs', function(exists) { if (!exists){ try{ launchPhantom(prequire('phantomjs').path); } catch(e){ var npm = require('npm'); npm.load(npm.config, function (err) { if (err) { logger.error(err); } npm.commands.install(['phantomjs'], function (err) { if (err) { logger.error(err); } launchPhantom(prequire('phantomjs').path); }); npm.on('log', function (message) { logger.info(message); }); }); } } else { launchPhantom(); } }); };
Remove Article date (until it became true)
import React from 'react' function getColorFromId(id) { const hue = (id * 97) % 360 return `hsl(${hue}, 32%, 68%)` } const Article = ({ link, title, id }) => ( <div className='card'> <div className='card-img-top' style={{height: '5em', background: getColorFromId(id)}} alt='Card image cap' /> <div className='card-block'> <h4 className='card-title'> <a href={link}> {title} </a> </h4> <p className='card-text'> <small className='text-muted'></small> </p> </div> </div> ) export default Article
import React from 'react' function getColorFromId(id) { const hue = (id * 97) % 360 return `hsl(${hue}, 32%, 68%)` } const Article = ({ link, title, id }) => ( <div className='card'> <div className='card-img-top' style={{height: '5em', background: getColorFromId(id)}} alt='Card image cap' /> <div className='card-block'> <h4 className='card-title'> <a href={link}> {title} </a> </h4> <p className='card-text'> <small className='text-muted'>06 de noviembre de 2016</small> </p> </div> </div> ) export default Article
Make the test more robust
package logrus import ( "bytes" "errors" "testing" ) func TestQuoting(t *testing.T) { tf := &TextFormatter{DisableColors: true} checkQuoting := func(q bool, value interface{}) { b, _ := tf.Format(WithField("test", value)) idx := bytes.Index(b, ([]byte)("test=")) cont := bytes.Contains(b[idx+5:], []byte{'"'}) if cont != q { if q { t.Errorf("quoting expected for: %#v", value) } else { t.Errorf("quoting not expected for: %#v", value) } } } checkQuoting(false, "abcd") checkQuoting(false, "v1.0") checkQuoting(true, "/foobar") checkQuoting(true, "x y") checkQuoting(true, "x,y") checkQuoting(false, errors.New("invalid")) checkQuoting(true, errors.New("invalid argument")) }
package logrus import ( "bytes" "errors" "testing" ) func TestQuoting(t *testing.T) { tf := new(TextFormatter) checkQuoting := func(q bool, value interface{}) { b, _ := tf.Format(WithField("test", value)) idx := bytes.LastIndex(b, []byte{'='}) cont := bytes.Contains(b[idx:], []byte{'"'}) if cont != q { if q { t.Errorf("quoting expected for: %#v", value) } else { t.Errorf("quoting not expected for: %#v", value) } } } checkQuoting(false, "abcd") checkQuoting(false, "v1.0") checkQuoting(true, "/foobar") checkQuoting(true, "x y") checkQuoting(true, "x,y") checkQuoting(false, errors.New("invalid")) checkQuoting(true, errors.New("invalid argument")) }
Fix the name of a variable so it correctly reflects its purpose
Geolocation = (function() { var get = function(element) { var missing = function() {element.innerHTML = "MISSING.";}; var error = function() {element.innerHTML = "ERROR!"; }; if (!("geolocation" in navigator)) { return missing(); } navigator.geolocation.getCurrentPosition(function(pos) { element.innerHTML = "<p>" + pos.coords.latitude.toString() + "<br/>" + pos.coords.longitude.toString() + "</p>"; var img = new Image(); img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + pos.coords.latitude + "," + pos.coords.longitude + "&zoom=13&size=300x300&sensor=false"; element.appendChild(img); }, error); }; // Public interface: return {get: get}; })();
Geolocation = (function() { var get = function(element) { var disabled = function() {element.innerHTML = "DISABLED.";}; var error = function() {element.innerHTML = "ERROR!"; }; if (!("geolocation" in navigator)) { return disabled(); } navigator.geolocation.getCurrentPosition(function(pos) { element.innerHTML = "<p>" + pos.coords.latitude.toString() + "<br/>" + pos.coords.longitude.toString() + "</p>"; var img = new Image(); img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + pos.coords.latitude + "," + pos.coords.longitude + "&zoom=13&size=300x300&sensor=false"; element.appendChild(img); }, error); }; // Public interface: return {get: get}; })();
Make more generic to allow easily adding more contact-items in the future
var animationDuration = 800; var fadeInDelay = animationDuration; jQuery.fn.extend({ fadeInOpacity: function() { $( this ).animate( { opacity: 1 }, animationDuration ); } }); $( document ).ready( function() { // Fade in the whole shebang after the DOM is ready $( '#wrapper ').fadeIn( animationDuration, function() { var numberOfContactItems = 0; $( '.contact-item' ).each( function( i ) { var item = $( this ); setTimeout( function() { console.log(i) item.fadeInOpacity(); }, i * fadeInDelay); numberOfContactItems += 1; }); setTimeout( function() { $( '.category-item' ).first().click(); }, numberOfContactItems * fadeInDelay); }); $( '.category-item' ).click( function( e ) { $( this ).toggleClass( 'open closed' ); $( this ).find( '.category-text' ).stop().slideToggle(); $( this ).find( '.read-more-icon' ).toggleClass( 'fa-chevron-circle-down fa-times-circle' ); }); // Set copyright year to current year $( '#current-year' ).text( (new Date).getFullYear() ); })
var animationDuration = 1000; var fadeInDelay = animationDuration; var openFirstCategoryDelay = 2*fadeInDelay; jQuery.fn.extend({ fadeInOpacity: function() { $( this ).animate( { opacity: 1 }, animationDuration ); } }); $( document ).ready( function() { // Fade in the whole shebang after the DOM is ready $( '#wrapper ').fadeIn( animationDuration, function() { setTimeout( function() { $( '.category-item' ).first().click(); }, openFirstCategoryDelay); }); $( '.category-item' ).click( function( e ) { $( this ).toggleClass( 'open closed' ); $( this ).find( '.category-text' ).stop().slideToggle(); $( this ).find( '.read-more-icon' ).toggleClass( 'fa-chevron-circle-down fa-times-circle' ); }); // Set copyright year to current year $( '#current-year' ).text( (new Date).getFullYear() ); }) // $(window).on( 'load' , function() { // $( '.contact-item' ).each( function( i ) { // var item = $( this ); // setTimeout( function() { // console.log(i) // item.fadeInOpacity(); // }, i * fadeInDelay); // }); // });
Use fresh build environment by default in tests
import os import sphinx_tests_util from xml.etree import ElementTree from xml.dom import minidom # ============================================================================= # Utility functions def srcdir(name): test_root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(test_root, "data", name) def pretty_print_xml(node): minidom_xml = minidom.parseString(ElementTree.tostring(node)) output = minidom_xml.toprettyxml(indent=" ") lines = [line for line in output.splitlines() if line.strip()] print "\n".join(lines) def with_app(*args, **kwargs): kwargs = kwargs.copy() # Expand test data directory. if "srcdir" in kwargs: kwargs["srcdir"] = srcdir(kwargs["srcdir"]) # By default use a fresh build environment. if "freshenv" not in kwargs: kwargs["freshenv"] = True return sphinx_tests_util.with_app(*args, **kwargs)
import os import sphinx_tests_util from xml.etree import ElementTree from xml.dom import minidom # ============================================================================= # Utility functions def srcdir(name): test_root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(test_root, "data", name) def pretty_print_xml(node): minidom_xml = minidom.parseString(ElementTree.tostring(node)) output = minidom_xml.toprettyxml(indent=" ") lines = [line for line in output.splitlines() if line.strip()] print "\n".join(lines) def with_app(*args, **kwargs): kwargs = kwargs.copy() if "srcdir" in kwargs: kwargs["srcdir"] = srcdir(kwargs["srcdir"]) return sphinx_tests_util.with_app(*args, **kwargs)
Change chromhost to use normal sockets
#!/usr/bin/env python import socket import struct import sys def send_to_chrome(message): # Write message size. sys.stdout.write(struct.pack('I', len(message))) # Write the message itself. sys.stdout.write(message) sys.stdout.flush() def read_from_chrome(): text_length_bytes = sys.stdin.read(4) if len(text_length_bytes) == 0: sys.exit(0) # Unpack message length as 4 byte integer. text_length = struct.unpack('i', text_length_bytes)[0] # Read the text (JSON object) of the message. text = sys.stdin.read(text_length).decode('utf-8') return text # sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # socket_name = '/tmp/cachebrowser.sock' # sock.connect(socket_name) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('127.0.0.1', 4242)) message = read_from_chrome() sock.send(message) sock.send('\n') # response = '' # while True: # read = sock.recv(1024) # if len(read) == 0: # break # response += read response = sock.recv(1024) send_to_chrome(response) # send_to_chrome("{}")
#!/usr/bin/env python import socket import struct import sys def send_to_chrome(message): # Write message size. sys.stdout.write(struct.pack('I', len(message))) # Write the message itself. sys.stdout.write(message) sys.stdout.flush() def read_from_chrome(): text_length_bytes = sys.stdin.read(4) if len(text_length_bytes) == 0: sys.exit(0) # Unpack message length as 4 byte integer. text_length = struct.unpack('i', text_length_bytes)[0] # Read the text (JSON object) of the message. text = sys.stdin.read(text_length).decode('utf-8') return text sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) socket_name = '/tmp/cachebrowser.sock' sock.connect(socket_name) message = read_from_chrome() sock.send(message) sock.send('\n') response = '' while True: read = sock.recv(1024) if len(read) == 0: break response += read # response = sock.recv(1024) send_to_chrome(response)
[fix] Enable save button if custom and not in developer mode
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt frappe.require('assets/frappe/js/lib/jscolor/jscolor.js'); frappe.provide("frappe.website_theme"); $.extend(frappe.website_theme, { color_variables: ["background_color", "top_bar_color", "top_bar_text_color", "footer_color", "footer_text_color", "text_color", "link_color"] }); frappe.ui.form.on("Website Theme", "onload_post_render", function(frm) { $.each(frappe.website_theme.color_variables, function(i, v) { $(frm.fields_dict[v].input).addClass('color {required:false,hash:true}'); }); jscolor.bind(); }); frappe.ui.form.on("Website Theme", "refresh", function(frm) { frm.toggle_display(["module", "custom"], !frappe.boot.developer_mode); if (!frm.doc.custom && !frappe.boot.developer_mode) { frm.set_read_only(); frm.disable_save(); } else { frm.enable_save(); } });
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt frappe.require('assets/frappe/js/lib/jscolor/jscolor.js'); frappe.provide("frappe.website_theme"); $.extend(frappe.website_theme, { color_variables: ["background_color", "top_bar_color", "top_bar_text_color", "footer_color", "footer_text_color", "text_color", "link_color"] }); frappe.ui.form.on("Website Theme", "onload_post_render", function(frm) { $.each(frappe.website_theme.color_variables, function(i, v) { $(frm.fields_dict[v].input).addClass('color {required:false,hash:true}'); }); jscolor.bind(); }); frappe.ui.form.on("Website Theme", "refresh", function(frm) { frm.toggle_display(["module", "custom"], !!frappe.boot.developer_mode); if (!frm.doc.custom && !!!frappe.boot.developer_mode) { frm.set_read_only(); frm.disable_save(); } });
Add blank line to satisfy OCD
<?php class Pitch extends BaseModel { protected $table = 'pitches'; public static $rules = [ 'email' => 'required|email', 'name' => 'required', 'blurb' => 'required' ]; /** * Class constants */ const UNSEEN = 10; const REVIEW = 20; const REJECTED = 30; const ACCEPTED = 40; const WAITING = 60; const PUBLISHED = 70; static public $statusList = [ Pitch::UNSEEN => 'Unseen', Pitch::REVIEW => 'In Review', Pitch::REJECTED => 'Rejected', Pitch::ACCEPTED => 'Accepted', Pitch::WAITING => 'Waiting for Rev', Pitch::PUBLISHED => 'Published' ]; /** * Pitch belongsTo Author */ public function author() { return $this->belongsTo('Author'); } /** * Pitch belongsTo Story */ public function story() { return $this->belongsTo('Story'); } public function scopePending($query) { return $query->whereIn('status', [ Pitch::UNSEEN, Pitch::REVIEW, Pitch::ACCEPTED, Pitch::WAITING ]); } }
<?php class Pitch extends BaseModel { protected $table = 'pitches'; public static $rules = [ 'email' => 'required|email', 'name' => 'required', 'blurb' => 'required' ]; /** * Class constants */ const UNSEEN = 10; const REVIEW = 20; const REJECTED = 30; const ACCEPTED = 40; const WAITING = 60; const PUBLISHED = 70; static public $statusList = [ Pitch::UNSEEN => 'Unseen', Pitch::REVIEW => 'In Review', Pitch::REJECTED => 'Rejected', Pitch::ACCEPTED => 'Accepted', Pitch::WAITING => 'Waiting for Rev', Pitch::PUBLISHED => 'Published' ]; /** * Pitch belongsTo Author */ public function author() { return $this->belongsTo('Author'); } /** * Pitch belongsTo Story */ public function story() { return $this->belongsTo('Story'); } public function scopePending($query) { return $query->whereIn('status', [ Pitch::UNSEEN, Pitch::REVIEW, Pitch::ACCEPTED, Pitch::WAITING ]); } }
Fix the help command test after the introduction of settings
package cmd import ( "github.com/gsamokovarov/jump/cli" ) func Example_helpCmd() { _ = helpCmd(cli.Args{}, nil) // Output: // Usage: jump [COMMAND ...] // // Jump to a fuzzy-matched directory passed as an argument. // // Commands: // cd Fuzzy match a directory to jump to. // chdir Update the score of directory during chdir. // clean Cleans the database of inexisting entries. // forget Removes the current directory from the database. // hint Hints relevant paths for jumping. // import Import autojump or z scores. // pin Pin a directory to a search term. // pins Lists all the pinned search terms. // settings Configure jump settings // shell Display a shell integration script. // top Lists the directories as they are scored. // unpin Unpin a search term. // // Options: // --help Show this screen. // --version Show version. }
package cmd import ( "github.com/gsamokovarov/jump/cli" ) func Example_helpCmd() { _ = helpCmd(cli.Args{}, nil) // Output: // Usage: jump [COMMAND ...] // // Jump to a fuzzy-matched directory passed as an argument. // // Commands: // cd Fuzzy match a directory to jump to. // chdir Update the score of directory during chdir. // clean Cleans the database of inexisting entries. // forget Removes the current directory from the database. // hint Hints relevant paths for jumping. // import Import autojump or z scores. // pin Pin a directory to a search term. // pins Lists all the pinned search terms. // shell Display a shell integration script. // top Lists the directories as they are scored. // unpin Unpin a search term. // // Options: // --help Show this screen. // --version Show version. }
Fix enabled flag not working when the user doesnt explicity set enabled to true in config
// jscs:disable /* globals define */ String.prototype.toSnakeCase = function() { return this.replace(/([A-Z])/g, function(string) { return '_' + string.toLowerCase(); }); }; (function() { 'use strict'; var _elev = window._elev = {}; function _setup(config) { if (config.enabled === false) { return; } var i, e; i = document.createElement("script"), i.type = 'text/javascript'; i.async = 1, i.src = "https://static.elev.io/js/v3.js", e = document.getElementsByTagName("script")[0], e.parentNode.insertBefore(i, e); if (!config.accountId) { throw new Error('ENV.elevio.accountId must be defined in config/environment.js'); } // elevio uses snake case for all their keys. // All the config for this addon uses camelCase for (var key in config) { if (config.hasOwnProperty(key)) { _elev[key.toSnakeCase()] = config[key]; } } } function generateModule(name, values) { define(name, [], function() { 'use strict'; Object.defineProperty(values, '__esModule', { value: true }); return values; }); } generateModule('elevio', { default: _elev, _setup: _setup }); })();
// jscs:disable /* globals define */ String.prototype.toSnakeCase = function() { return this.replace(/([A-Z])/g, function(string) { return '_' + string.toLowerCase(); }); }; (function() { 'use strict'; var _elev = window._elev = {}; function _setup(config) { if (!config.enabled) { return; } var i, e; i = document.createElement("script"), i.type = 'text/javascript'; i.async = 1, i.src = "https://static.elev.io/js/v3.js", e = document.getElementsByTagName("script")[0], e.parentNode.insertBefore(i, e); if (!config.accountId) { throw new Error('ENV.elevio.accountId must be defined in config/environment.js'); } // elevio uses snake case for all their keys. // All the config for this addon uses camelCase for (var key in config) { if (config.hasOwnProperty(key)) { _elev[key.toSnakeCase()] = config[key]; } } } function generateModule(name, values) { define(name, [], function() { 'use strict'; Object.defineProperty(values, '__esModule', { value: true }); return values; }); } generateModule('elevio', { default: _elev, _setup: _setup }); })();
Prepare for tagging release 0.1: Add comments to LibCharm.IO
try: from Bio import SeqIO from Bio.Alphabet import IUPAC except ImportError as e: print('ERROR: {}'.format(e.msg)) exit(1) def load_file(filename, file_format="fasta"): """ Load sequence from file and returns sequence as Bio.Seq object filename - String; Path and filename of input sequence file file_format - String; Format to be used. Refer to Biopython docs for available formats. Defaults to 'fasta' """ content = None try: # assume sequence is DNA content = SeqIO.read(filename, file_format, IUPAC.unambiguous_dna) except ValueError as e: # if this fails, try RNA instead print('ERROR: {}'.format(e)) try: content = SeqIO.read(filename, file_format, IUPAC.unambiguous_rna) except ValueError as e: # if this fails, too, raise exception and exit with error code 1 print('ERROR: {}'.format(e)) exit(1) # if some kind of data could be read, return the sequence object if content: seq = content.seq return seq # else return None else: return None
try: from Bio import SeqIO from Bio.Alphabet import IUPAC except ImportError as e: print('ERROR: {}'.format(e.msg)) exit(1) def load_file(filename, file_format="fasta"): """ Load sequence from file in FASTA file_format filename - Path and filename of input sequence file """ content = None try: content = SeqIO.read(filename, file_format, IUPAC.unambiguous_dna) except ValueError as e: print('ERROR: {}'.format(e)) try: content = SeqIO.read(filename, file_format, IUPAC.unambiguous_rna) except ValueError as e: print('ERROR: {}'.format(e)) exit(1) if content: seq = content.seq return seq else: return None