text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add link to 3.2 documentation and remove 2.0 link.
window.docMeta = (function () { var version = '3.2'; var name = 'ogm-manual'; var href = window.location.href; return { name: name, version: version, availableDocVersions: ["2.1", "3.0", "3.1", "3.2"], thisPubBaseUri: href.substring(0, href.indexOf(name) + name.length) + '/' + version, unversionedDocBaseUri: href.substring(0, href.indexOf(name) + name.length) + '/', commonDocsBaseUri: href.substring(0, href.indexOf(name) - 1) } })(); (function () { var baseUri = window.docMeta.unversionedDocBaseUri + window.location.pathname.split(window.docMeta.name + '/')[1].split('/')[0] + '/'; var docPath = window.location.href.replace(baseUri, ''); window.neo4jPageId = docPath; })(); // vim: set sw=2 ts=2:
window.docMeta = (function () { var version = '3.2'; var name = 'ogm-manual'; var href = window.location.href; return { name: name, version: version, availableDocVersions: ["2.0", "2.1", "3.0", "3.1"], thisPubBaseUri: href.substring(0, href.indexOf(name) + name.length) + '/' + version, unversionedDocBaseUri: href.substring(0, href.indexOf(name) + name.length) + '/', commonDocsBaseUri: href.substring(0, href.indexOf(name) - 1) } })(); (function () { var baseUri = window.docMeta.unversionedDocBaseUri + window.location.pathname.split(window.docMeta.name + '/')[1].split('/')[0] + '/'; var docPath = window.location.href.replace(baseUri, ''); window.neo4jPageId = docPath; })(); // vim: set sw=2 ts=2:
Fix Appends when no results were asked.
package com.google.cloud.anviltop.hbase.adapters; import com.google.bigtable.anviltop.AnviltopServices; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.client.Result; import java.util.ArrayList; import java.util.List; /** * Adapt an AppendRowResponse from Anviltop to an HBase Result */ public class AppendResponseAdapter implements ResponseAdapter<AnviltopServices.AppendRowResponse, Result> { protected final RowAdapter rowAdapter; public AppendResponseAdapter(RowAdapter rowAdapter) { this.rowAdapter = rowAdapter; } @Override public Result adaptResponse(AnviltopServices.AppendRowResponse response) { List<Cell> cells = new ArrayList<Cell>(); if (response.hasRow()) { return rowAdapter.adaptResponse(response.getRow()); } return null; } }
package com.google.cloud.anviltop.hbase.adapters; import com.google.bigtable.anviltop.AnviltopServices; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.client.Result; import java.util.ArrayList; import java.util.List; /** * Adapt an AppendRowResponse from Anviltop to an HBase Result */ public class AppendResponseAdapter implements ResponseAdapter<AnviltopServices.AppendRowResponse, Result> { protected final RowAdapter rowAdapter; public AppendResponseAdapter(RowAdapter rowAdapter) { this.rowAdapter = rowAdapter; } @Override public Result adaptResponse(AnviltopServices.AppendRowResponse response) { List<Cell> cells = new ArrayList<Cell>(); if (response.hasRow()) { return rowAdapter.adaptResponse(response.getRow()); } return new Result(); } }
Fix react-app-rewire-less not working on Windows Closes #53
const path = require('path') function rewireLess (config, env, lessLoaderOptions = {}) { const lessExtension = /\.less$/; const fileLoader = config.module.rules .find(rule => rule.loader && rule.loader.endsWith(`${path.sep}file-loader${path.sep}index.js`)); fileLoader.exclude.push(lessExtension); const cssRules = config.module.rules .find(rule => String(rule.test) === String(/\.css$/)); let lessRules; if (env === 'production') { lessRules = { test: lessExtension, loader: [ // TODO: originally this part is wrapper in extract-text-webpack-plugin // which we cannot do, so some things like relative publicPath // will not work. // https://github.com/timarney/react-app-rewired/issues/33 ...cssRules.loader, { loader: 'less-loader', options: lessLoaderOptions } ] }; } else { lessRules = { test: lessExtension, use: [ ...cssRules.use, { loader: 'less-loader', options: lessLoaderOptions } ] }; } config.module.rules.push(lessRules); return config; } module.exports = rewireLess;
function rewireLess (config, env, lessLoaderOptions = {}) { const lessExtension = /\.less$/; const fileLoader = config.module.rules .find(rule => rule.loader && rule.loader.endsWith('/file-loader/index.js')); fileLoader.exclude.push(lessExtension); const cssRules = config.module.rules .find(rule => String(rule.test) === String(/\.css$/)); let lessRules; if (env === 'production') { lessRules = { test: lessExtension, loader: [ // TODO: originally this part is wrapper in extract-text-webpack-plugin // which we cannot do, so some things like relative publicPath // will not work. // https://github.com/timarney/react-app-rewired/issues/33 ...cssRules.loader, { loader: 'less-loader', options: lessLoaderOptions } ] }; } else { lessRules = { test: lessExtension, use: [ ...cssRules.use, { loader: 'less-loader', options: lessLoaderOptions } ] }; } config.module.rules.push(lessRules); return config; } module.exports = rewireLess;
Allow columns to be translated
<?php /** * Created by PhpStorm. * User: mirel * Date: 24.10.2014 * Time: 16:10 */ namespace mpf\widgets\viewtable\columns; use mpf\base\TranslatableObject; use mpf\web\helpers\Html; class Basic extends TranslatableObject { public $name; public $label; public $value; public $htmlOptions = []; public $headerHtmlOptions = []; public $rowHtmlOptions = []; /** * Can be 'input' or 'raw'. If type is raw then it will not apply any escape to it. If not it will use html_encode from Html helper. * @var string */ public $type = 'input'; /** * @var \mpf\widgets\viewtable\Table */ public $table; public function display(){ return Html::get()->tag('tr', $this->getRowContent(), $this->rowHtmlOptions); } protected function getRowContent(){ return Html::get()->tag('th', $this->getLabel(), $this->headerHtmlOptions) . Html::get()->tag('td', $this->getValue(), $this->htmlOptions); } protected function getLabel(){ return $this->translate($this->label?:$this->table->getLabel($this->name)); } protected function getValue(){ return $this->value?:$this->table->model->{$this->name}; } }
<?php /** * Created by PhpStorm. * User: mirel * Date: 24.10.2014 * Time: 16:10 */ namespace mpf\widgets\viewtable\columns; use mpf\base\Object; use mpf\web\helpers\Html; class Basic extends Object { public $name; public $label; public $value; public $htmlOptions = []; public $headerHtmlOptions = []; public $rowHtmlOptions = []; /** * Can be 'input' or 'raw'. If type is raw then it will not apply any escape to it. If not it will use html_encode from Html helper. * @var string */ public $type = 'input'; /** * @var \mpf\widgets\viewtable\Table */ public $table; public function display(){ return Html::get()->tag('tr', $this->getRowContent(), $this->rowHtmlOptions); } protected function getRowContent(){ return Html::get()->tag('th', $this->getLabel(), $this->headerHtmlOptions) . Html::get()->tag('td', $this->getValue(), $this->htmlOptions); } protected function getLabel(){ return $this->label?:$this->table->getLabel($this->name); } protected function getValue(){ return $this->value?:$this->table->model->{$this->name}; } }
Test with an existing id
import subprocess import unittest class TestDataIsInstalled(unittest.TestCase): TEST_CMD = "python -c 'from vulndb import DBVuln; DBVuln.from_id(1)'" def test_data_is_installed_in_virtualenv(self): # When we run this in the current CMD it will load the python class # and db files from this directory (because of python's PATH) subprocess.check_output(self.TEST_CMD, shell=True) subprocess.check_output('python setup.py install', shell=True) # Now we run it in /tmp , where there is no vulndb in current PATH # so it will try to find it inside the site-packages subprocess.check_output(self.TEST_CMD, shell=True, cwd='/tmp/')
import subprocess import unittest class TestDataIsInstalled(unittest.TestCase): TEST_CMD = "python -c 'from vulndb import DBVuln; DBVuln.from_id(123)'" def test_data_is_installed_in_virtualenv(self): # When we run this in the current CMD it will load the python class # and db files from this directory (because of python's PATH) subprocess.check_output(self.TEST_CMD, shell=True) subprocess.check_output('python setup.py install', shell=True) # Now we run it in /tmp , where there is no vulndb in current PATH # so it will try to find it inside the site-packages subprocess.check_output(self.TEST_CMD, shell=True, cwd='/tmp/')
Make test task run the test parts in sequence
var gulp = require('gulp'); var tsc = require('gulp-tsc'); var tape = require('gulp-tape'); var tapSpec = require('tap-spec'); var del = require('del'); var runSequence = require('run-sequence'); gulp.task("test:clean", function(done) { del(['build-test/**']).then(function(paths) { console.log("=====\nDeleted the following files:\n" + paths.join('\n')+ "\n====="); done(); }); }); gulp.task("test:build", function (done) { gulp.src(['test/**/*.ts']) .pipe(tsc()) .pipe(gulp.dest('build-test/')) .on('end', done); }); gulp.task("test:run", function (done) { gulp.src('build-test/test/**/*.test.js') .pipe(tape({ reporter: tapSpec() })) .on('end', done);; }); gulp.task("test", function (done) { runSequence('test:clean', 'test:build', 'test:run', done); });
var gulp = require('gulp'); var tsc = require('gulp-tsc'); var tape = require('gulp-tape'); var tapSpec = require('tap-spec'); var del = require('del'); gulp.task("test:clean", function(done) { del(['build-test/**']).then(function(paths) { console.log("=====\nDeleted the following files:\n" + paths.join('\n')+ "\n====="); done(); }); }); gulp.task("test:build", function (done) { gulp.src(['test/**/*.ts']) .pipe(tsc()) .pipe(gulp.dest('build-test/')) .on('end', done); }); gulp.task("test:run", function (done) { gulp.src('build-test/test/**/*.test.js') .pipe(tape({ reporter: tapSpec() })) .on('end', done);; }); gulp.task("test", ["test:build"], function (done) { gulp.src('build-test/test/**/*.test.js') .pipe(tape({ reporter: tapSpec() })); });
Fix duplicate route id's This was possible because of the routes array that was being spliced, so we can not ensure that the route array length is usable for id identification.
'use strict'; /* A RoutesGenerator generates a list of routes. */ class RoutesGenerator { constructor(region, edges) { this.region = region; this.edges = edges; // [ ... { from, to } ... ]; tripId's are their index in this array this.nextRouteId = 0; this.routes = []; // [ ... { routeId, [ ... edgeId ... ] } ... ] this.debugpoints = []; } addRoute(edges){ this.addRouteRaw(edges, null); } addRouteRaw(edges, trips){ var routeId = this.nextRouteId++; var size = 0; edges.forEach(edge => size = size + edge.from.size + edge.to.size); var route = { routeId: routeId, edges: edges, trips: trips, size: size }; this.routes.push(route); edges.forEach(edge => edge.route = route); } generate() { throw new Error('RoutesGenerator#generate() has not been implemented yet.'); } getRoutes() { return this.routes; } } module.exports = RoutesGenerator;
'use strict'; /* A RoutesGenerator generates a list of routes. */ class RoutesGenerator { constructor(region, edges) { this.region = region; this.edges = edges; // [ ... { from, to } ... ]; tripId's are their index in this array this.nextTripId = 0; this.routes = []; // [ ... { routeId, [ ... edgeId ... ] } ... ] this.debugpoints = []; } addRoute(edges){ this.addRouteRaw(edges, null); } addRouteRaw(edges, trips){ var routeId = this.routes.length; var size = 0; edges.forEach(edge => size = size + edge.from.size + edge.to.size); var route = { routeId: routeId, edges: edges, trips: trips, size: size }; this.routes.push(route); edges.forEach(edge => edge.route = route); } generate() { throw new Error('RoutesGenerator#generate() has not been implemented yet.'); } getRoutes() { return this.routes; } } module.exports = RoutesGenerator;
Comment out rush warning and job score
<?php $job = $item->assocObject;?> <?php $id = 'job_evt_'.$job->ID.$item->ID;?> <div id="<?php echo $id;?>"> <div class="pad"><?php $job = $item->getAssocObject(); ?> <?php /* js: hide rush warning, todo: rm red bg <?php if($job->RUSH){?> <span class="warning">RUSH</span>&nbsp; <?php } ?> */ ?> <a href="<?php echo CHtml::normalizeUrl(array('job/view', 'id'=>$job->ID));?>"> <?php echo CHtml::encode($job->NAME);?> </a>&nbsp; <?php /* js: hide job score (<strong><?php echo $job->score;?></strong>) */ ?> <?php echo CHtml::activeHiddenField($item, 'ID');?> <?php Yii::app()->clientScript->registerCss($id, "#$id{}");/*480 is number of minutes in 8 hours*/?></div> </div>
<?php $job = $item->assocObject;?> <?php $id = 'job_evt_'.$job->ID.$item->ID;?> <div id="<?php echo $id;?>"> <div class="pad"><?php $job = $item->getAssocObject(); ?> <?php /* js: hide rush warning <?php if($job->RUSH){?> <span class="warning">RUSH</span>&nbsp; <?php } ?> */ ?> <a href="<?php echo CHtml::normalizeUrl(array('job/view', 'id'=>$job->ID));?>"> <?php echo CHtml::encode($job->NAME);?> </a>&nbsp; <?php /* js: hide job score (<strong><?php echo $job->score;?></strong>) */ ?> <?php echo CHtml::activeHiddenField($item, 'ID');?> <?php Yii::app()->clientScript->registerCss($id, "#$id{}");/*480 is number of minutes in 8 hours*/?></div> </div>
Move setState logic on new tweet to component method
'use strict'; var React = require('react'); var io = require('socket.io-client'); var TwitterStreamList = require('./stream-list'); var TwitterStreamApp = React.createClass({ getInitialState: function() { return { tweets: [] }; }, onTweetReceived: function(tweet) { var tweets = this.state.tweets.slice(); tweets.unshift(tweet); this.setState({ tweets: tweets }); }, componentDidMount: function() { this.socket = io(); this.socket.on('tweet', this.onTweetReceived); }, this.setState({ tweets: tweets }); }.bind(this)); }, render: function() { return ( <div className="TwitterStream"> <TwitterStreamList data={this.state.tweets}/> </div> ); } }); module.exports = TwitterStreamApp;
'use strict'; var React = require('react'); var io = require('socket.io-client'); var TwitterStreamList = require('./stream-list'); var TwitterStreamApp = React.createClass({ getInitialState: function() { return { tweets: [] }; }, componentDidMount: function() { var socket = io(); socket.on('tweet', function(tweet) { var tweets = this.state.tweets.slice(); tweets.unshift(tweet); this.setState({ tweets: tweets }); }.bind(this)); }, render: function() { return ( <div className="TwitterStream"> <TwitterStreamList data={this.state.tweets}/> </div> ); } }); module.exports = TwitterStreamApp;
chore: Add close comands to MockRedis class This closes #15 Signed-off-by: Kai Blin <ad3597797f6179d503c382b2627cc19939309418@biosustain.dtu.dk>
from mockredis import MockRedis as _MockRedis from .generic import GenericCommandsMixin from .hash import HashCommandsMixin from .list import ListCommandsMixin from .set import SetCommandsMixin __all__ = ['MockRedis'] class MockRedis(GenericCommandsMixin, HashCommandsMixin, ListCommandsMixin, SetCommandsMixin): """Fake high-level aioredis.Redis interface""" def __init__(self, connection=None, encoding=None, **kwargs): # Just for API compatibility self._conn = connection self._redis = _MockRedis(**kwargs) self._encoding = encoding async def wait_closed(self): if self._conn: await self._conn.wait_closed() def close(self): if self._conn: self._conn.close() async def create_redis(address, *, db=None, password=None, ssl=None, encoding=None, commands_factory=MockRedis, loop=None): '''Create a fake high-level MockRedis interface This function is a coroutine ''' return commands_factory(None, encoding=encoding)
from mockredis import MockRedis as _MockRedis from .generic import GenericCommandsMixin from .hash import HashCommandsMixin from .list import ListCommandsMixin from .set import SetCommandsMixin __all__ = ['MockRedis'] class MockRedis(GenericCommandsMixin, HashCommandsMixin, ListCommandsMixin, SetCommandsMixin): """Fake high-level aioredis.Redis interface""" def __init__(self, connection=None, encoding=None, **kwargs): # Just for API compatibility self._conn = connection self._redis = _MockRedis(**kwargs) self._encoding = encoding async def create_redis(address, *, db=None, password=None, ssl=None, encoding=None, commands_factory=MockRedis, loop=None): '''Create a fake high-level MockRedis interface This function is a coroutine ''' return commands_factory(None, encoding=encoding)
Add test annotation again, ignore overrides this.
package com.crawljax.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.File; import org.junit.Ignore; import org.junit.Test; public class PrettyHTMLTest { private static final String TESTFILE = "src/test/java/com/crawljax/util/tuduDombefore.html"; private static final String CONTROLFILE = "src/test/java/com/crawljax/util/tuduDombefore.html.tidy"; @Ignore @Test public void prettifyHTML() { String testdom = Helper.getContent(new File(TESTFILE)); String controldom = Helper.getContent(new File(CONTROLFILE)); assertNotNull("File should be read", testdom); assertNotNull("File should be read", controldom); testdom = PrettyHTML.prettyHTML(testdom); assertEquals(controldom, testdom); } }
package com.crawljax.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.File; import org.junit.Ignore; public class PrettyHTMLTest { private static final String TESTFILE = "src/test/java/com/crawljax/util/tuduDombefore.html"; private static final String CONTROLFILE = "src/test/java/com/crawljax/util/tuduDombefore.html.tidy"; @Ignore public void prettifyHTML() { String testdom = Helper.getContent(new File(TESTFILE)); String controldom = Helper.getContent(new File(CONTROLFILE)); assertNotNull("File should be read", testdom); assertNotNull("File should be read", controldom); testdom = PrettyHTML.prettyHTML(testdom); assertEquals(controldom, testdom); } }
Update package according to licence change.
import os from setuptools import find_packages, setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-etesync-journal', version='0.1.0', packages=find_packages(), include_package_data=True, license='AGPLv3', description='The server side implementation of the EteSync protocol.', long_description=README, url='https://www.etesync.com/', author='EteSync', author_email='contact.journal@etesync.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: AGPLv3', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
import os from setuptools import find_packages, setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-etesync-journal', version='0.1.0', packages=find_packages(), include_package_data=True, license='GPLv3', description='The server side implementation of the EteSync protocol.', long_description=README, url='https://www.etesync.com/', author='EteSync', author_email='contact.journal@etesync.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: GPLv3', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
Fix migration history bug introduced with merge
"""Add compound index to Contact and Event Revision ID: 1fd7b3e0b662 Revises: 5305d4ae30b4 Create Date: 2015-02-17 18:11:30.726188 """ # revision identifiers, used by Alembic. revision = '1fd7b3e0b662' down_revision = '5305d4ae30b4' from alembic import op def upgrade(): op.create_index( 'ix_contact_ns_uid_provider_name', 'contact', ['namespace_id', 'uid', 'provider_name'], unique=False) op.create_index( 'ix_event_ns_uid_provider_name', 'event', ['namespace_id', 'uid', 'provider_name'], unique=False) def downgrade(): raise Exception("Don't bother.")
"""Add compound index to Contact and Event Revision ID: 1fd7b3e0b662 Revises: 5305d4ae30b4 Create Date: 2015-02-17 18:11:30.726188 """ # revision identifiers, used by Alembic. revision = '1fd7b3e0b662' down_revision = '2d8a350b4885' from alembic import op def upgrade(): op.create_index( 'ix_contact_ns_uid_provider_name', 'contact', ['namespace_id', 'uid', 'provider_name'], unique=False) op.create_index( 'ix_event_ns_uid_provider_name', 'event', ['namespace_id', 'uid', 'provider_name'], unique=False) def downgrade(): raise Exception("Don't bother.")
Improve CPF legibility and footprint.
<?php namespace Respect\Validation\Rules; class Cpf extends AbstractRule { public function validate($input) { // Code ported from jsfromhell.com $c = preg_replace('/\D/', '', $input); if (strlen($c) != 11 || preg_match("/^{$c[0]}{11}$/", $c)) return false; for ($s = 10, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--); if ($c[9] != ((($n %= 11) < 2) ? 0 : 11 - $n)) return false; for ($s = 11, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--); if ($c[10] != ((($n %= 11) < 2) ? 0 : 11 - $n)) return false; return true; } }
<?php namespace Respect\Validation\Rules; class Cpf extends AbstractRule { public function validate($input) { // Code ported from jsfromhell.com $c = preg_replace('/\D/', '', $input); if (strlen($c) != 11) { return false; } if (preg_match("/^{$c[0]}{11}$/", $c)) { return false; } for ($s = 10, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--); if ($c[9] != ((($n %= 11) < 2) ? 0 : 11 - $n)) { return false; } for ($s = 11, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--); if ($c[10] != ((($n %= 11) < 2) ? 0 : 11 - $n)) { return false; } return true; } }
Fix groupIndex for stacked graphs. When there is more than one line on a graph they are applied with the class .group(index)
var _ = require('underscore'); module.exports = { stack: function (browser, selector, index) { var lineInGroup = _.isNumber(index) ? '.group' + index : ''; return function () { var linePath; return browser .$(selector + ' svg .line' + lineInGroup) .should.eventually.exist .getAttribute('d').then(function (d) { linePath = d.split('M')[1]; }) .$(selector + ' svg .stack' + lineInGroup) .should.eventually.exist .getAttribute('d').then(function (d) { // the line follows the top of the stack, so the line path should be a // substring of the stack path d.should.contain(linePath); }); }; } };
module.exports = { stack: function (browser, selector, index) { index = index || ''; return function () { var linePath; return browser .$(selector + ' svg .line' + index) .should.eventually.exist .getAttribute('d').then(function (d) { linePath = d.split('M')[1]; }) .$(selector + ' svg .stack' + index) .should.eventually.exist .getAttribute('d').then(function (d) { // the line follows the top of the stack, so the line path should be a // substring of the stack path d.should.contain(linePath); }); }; } };
Add test de some de vetores
package test; import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import processing.core.PVector; public class VetorCompostoTest { PVector local, dir, acel, test, empty; Map<String, PVector> vectors; @Before public void setUp() throws Exception { vectors = new HashMap<String, PVector>(); local = new PVector(1.4e-3F, 3e-3F); dir = new PVector(1e-3F, 6e-3F); acel = new PVector(1.2e-3F, 1.2e-3F); test = new PVector(1.4e-3F + 1e-3F, 3e-3F + 6e-3F); empty = new PVector(); vectors.put("local", local); vectors.put("acel", acel); vectors.put("dir", dir); } @Test public void testQuandoForAdicionadoNovoVetor() { vectors.put("local", local); assertEquals(local, vectors.get("local")); } @Test public void testQuandoForRemovidoPeloLabel() { vectors.remove("dir"); assertEquals(vectors.get("dir"), null); } @Test public void testQuandoForTrabalhadoPeloNome() { vectors.get("local").add(vectors.get("dir")); assertEquals(test, vectors.get("local")); } }
package test; import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import processing.core.PVector; public class VetorCompostoTest { PVector local, dir, acel, testVector; String localLabel, dirLabel, acelLabel; Map<String, PVector> vectors; @Before public void setUp() throws Exception { vectors = new HashMap<String, PVector>(); local = PVector.random2D(); dir = PVector.random2D(); acel = PVector.random2D(); localLabel = "localLabel"; dirLabel = "dirLabel"; acelLabel = "acelLabel"; vectors.put("localLabel", local); vectors.put("dirLabel", dir); vectors.put("acelLabel", acel); testVector = vectors.get(localLabel); vectors.remove(dirLabel); } @After public void tearDown() throws Exception { vectors.clear(); } @Test public void testQuandoForAdicionadoNovoVetor() { assertEquals(testVector, vectors.get(localLabel)); } @Test public void testQuandoForRemovidoPeloLabel() { assertEquals(vectors.get(dirLabel), null); } }
fix(PointSet): Update vtkPointSet to use vtkPoints instead of vtkDataArray directly
import * as macro from '../../../macro'; import vtk from '../../../vtk'; import vtkDataSet from '../DataSet'; import vtkPoints from '../../Core/Points'; // ---------------------------------------------------------------------------- // Global methods // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // vtkPointSet methods // ---------------------------------------------------------------------------- function vtkPointSet(publicAPI, model) { // Set our className model.classHierarchy.push('vtkPointSet'); // Create empty points if (!model.points) { model.points = vtkPoints.newInstance(); } else { model.points = vtk(model.points); } publicAPI.getBounds = () => model.points.getBounds(); publicAPI.computeBounds = () => { publicAPI.getBounds(); }; } // ---------------------------------------------------------------------------- // Object factory // ---------------------------------------------------------------------------- const DEFAULT_VALUES = { // points: null, }; // ---------------------------------------------------------------------------- export function extend(publicAPI, model, initialValues = {}) { Object.assign(model, DEFAULT_VALUES, initialValues); // Inheritance vtkDataSet.extend(publicAPI, model, initialValues); macro.setGet(publicAPI, model, ['points']); // Object specific methods vtkPointSet(publicAPI, model); } // ---------------------------------------------------------------------------- export const newInstance = macro.newInstance(extend, 'vtkPointSet'); // ---------------------------------------------------------------------------- export default { newInstance, extend };
import * as macro from '../../../macro'; import vtkDataSet from '../DataSet'; import vtkDataArray from '../../Core/DataArray'; // ---------------------------------------------------------------------------- // Global methods // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Static API // ---------------------------------------------------------------------------- export const STATIC = { }; // ---------------------------------------------------------------------------- // vtkPointSet methods // ---------------------------------------------------------------------------- function vtkPointSet(publicAPI, model) { // Set our className model.classHierarchy.push('vtkPointSet'); // Create empty points if (!model.points) { model.points = vtkDataArray.newInstance({ empty: true }); } publicAPI.getBounds = () => model.points.getBounds(); publicAPI.computeBounds = () => { publicAPI.getBounds(); }; } // ---------------------------------------------------------------------------- // Object factory // ---------------------------------------------------------------------------- const DEFAULT_VALUES = { points: null, }; // ---------------------------------------------------------------------------- export function extend(publicAPI, model, initialValues = {}) { Object.assign(model, DEFAULT_VALUES, initialValues); // Inheritance vtkDataSet.extend(publicAPI, model, initialValues); macro.setGet(publicAPI, model, ['points']); // Object specific methods vtkPointSet(publicAPI, model); } // ---------------------------------------------------------------------------- export const newInstance = macro.newInstance(extend, 'vtkPointSet'); // ---------------------------------------------------------------------------- export default Object.assign({ newInstance, extend }, STATIC);
Improve printing in bucky's DebugClient
import sys import time import datetime from bucky.client import Client from bucky.names import statname class DebugClient(Client): out_path = None def __init__(self, cfg, pipe): super(DebugClient, self).__init__(pipe) if self.out_path: self.stdout = open(self.out_path, 'w') else: self.stdout = sys.stdout def send(self, host, name, value, tstamp): if self.filter(host, name, value, tstamp): self.write(host, name, value, tstamp) def filter(self, host, name, value, tstamp): return True def write(self, host, name, value, tstamp): target = statname(host, name) dtime = datetime.datetime.fromtimestamp(tstamp) time_lbl = dtime.strftime('%y%m%d %H:%M:%S') self.stdout.write('%s (%.1fs) %s %r\n' % (time_lbl, tstamp - time.time(), target, value)) self.stdout.flush()
import sys from bucky.client import Client class DebugClient(Client): out_path = None def __init__(self, cfg, pipe): super(DebugClient, self).__init__(pipe) if self.out_path: self.stdout = open(self.out_path, 'w') else: self.stdout = sys.stdout def send(self, host, name, value, time): if self.filter(host, name, value, time): self.write(host, name, value, time) def filter(self, host, name, value, time): return True def write(self, host, name, value, time): self.stdout.write('%s %s %s %s\n' % (host, name, value, time)) self.stdout.flush()
Add trove classifiers for additional Python support - Include classifier for general Python 2/3 support. - Include classifier for general PyPy support. - Include classifier for Python 3.7 support. Testing added in 0c1bbf6be93b2f0a110a9000fb514301c4d5ab89.
try: from setuptools import setup except ImportError: from distutils.core import setup import toml with open("README.rst") as readme_file: readme_string = readme_file.read() setup( name="toml", version=toml.__version__, description="Python Library for Tom's Obvious, Minimal Language", author="Uiri Noyb", author_email="uiri@xqz.ca", url="https://github.com/uiri/toml", packages=['toml'], license="License :: OSI Approved :: MIT License", long_description=readme_string, classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ] )
try: from setuptools import setup except ImportError: from distutils.core import setup import toml with open("README.rst") as readme_file: readme_string = readme_file.read() setup( name="toml", version=toml.__version__, description="Python Library for Tom's Obvious, Minimal Language", author="Uiri Noyb", author_email="uiri@xqz.ca", url="https://github.com/uiri/toml", packages=['toml'], license="License :: OSI Approved :: MIT License", long_description=readme_string, classifiers=[ 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6'] )
Fix cause of failing DEAs
/* * The Gemma project. * * Copyright (c) 2006-2012 University of British Columbia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ubic.gemma.model.common.auditAndSecurity.eventType; /** * The mapping of probes to genes for an ArrayDesign */ public class ArrayDesignGeneMappingEvent extends ubic.gemma.model.common.auditAndSecurity.eventType.ArrayDesignAnalysisEvent { /** * The serial version UID of this class. Needed for serialization. */ private static final long serialVersionUID = -7566135203525054499L; /** * No-arg constructor added to satisfy javabean contract * * @author Paul */ public ArrayDesignGeneMappingEvent() { } @SuppressWarnings({ "unused", "WeakerAccess" }) // Possible external use public static final class Factory { public static ubic.gemma.model.common.auditAndSecurity.eventType.ArrayDesignGeneMappingEvent newInstance() { return new ubic.gemma.model.common.auditAndSecurity.eventType.ArrayDesignGeneMappingEvent(); } } }
/* * The Gemma project. * * Copyright (c) 2006-2012 University of British Columbia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ubic.gemma.model.common.auditAndSecurity.eventType; /** * The mapping of probes to genes for an ArrayDesign */ public abstract class ArrayDesignGeneMappingEvent extends ubic.gemma.model.common.auditAndSecurity.eventType.ArrayDesignAnalysisEvent { /** * The serial version UID of this class. Needed for serialization. */ private static final long serialVersionUID = -7566135203525054499L; /** * No-arg constructor added to satisfy javabean contract * * @author Paul */ public ArrayDesignGeneMappingEvent() { } }
[FIX] stock_cancel: Set as not installable because it's broken
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (c) 2014 Andrea Cometa All Rights Reserved. # www.andreacometa.it # openerp@andreacometa.it # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Stock Cancel', 'version': '1.2', 'category': 'Stock', 'description': """This module allows you to bring back a completed stock picking to draft state""", 'author': 'www.andreacometa.it', 'website': 'http://www.andreacometa.it', 'depends': ['stock_picking_invoice_link'], 'data': [ 'stock_view.xml', ], 'installable': False, 'images': ['images/stock_picking.jpg'], }
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (c) 2014 Andrea Cometa All Rights Reserved. # www.andreacometa.it # openerp@andreacometa.it # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Stock Cancel', 'version': '1.2', 'category': 'Stock', 'description': """This module allows you to bring back a completed stock picking to draft state""", 'author': 'www.andreacometa.it', 'website': 'http://www.andreacometa.it', 'depends': ['stock_picking_invoice_link'], 'data': [ 'stock_view.xml', ], 'installable': True, 'images': ['images/stock_picking.jpg'], }
Use options.path instead of absoluteImagePath
// dependencies var jipics = "http://jipics.net/" , Request = require("request") , fs = require("fs") ; /** * Upload method * * Arguments * @options: a string representing the image path or an * object contanining the following fields: * - path: the path to the image * - deleteAfterUpload: if true, the image will be deleted after a sucessful upload * * */ exports.upload = function (options, callback) { // get the image from the request if (typeof options === "string") { options = { path: options } } // force options to be an object options = Object (options); // validate path if (!options.path) { return callback ("The path to the image must be provided."); } // upload the image to jipics.net Request.post(jipics, function (err, res) { // handle error if (err) { return callback (err); } // delete image if (options.deleteAfterUpload) { return fs.unlink(absoluteImagePath, callback); } callback (null, res); // create the read stream from image file }).form().append("image", fs.createReadStream(options.path)); };
// dependencies var jipics = "http://jipics.net/" , Request = require("request") , fs = require("fs") ; /** * Upload method * * Arguments * @options: a string representing the image path or an * object contanining the following fields: * - path: the path to the image * - deleteAfterUpload: if true, the image will be deleted after a sucessful upload * * */ exports.upload = function (options, callback) { // get the image from the request if (typeof options === "string") { options = { path: options } } // force options to be an object options = Object (options); // validate path if (!options.path) { return callback ("The path to the image must be provided."); } // upload the image to jipics.net Request.post(jipics, function (err, res) { // handle error if (err) { return callback (err); } // delete image if (options.deleteAfterUpload) { return fs.unlink(absoluteImagePath, callback); } callback (null, res); // create the read stream from image file }).form().append("image", fs.createReadStream(absoluteImagePath)); };
Add better error message for missing app key
<?php namespace Illuminate\Encryption; use RuntimeException; use Illuminate\Support\Str; use Illuminate\Support\ServiceProvider; class EncryptionServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('encrypter', function ($app) { $config = $app->make('config')->get('app'); // If the key starts with "base64:", we will need to decode the key before handing // it off to the encrypter. Keys may be base-64 encoded for presentation and we // want to make sure to convert them back to the raw bytes before encrypting. if (Str::startsWith($key = $config['key'], 'base64:')) { $key = base64_decode(substr($key, 7)); } if (is_null($key) || $key === '') { throw new RuntimeException( 'The application encryption key is missing. Run php artisan key:generate to generate it.' ); } return new Encrypter($key, $config['cipher']); }); } }
<?php namespace Illuminate\Encryption; use Illuminate\Support\Str; use Illuminate\Support\ServiceProvider; class EncryptionServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('encrypter', function ($app) { $config = $app->make('config')->get('app'); // If the key starts with "base64:", we will need to decode the key before handing // it off to the encrypter. Keys may be base-64 encoded for presentation and we // want to make sure to convert them back to the raw bytes before encrypting. if (Str::startsWith($key = $config['key'], 'base64:')) { $key = base64_decode(substr($key, 7)); } return new Encrypter($key, $config['cipher']); }); } }
Send game_ready to players when game is ready
class LoadingController { constructor($log, $scope, $state, $interval, SocketService, GameService) { 'ngInject'; this.$log = $log; this.$state = $state; this.$interval = $interval; this.GameService = GameService; this.SocketService = SocketService; this.waitTime = 5000; this.animTime = 850; this.ellipsis = '.'; $scope.$on('server_disconnect', function(event, args) { alert('Server disconnected. Game ended.'); $state.go('home'); }); this.setAnimation(); this.setGameAssetChecker(this.waitTime); } setAnimation() { this.$interval(() => this.changeEllipsis(), this.animTime, 0, true); } setGameAssetChecker(waitTime) { this.$interval(() => this.checkAssets(), waitTime, 1, true); } changeEllipsis() { this.ellipsis += '.'; if (this.ellipsis.length > 3) { this.ellipsis = '.'; } } checkAssets() { if (this.GameService.isGameReady()) { this.$log.log('Game ready'); this.$state.go('game'); this.SocketService.send({ type: 'game_ready', role: 'owner' }); } else { this.$log.log('Game not ready yet'); this.setGameAssetChecker(1000); } } } export default LoadingController;
class LoadingController { constructor($log, $scope, $state, $interval, SocketService, GameService) { 'ngInject'; this.$log = $log; this.$state = $state; this.$interval = $interval; this.GameService = GameService; this.SocketService = SocketService; this.waitTime = 5000; this.animTime = 850; this.ellipsis = '.'; $scope.$on('server_disconnect', function(event, args) { alert('Server disconnected. Game ended.'); $state.go('home'); }); this.setAnimation(); this.setGameAssetChecker(this.waitTime); } setAnimation() { this.$interval(() => this.changeEllipsis(), this.animTime, 0, true); } setGameAssetChecker(waitTime) { this.$interval(() => this.checkAssets(), waitTime, 1, true); } changeEllipsis() { this.ellipsis += '.'; if (this.ellipsis.length > 3) { this.ellipsis = '.'; } } checkAssets() { if (this.GameService.isGameReady()) { this.$log.log('Game ready'); this.$state.go('game'); //TODO: send the info to devices } else { this.$log.log('Game not ready yet'); this.setGameAssetChecker(1000); } } } export default LoadingController;
Add comments and check for virtual files
/* @flow */ import path from 'path' import State from '../State' import File from '../File' import Rule from '../Rule' import type { Command, OptionsInterface, Phase } from '../types' export default class CopyTargetsToRoot extends Rule { static parameterTypes: Array<Set<string>> = [new Set(['*'])] static description: string = 'Copy targets to root directory.' static alwaysEvaluate: boolean = true static async appliesToParameters (state: State, command: Command, phase: Phase, options: OptionsInterface, ...parameters: Array<File>): Promise<boolean> { return !!options.copyTargetsToRoot && parameters.every(file => !file.virtual && state.targets.has(file.filePath) && path.dirname(file.filePath) !== '.') } async initialize () { // Remove the old target and replace with the new one. this.removeTarget(this.firstParameter.filePath) await this.addResolvedTarget('$BASE_0') } async run () { // Copy the target to it's new location and add the result as an output. const filePath = this.resolvePath('$ROOTDIR/$BASE_0') await this.firstParameter.copy(filePath) await this.getOutput(filePath) return true } }
/* @flow */ import path from 'path' import State from '../State' import File from '../File' import Rule from '../Rule' import type { Command, OptionsInterface, Phase } from '../types' export default class CopyTargetsToRoot extends Rule { static parameterTypes: Array<Set<string>> = [new Set(['*'])] static description: string = 'Copy targets to root directory.' static alwaysEvaluate: boolean = true static async appliesToParameters (state: State, command: Command, phase: Phase, options: OptionsInterface, ...parameters: Array<File>): Promise<boolean> { return !!options.copyTargetsToRoot && parameters.every(file => state.targets.has(file.filePath) && path.dirname(file.filePath) !== '.') } async initialize () { this.removeTarget(this.firstParameter.filePath) await this.addResolvedTarget('$BASE_0') } async run () { const filePath = this.resolvePath('$ROOTDIR/$BASE_0') await this.firstParameter.copy(filePath) await this.getOutput(filePath) return true } }
Add 'command+shift+c' to open dev tools
import Combokeys from 'combokeys' import hookGlobalBind from 'combokeys/plugins/global-bind' const combo = new Combokeys(document.documentElement) hookGlobalBind(combo) import {remote} from '../electron' import createQueue from '../sagas/queue' import { focusSearch, showNextTab, showPreviousTab, closeTab } from '../actions' const queue = createQueue('shortcuts') export default function * shortcutsSaga () { yield* queue.exhaust() } function openDevTools () { const win = remote.getCurrentWindow() win.webContents.openDevTools({detach: true}) } // dev shortcuts combo.bindGlobal(['shift+f12', 'ctrl+shift+c', 'command+shift+c'], openDevTools) combo.bindGlobal(['shift+f5', 'shift+command+r'], () => window.location.reload()) // user shortcuts combo.bindGlobal(['ctrl+f', 'command+f'], () => { queue.dispatch(focusSearch()) }) combo.bindGlobal(['ctrl+tab', 'ctrl+pagedown'], () => { queue.dispatch(showNextTab()) }) combo.bindGlobal(['ctrl+shift+tab', 'ctrl+pageup'], () => { queue.dispatch(showPreviousTab()) }) combo.bindGlobal(['ctrl+w'], () => { queue.dispatch(closeTab()) })
import Combokeys from 'combokeys' import hookGlobalBind from 'combokeys/plugins/global-bind' const combo = new Combokeys(document.documentElement) hookGlobalBind(combo) import {remote} from '../electron' import createQueue from '../sagas/queue' import { focusSearch, showNextTab, showPreviousTab, closeTab } from '../actions' const queue = createQueue('shortcuts') export default function * shortcutsSaga () { yield* queue.exhaust() } function openDevTools () { const win = remote.getCurrentWindow() win.webContents.openDevTools({detach: true}) } // dev shortcuts combo.bindGlobal(['shift+f12', 'ctrl+shift+c'], openDevTools) combo.bindGlobal(['shift+f5', 'shift+command+r'], () => window.location.reload()) // user shortcuts combo.bindGlobal(['ctrl+f', 'command+f'], () => { queue.dispatch(focusSearch()) }) combo.bindGlobal(['ctrl+tab', 'ctrl+pagedown'], () => { queue.dispatch(showNextTab()) }) combo.bindGlobal(['ctrl+shift+tab', 'ctrl+pageup'], () => { queue.dispatch(showPreviousTab()) }) combo.bindGlobal(['ctrl+w'], () => { queue.dispatch(closeTab()) })
Fix image size in chat
import React from "react-native"; const { Dimensions, Image } = React; export default class EmbedImage extends React.Component { shouldComponentUpdate(nextProps) { return ( this.props.height !== nextProps.height || this.props.width !== nextProps.width || this.props.uri !== nextProps.uri ); } render() { const { height, width, uri } = this.props; const win = Dimensions.get("window"); const ratio = (height && width) ? (height / width) : 1; // Determine the optimal height and width const displayWidth = (height ? Math.min(width, win.width - 120) : 160); const displayHeight = displayWidth * ratio; return ( <Image style={[ { height: displayHeight, width: displayWidth }, this.props.style ]} source={{ uri }} /> ); } } EmbedImage.propTypes = { height: React.PropTypes.number, width: React.PropTypes.number, uri: React.PropTypes.string.isRequired };
import React from "react-native"; const { Dimensions, Image } = React; export default class EmbedImage extends React.Component { shouldComponentUpdate(nextProps) { return ( this.props.height !== nextProps.height || this.props.width !== nextProps.width || this.props.uri !== nextProps.uri ); } render() { const { height, width, uri } = this.props; const win = Dimensions.get("window"); const ratio = (height && width) ? (height / width) : 1; // Determine the optimal height and width const displayWidth = (height ? Math.min(width, win.width - 56) : 160); const displayHeight = displayWidth * ratio; return ( <Image style={[ { height: displayHeight, width: displayWidth }, this.props.style ]} source={{ uri }} /> ); } } EmbedImage.propTypes = { height: React.PropTypes.number, width: React.PropTypes.number, uri: React.PropTypes.string.isRequired };
Add tests as data_dir to ndimage.segment
#!/usr/bin/env python def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('segment', parent_package, top_path) config.add_extension('_segmenter', sources=['Segmenter_EXT.c', 'Segmenter_IMPL.c'], depends = ['ndImage_Segmenter_structs.h'] ) config.add_data_dir('tests') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
#!/usr/bin/env python def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('segment', parent_package, top_path) config.add_extension('_segmenter', sources=['Segmenter_EXT.c', 'Segmenter_IMPL.c'], depends = ['ndImage_Segmenter_structs.h'] ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
Add karma-jasmine to the plugins
const gulp = require('gulp'); const tsc = require('gulp-typescript'); const Server = require('karma').Server; const tsProject = tsc.createProject('src/tsconfig.json'); const tsProjectSpec = tsc.createProject('spec/tsconfig.json'); gulp.task('default', ['build']); gulp.task('build', () => { return tsProject.src() .pipe(tsc(tsProject)) .pipe(gulp.dest('build')); }); gulp.task('test', ['test-build:spec', 'test-build:src'], () => { new Server({ configFile: __dirname + '/karma.conf.js', singleRun: true, plugins: [ 'karma-jasmine', 'karma-spec-reporter', 'karma-coverage', 'karma-coveralls' ] }).start(); }); gulp.task('test-build:spec', (done) => { tsProjectSpec.src() .pipe(tsc(tsProjectSpec)) .pipe(gulp.dest('test-build')) .on('end', done); }); gulp.task('test-build:src', (done) => { tsProject.src() .pipe(tsc(tsProject)) .pipe(gulp.dest('test-build/src')) .on('end', done); });
const gulp = require('gulp'); const tsc = require('gulp-typescript'); const Server = require('karma').Server; const tsProject = tsc.createProject('src/tsconfig.json'); const tsProjectSpec = tsc.createProject('spec/tsconfig.json'); gulp.task('default', ['build']); gulp.task('build', () => { return tsProject.src() .pipe(tsc(tsProject)) .pipe(gulp.dest('build')); }); gulp.task('test', ['test-build:spec', 'test-build:src'], () => { new Server({ configFile: __dirname + '/karma.conf.js', singleRun: true, plugins:[ 'karma-spec-reporter', 'karma-coverage', 'karma-coveralls' ] }).start(); }); gulp.task('test-build:spec', (done) => { tsProjectSpec.src() .pipe(tsc(tsProjectSpec)) .pipe(gulp.dest('test-build')) .on('end', done); }); gulp.task('test-build:src', (done) => { tsProject.src() .pipe(tsc(tsProject)) .pipe(gulp.dest('test-build/src')) .on('end', done); });
Update withMultipleDates HOC example usage
import React from 'react'; import {render} from 'react-dom'; import InfiniteCalendar, { Calendar, defaultMultipleDateInterpolation, withMultipleDates, } from 'react-infinite-calendar'; import 'react-infinite-calendar/styles.css'; const MultipleDatesCalendar = withMultipleDates(Calendar); render( <InfiniteCalendar Component={MultipleDatesCalendar} /* * The `interpolateSelection` prop allows us to map the resulting state when a user selects a date. * By default, it adds the date to the selected dates array if it isn't already selected. * If the date is already selected, it removes it. * * You could re-implement this if this isn't the behavior you want. */ interpolateSelection={defaultMultipleDateInterpolation} selected={[new Date(2017, 1, 10), new Date(2017, 1, 18), new Date()]} />, document.querySelector('#root') );
import React from 'react'; import {render} from 'react-dom'; import InfiniteCalendar, { Calendar, defaultMultipleDateInterpolation, withMultipleDates, } from 'react-infinite-calendar'; import 'react-infinite-calendar/styles.css'; render( <InfiniteCalendar Component={withMultipleDates(Calendar)} /* * The `interpolateSelection` prop allows us to map the resulting state when a user selects a date. * By default, it adds the date to the selected dates array if it isn't already selected. * If the date is already selected, it removes it. * * You could re-implement this if this isn't the behavior you want. */ interpolateSelection={defaultMultipleDateInterpolation} selected={[new Date(2017, 1, 10), new Date(2017, 1, 18), new Date()]} />, document.querySelector('#root') );
FIx function definition for getSubscribedEvents()
<?php namespace Factorial\Fabalicious; use Composer\Composer; use Composer\EventDispatcher\EventSubscriberInterface; use Composer\IO\IOInterface; use Composer\Plugin\PluginInterface; use Composer\Script\Event; use Composer\Script\ScriptEvents; use Composer\Util\Filesystem; /** * A Composer plugin to do some custom handling installing fabalicious. */ class InstallerPlugin implements PluginInterface, EventSubscriberInterface { protected $io; /** * Construct a new Composer NPM bridge plugin. */ public function __construct() { } /** * Activate the plugin. */ public function activate(Composer $composer, IOInterface $io) { $this->io = $io; } /** * Get the event subscriber configuration for this plugin. */ public static function getSubscribedEvents(){ return [ ScriptEvents::POST_INSTALL_CMD => 'onPostInstallCmd', ]; } /** * Handle post install command events. */ public function onPostInstallCmd(Event $event) { $fs = new Filesystem(); $working_dir = getcwd(); $fabalicious_dir = dirname(__DIR__); $relative_dir = $fs->findShortestPath($working_dir, $fabalicious_dir); try { $fs->unlink('fabfile.py'); } catch (\Exception $e) { } system(sprintf('ln -s %s/fabfile.py fabfile.py', $relative_dir)); $this->io->write('Created symlink for fabalicious.'); } }
<?php namespace Factorial\Fabalicious; use Composer\Composer; use Composer\EventDispatcher\EventSubscriberInterface; use Composer\IO\IOInterface; use Composer\Plugin\PluginInterface; use Composer\Script\Event; use Composer\Script\ScriptEvents; use Composer\Util\Filesystem; /** * A Composer plugin to do some custom handling installing fabalicious. */ class InstallerPlugin implements PluginInterface, EventSubscriberInterface { protected $io; /** * Construct a new Composer NPM bridge plugin. */ public function __construct() { } /** * Activate the plugin. */ public function activate(Composer $composer, IOInterface $io) { $this->io = $io; } /** * Get the event subscriber configuration for this plugin. */ public static function getSubscribedEvents(): array { return [ ScriptEvents::POST_INSTALL_CMD => 'onPostInstallCmd', ]; } /** * Handle post install command events. */ public function onPostInstallCmd(Event $event) { $fs = new Filesystem(); $working_dir = getcwd(); $fabalicious_dir = dirname(__DIR__); $relative_dir = $fs->findShortestPath($working_dir, $fabalicious_dir); try { $fs->unlink('fabfile.py'); } catch (\Exception $e) { } system(sprintf('ln -s %s/fabfile.py fabfile.py', $relative_dir)); $this->io->write('Created symlink for fabalicious.'); } }
Disable Chrome flag to get CircleCI working again
module.exports = { test_page: 'tests/index.html?hidepassed', disable_watching: true, launch_in_ci: [ 'Chrome' ], launch_in_dev: [ 'Chrome' ], browser_args: { Chrome: { ci: [ // --no-sandbox is needed when running Chrome inside a container process.env.CI ? '--no-sandbox' : null, '--headless', '--disable-gpu', '--disable-software-rasterizer', '--mute-audio', '--remote-debugging-port=0', '--window-size=1440,900' ].filter(Boolean) } } };
module.exports = { test_page: 'tests/index.html?hidepassed', disable_watching: true, launch_in_ci: [ 'Chrome' ], launch_in_dev: [ 'Chrome' ], browser_args: { Chrome: { ci: [ // --no-sandbox is needed when running Chrome inside a container process.env.CI ? '--no-sandbox' : null, '--headless', '--disable-gpu', '--disable-dev-shm-usage', '--disable-software-rasterizer', '--mute-audio', '--remote-debugging-port=0', '--window-size=1440,900' ].filter(Boolean) } } };
Fix duplicate call of 't.end()' in tests
var test = require('tap').test, wolfram = require('../') test('valid response', function(t) { var client = wolfram.createClient(process.env.WOLFRAM_APPID) t.test("integrate 2x", function(t) { client.query("integrate 2x", function(err, result) { t.notOk(err, "err should be null") t.type(result, "object") t.ok(result.length) t.equal(result.length, 2, "result length should be 2") t.equal(result[0].primary, true, "first pod should be primary") t.equal(result[0].subpods[0].value, ' integral 2 x dx = x^2+constant', 'result should be constant') t.ok(result[0].subpods[0].image, "result should have an image representation") t.end() }) }) t.test("1+1", function(t) { client.query("1+1", function(err, result) { t.notOk(err, "err should be null") t.type(result, "object") t.ok(result.length) t.equal(result.length, 6) t.equal(result[1].primary, true) t.equal(result[1].subpods[0].value, '2') t.end() }) }) })
var test = require('tap').test, wolfram = require('../') test('valid response', function(t) { var client = wolfram.createClient(process.env.WOLFRAM_APPID) client.query("integrate 2x", function(err, result) { t.notOk(err, "err should be null") t.type(result, "object") t.ok(result.length) t.equal(result.length, 2, "result length should be 2") t.equal(result[0].primary, true, "first pod should be primary") t.equal(result[0].subpods[0].value, ' integral 2 x dx = x^2+constant', 'result should be constant') t.ok(result[0].subpods[0].image, "result should have an image representation") t.end() }) client.query("1+1", function(err, result) { t.notOk(err, "err should be null") t.type(result, "object") t.ok(result.length) t.equal(result.length, 6) t.equal(result[1].primary, true) t.equal(result[1].subpods[0].value, '2') t.end() }) })
Fix a bug where new users couldn't access settings page Signed-off-by: Felipe Milani <6def120dcec8fcb28aed4723fac713cfff66d853@gmail.com>
import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { ServiceConfiguration } from 'meteor/service-configuration'; import { _ } from 'lodash'; const services = Meteor.settings.private.oAuth; (() => { if (services) { _.forOwn(services, (data, service) => { ServiceConfiguration.configurations.upsert({ service }, { $set: data, }); }); } })(); Accounts.onCreateUser((options, user) => { const newUser = user; const profile = options.profile; // keeps the default hook if (profile) { newUser.profile = profile; } // copy the profile picture and email to the users' meteor profile _.forOwn(newUser.services, (data) => { // although this is a for loop, a user should only have 1 service newUser.profile.picture = data.picture; newUser.profile.email = data.email; }); // create the user settings newUser.settings = {}; return newUser; }); // FIXME: deny user updates and create user api // (currently needed so users can update their settings) Meteor.users.allow({ update() { return true; }, });
import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { ServiceConfiguration } from 'meteor/service-configuration'; import { _ } from 'lodash'; const services = Meteor.settings.private.oAuth; (() => { if (services) { _.forOwn(services, (data, service) => { ServiceConfiguration.configurations.upsert({ service }, { $set: data, }); }); } })(); Accounts.onCreateUser((options, user) => { const newUser = user; const profile = options.profile; // keeps the default hook if (profile) { newUser.profile = profile; } // copy the profile picture and email to the users' meteor profile _.forOwn(newUser.services, (data) => { // although this is a for loop, a user should only have 1 service newUser.profile.picture = data.picture; newUser.profile.email = data.email; }); return newUser; }); // FIXME: deny user updates and create user api // (currently needed so users can update their settings) Meteor.users.allow({ update() { return true; }, });
Allow an `options` to be passed when initializing modal
var $soloModal = null // Used when allowMultiple = false. // The public API. Modal = { allowMultiple: false, show: function(templateName, data, options){ if($soloModal == null || this.allowMultiple){ var parentNode = document.body var view = Blaze.renderWithData(Template[templateName], data, parentNode) var domRange = view._domrange // TODO: Don't violate against the public API. var $modal = domRange.$('.modal') $modal.on('shown.bs.modal', function(event){ $modal.find('[autofocus]').focus() }) $modal.on('hidden.bs.modal', function(event){ Blaze.remove(view) $soloModal = null }) $soloModal = $modal $modal.modal(options) } }, hide: function(/* optional */ template){ if(template instanceof Blaze.TemplateInstance){ template.$('.modal').modal('hide') }else if($soloModal != null){ $soloModal.modal('hide') } } }
var $soloModal = null // Used when allowMultiple = false. // The public API. Modal = { allowMultiple: false, show: function(templateName, data){ if($soloModal == null || this.allowMultiple){ var parentNode = document.body var view = Blaze.renderWithData(Template[templateName], data, parentNode) var domRange = view._domrange // TODO: Don't violate against the public API. var $modal = domRange.$('.modal') $modal.on('shown.bs.modal', function(event){ $modal.find('[autofocus]').focus() }) $modal.on('hidden.bs.modal', function(event){ Blaze.remove(view) $soloModal = null }) $soloModal = $modal $modal.modal() } }, hide: function(/* optional */ template){ if(template instanceof Blaze.TemplateInstance){ template.$('.modal').modal('hide') }else if($soloModal != null){ $soloModal.modal('hide') } } }
Fix mistake - exec needs to be a single string
/*! * to-clipboard <https://github.com/jonschlinkert/to-clipboard> * * Copyright (c) 2015, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; var cp = require('child_process'); var program = { darwin: { name: 'pbcopy', args: [] }, win32: { name: 'clip', args: [], }, linux: { name: 'xclip', args: ['-selection', 'clipboard'] } }; function toClipboard(args, cb) { var proc = cp.spawn(program.name, program.args, { stdio: ["pipe", "ignore", "ignore"] }); if (cb) { proc.on("error", cb); proc.on("exit", function() { cb(null); }); } proc.stdin.write(args); proc.stdin.end(); } toClipboard.sync = function toClipboardSync(args) { return cp.execSync(program.name + ' ' + program.args.join(' '), { input: args }); }; /** * Expose `toClipboard` */ module.exports = toClipboard;
/*! * to-clipboard <https://github.com/jonschlinkert/to-clipboard> * * Copyright (c) 2015, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; var cp = require('child_process'); var program = { darwin: { name: 'pbcopy', args: [] }, win32: { name: 'clip', args: [], }, linux: { name: 'xclip', args: ['-selection', 'clipboard'] } }; function toClipboard(args, cb) { var proc = cp.spawn(program.name, program.args, { stdio: ["pipe", "ignore", "ignore"] }); if (cb) { proc.on("error", cb); proc.on("exit", function() { cb(null); }); } proc.stdin.write(args); proc.stdin.end(); } toClipboard.sync = function toClipboardSync(args) { return cp.execSync(program.name, program.args, { input: args }); }; /** * Expose `toClipboard` */ module.exports = toClipboard;
Implement the Page Factory Pattern and methods for login
/** * Created with IntelliJ IDEA. * User: jhasmanyquiroz * Date: 11/11/15 * Time: 3:08 PM * To change this template use File | Settings | File Templates. */ package ui.pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import ui.BasePageObject; public class MainPage extends BasePageObject { @FindBy(linkText = "Log In") private WebElement loginButton; @FindBy(xpath = "(//input[@value=''])[2]") private WebElement searchInput; @FindBy(css = "i.cif-search.search-icon") private WebElement searchButton; public MainPage() { PageFactory.initElements(driver, this); waitUntilPageObjectIsLoaded(); } public LoginPage clickLogInButton() { loginButton.click(); return new LoginPage(); } public MainPage setSearchCourseInput(String searchCourse) { searchInput.clear(); searchInput.sendKeys(searchCourse); return this; } public CoursesPage clickSearchButton() { return new CoursesPage(); } public void waitUntilPageObjectIsLoaded() { wait.until(ExpectedConditions.visibilityOf(loginButton)); } }
/** * Created with IntelliJ IDEA. * User: jhasmanyquiroz * Date: 11/11/15 * Time: 3:08 PM * To change this template use File | Settings | File Templates. */ package ui.pages; import framework.BrowserManager; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import ui.BasePageObject; public class MainPage extends BasePageObject { private BrowserManager browser; private WebElement element; public MainPage() { super(); browser = BrowserManager.getInstance(); } public void clickLogInButton() { element = browser.getDriver().findElement(By.linkText("Log In")); element.click(); } public void waitUntilPageObjectIsLoaded() { //To change body of implemented methods use File | Settings | File Templates. } }
Add a function to check if a file exists
# -*- coding:utf-8 -*- import tables import os def init_data_h5(filename): """Initialize a data HDF5 file""" if not file_exists(filename): with tables.openFile(filename, 'w') as f: setattr(f.root._v_attrs, 'n_simu', 0) def file_exists(filename): """Check if a file `filename` exists.""" file_exists = False try: fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0644) os.close(fd) os.remove(filename) except OSError, e: file_exists = True raise e return file_exists def new_simu(filename, data): """Put the simulation data into the HDF5 file""" with tables.openFile(filename, 'a') as f: n_simu = getattr(f.root._v_attrs, 'n_simu') # parse data and put them in a new group simu_group = f.createGroup('/', 'simu' + str(n_simu)) # TODO change value of n_simu
# -*- coding:utf-8 -*- import tables import os def init_data_h5(filename): """Initialize a data HDF5 file""" # Raise en error if the file already exists try: os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0644) except OSError, e: raise e # Else, continue by creating the file else: with tables.openFile(filename, 'w') as f: setattr(f.root._v_attrs, 'n_simu', 0) def new_simu(filename, data): """Put the simulation data into the HDF5 file""" with tables.openFile(filename, 'a') as f: n_simu = getattr(f.root._v_attrs, 'n_simu') # parse data and put them in a new group simu_group = f.createGroup('/', 'simu' + str(n_simu)) # TODO change value of n_simu
Add indexes to 'parent_id', 'lft', 'rgt' columns by default. The point here is to have some indexes. Of course, the appropiate ones will depend on the application and specific use case.
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class {{class}} extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('{{table}}', function(Blueprint $table) { // These columns are needed for Baum's Nested Set implementation to work. // Column names may be changed, but they *must* all exist and be modified // in the model. // Take a look at the model scaffold comments for details. $table->increments('id'); $table->integer('parent_id')->nullable(); $table->integer('lft')->nullable(); $table->integer('rgt')->nullable(); $table->integer('depth')->nullable(); // Add needed columns here (f.ex: name, slug, path, etc.) // $table->string('name', 255); $table->timestamps(); // Default indexes // Add indexes on parent_id, lft, rgt columns by default. Of course, // the correct ones will depend on the application and use case. $table->index('parent_id'); $table->index('lft'); $table->index('rgt'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('{{table}}'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class {{class}} extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('{{table}}', function(Blueprint $table) { // These columns are needed for Baum's Nested Set implementation to work. // Column names may be changed, but they *must* all exist and be modified // in the model. // Take a look at the model scaffold comments for details. $table->increments('id'); $table->integer('parent_id')->nullable(); $table->integer('lft')->nullable(); $table->integer('rgt')->nullable(); $table->integer('depth')->nullable(); // Add needed columns here (f.ex: name, slug, path, etc.) // $table->string('name', 255); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('{{table}}'); } }
PUBDEV-2078: Add extra argument to get per-feature reconstruction error for anomaly detection from Python.
""" AutoEncoder Models """ from model_base import * from metrics_base import * class H2OAutoEncoderModel(ModelBase): """ Class for AutoEncoder models. """ def __init__(self, dest_key, model_json): super(H2OAutoEncoderModel, self).__init__(dest_key, model_json,H2OAutoEncoderModelMetrics) def anomaly(self,test_data,per_feature=False): """ Obtain the reconstruction error for the input test_data. :param test_data: The dataset upon which the reconstruction error is computed. :param per_feature: Whether to return the square reconstruction error per feature. Otherwise, return the mean square error. :return: Return the reconstruction error. """ if not test_data: raise ValueError("Must specify test data") j = H2OConnection.post_json("Predictions/models/" + self._id + "/frames/" + test_data._id, reconstruction_error=True, reconstruction_error_per_feature=per_feature) return h2o.get_frame(j["model_metrics"][0]["predictions"]["frame_id"]["name"])
""" AutoEncoder Models """ from model_base import * from metrics_base import * class H2OAutoEncoderModel(ModelBase): """ Class for AutoEncoder models. """ def __init__(self, dest_key, model_json): super(H2OAutoEncoderModel, self).__init__(dest_key, model_json,H2OAutoEncoderModelMetrics) def anomaly(self,test_data): """ Obtain the reconstruction error for the input test_data. :param test_data: The dataset upon which the reconstruction error is computed. :return: Return the reconstruction error. """ if not test_data: raise ValueError("Must specify test data") j = H2OConnection.post_json("Predictions/models/" + self._id + "/frames/" + test_data._id, reconstruction_error=True) return h2o.get_frame(j["model_metrics"][0]["predictions"]["frame_id"]["name"])
Add box.text namespace. Also switch to oss@box.com for email addr. Fixes #7
# -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='genty', version='0.0.1', description='Allows you to run a test with multiple data sets', long_description=open(join(base_dir, 'README.rst')).read(), author='Box', author_email='oss@box.com', url='https://github.com/box/genty', license=open(join(base_dir, 'LICENSE')).read(), packages=find_packages(exclude=['test']), namespace_packages=[b'box', b'box.test'], test_suite='test', zip_safe=False, ) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='genty', version='0.0.1', description='Allows you to run a test with multiple data sets', long_description=open(join(base_dir, 'README.rst')).read(), author='Box', author_email='peter.potrebic@gmail.com', url='https://github.com/box/genty', license=open(join(base_dir, 'LICENSE')).read(), packages=find_packages(exclude=['test']), namespace_packages=[b'box'], test_suite='test', zip_safe=False, ) if __name__ == '__main__': main()
Update the test model definitions.
from django.db import models from django.utils.encoding import python_2_unicode_compatible from ..base import ModelLookup from ..registry import registry @python_2_unicode_compatible class Thing(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) def __str__(self): return self.name @python_2_unicode_compatible class OtherThing(models.Model): name = models.CharField(max_length=100) thing = models.ForeignKey(Thing) def __str__(self): return self.name @python_2_unicode_compatible class ManyThing(models.Model): name = models.CharField(max_length=100) things = models.ManyToManyField(Thing) def __str__(self): return self.name class ThingLookup(ModelLookup): model = Thing search_fields = ('name__icontains', ) registry.register(ThingLookup) from .test_base import * from .test_decorators import * from .test_fields import * from .test_functional import * from .test_forms import * from .test_templatetags import * from .test_views import * from .test_widgets import *
from django.db import models from ..base import ModelLookup from ..registry import registry class Thing(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) def __unicode__(self): return self.name def __str__(self): return self.name class OtherThing(models.Model): name = models.CharField(max_length=100) thing = models.ForeignKey(Thing) def __unicode__(self): return self.name def __str__(self): return self.name class ManyThing(models.Model): name = models.CharField(max_length=100) things = models.ManyToManyField(Thing) def __unicode__(self): return self.name def __str__(self): return self.name class ThingLookup(ModelLookup): model = Thing search_fields = ('name__icontains', ) registry.register(ThingLookup) from .test_base import * from .test_decorators import * from .test_fields import * from .test_functional import * from .test_forms import * from .test_templatetags import * from .test_views import * from .test_widgets import *
Switch to JSONAPIAdapter with cross domain and csrf headers
import DS from 'ember-data'; export default DS.JSONAPIAdapter.extend({ host: 'http://localhost:8000', buildURL(modelName, id, snapshot, requestType) { // Fix issue where CORS request failed on 301s: Ember does not seem to append trailing // slash to URLs for single documents, but DRF redirects to force a trailing slash var url = this._super(...arguments); if (requestType === 'deleteRecord' || requestType === 'updateRecord' || requestType === 'findRecord') { if (snapshot.record.get('links.self')) { url = snapshot.record.get('links.self'); } } if (url.lastIndexOf('/') !== url.length - 1) { url += '/'; } return url; }, ajax: function(url, method, hash) { hash.crossDomain = true; hash.xhrFields = {withCredentials: true}; return this._super(url, method, hash); }, headers: Ember.computed(function() { return { "X-CSRFToken": Ember.get(document.cookie.match(/csrftoken\=([^;]*)/), "1") }; }).volatile() });
import OsfAdapter from './osf-adapter'; export default DS.JSONAPIAdapter.extend({ host: 'http://localhost:8000', buildURL(modelName, id, snapshot, requestType) { // Fix issue where CORS request failed on 301s: Ember does not seem to append trailing // slash to URLs for single documents, but DRF redirects to force a trailing slash var url = this._super(...arguments); if (requestType === 'deleteRecord' || requestType === 'updateRecord' || requestType === 'findRecord') { if (snapshot.record.get('links.self')) { url = snapshot.record.get('links.self'); } } if (url.lastIndexOf('/') !== url.length - 1) { url += '/'; } return url; }, });
Remove , use bridge instead
'use strict'; angular .module('irma') .factory('resultsManager', resultsManager); resultsManager.$inject = ['$q', '$log', 'Result', 'bridge']; function resultsManager($q, $log, Result, bridge) { return { getResult: getResult }; function _load(scanId, resultId, deferred) { bridge.get({url: '/scan/' + scanId + '/results/' + resultId}) .then(_loadComplete); function _loadComplete(response) { if (response.code !== -1) { var results = _retrieveInstance(response.results); deferred.resolve(results); } } } function _retrieveInstance(resultData) { return new Result(resultData); } function getResult(scanId, resultId) { $log.info('Retrieve result'); var deferred = $q.defer(); _load(scanId, resultId, deferred); return deferred.promise; } }
'use strict'; angular .module('irma') .factory('resultsManager', resultsManager); resultsManager.$inject = ['$http', '$q', '$log', 'Result']; function resultsManager($http, $q, $log, Result) { return { getResult: getResult }; function _load(scanId, resultId, deferred) { $http.get('/_api/scan/' + scanId + '/results/' + resultId) .success(_loadComplete) .catch(_loadFailed); function _loadComplete(response) { var results = _retrieveInstance(response.results); deferred.resolve(results); } function _loadFailed(error) { $log.error('XHR failed for _load result:' + error.data); } } function _retrieveInstance(resultData) { return new Result(resultData); } function getResult(scanId, resultId) { $log.info('Retrieve result'); var deferred = $q.defer(); _load(scanId, resultId, deferred); return deferred.promise; } }
Remove footer to avoid floating footer
<?php get_header();?> <?php $catid = get_cat_id( single_cat_title("",false) );?> <head><title>Search result for <?php echo '"' . $_GET['s'] . '"' . ' - '; bloginfo('name'); ?></title></head> <div class="container contain-content"> <?php get_search_form();?> <?php if (have_posts()) : while(have_posts()) : the_post();?> <div class="shadow-box"> <a href="<?php the_permalink();?>" title = "<?php the_title();?>"><h3 class = "text-center"><?php the_title();?></h3></a> <h6 class = "text-muted text-center">Posted by <?php the_author();?> on <?php the_time('F jS, Y'); ?></h6> <center><?php if (has_post_thumbnail()) {the_post_thumbnail('large',array('class' => 'img-responsive img-thumbnail'));} ?></center> <p class = "content"><?php the_excerpt(); ?></p> </div> <?php endwhile; else : ?> <div class="shadow-box block-center"> <center> <h4 style = "margin-top:5px;">We can't found what you are looking for.</h4> <p class= "text-muted">Try other keyword or <a href="<?php echo get_option('home');?>">Go Home?</a></p> </center> </div> <?php endif; ?> </div>
<?php get_header();?> <?php $catid = get_cat_id( single_cat_title("",false) );?> <head><title>Search result for <?php echo '"' . $_GET['s'] . '"' . ' - '; bloginfo('name'); ?></title></head> <div class="container contain-content"> <?php get_search_form();?> <?php if (have_posts()) : while(have_posts()) : the_post();?> <div class="shadow-box"> <a href="<?php the_permalink();?>" title = "<?php the_title();?>"><h3 class = "text-center"><?php the_title();?></h3></a> <h6 class = "text-muted text-center">Posted by <?php the_author();?> on <?php the_time('F jS, Y'); ?></h6> <center><?php if (has_post_thumbnail()) {the_post_thumbnail('large',array('class' => 'img-responsive img-thumbnail'));} ?></center> <p class = "content"><?php the_excerpt(); ?></p> </div> <?php endwhile; else : ?> <p><?php _e('No post right now.'); ?></p> <?php endif; ?> </div> <?php get_footer();?>
Update stacktrace info with new model path structure
function $init$native$Exception$before(exc) { var _caller=arguments.callee.caller.caller; exc.stack_trace=[]; while(_caller) { exc.stack_trace.push(_caller); _caller = _caller.caller; } } Exception.$$.prototype.printStackTrace = function() { var _c = className(this); if (this.message.size > 0) { _c += ' "' + this.message + '"'; } print(_c); for (var i=0; i<this.stack_trace.length; i++) { var f = this.stack_trace[i]; var mm = f.$$metamodel$$; if (typeof(mm)==='function') { mm = mm(); f.$$metamodel$$=mm; } if (mm) { var _src = ''; if (i==0) { if (this.$loc && this.$file) _src = ' (' + this.$file + " " + this.$loc + ')'; } print(" at " + mm[0] + "::" + mm.d[mm.d.length-1] + _src); } } }
function $init$native$Exception$before(exc) { var _caller=arguments.callee.caller.caller; exc.stack_trace=[]; while(_caller) { exc.stack_trace.push(_caller); _caller = _caller.caller; } } Exception.$$.prototype.printStackTrace = function() { var _c = className(this); if (this.message.size > 0) { _c += ' "' + this.message + '"'; } print(_c); for (var i=0; i<this.stack_trace.length; i++) { var f = this.stack_trace[i]; var mm = f.$$metamodel$$; if (typeof(mm)==='function') { mm = mm(); f.$$metamodel$$=mm; } if (mm) { var _src = ''; if (i==0) { if (this.$loc && this.$file) _src = ' (' + this.$file + " " + this.$loc + ')'; } print(" at " + mm.pkg + "::" + mm.d.$nm + _src); } } }
Return a sample result, so can test methods that perform a sample git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/trunk@907681 13f79535-47bb-0310-9956-ffa450edef68 Former-commit-id: d8d665d37c5505160ac98d296685f055e1255d8e
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.protocol.http.sampler; import java.net.URL; /** * Dummy HTTPSampler class for use by classes that need an HTTPSampler, but that * don't need an actual sampler, e.g. for Parsing testing. */ public final class HTTPNullSampler extends HTTPSamplerBase { private static final long serialVersionUID = 240L; /** * Returns a sample Result with the request fields filled in. * * {@inheritDoc} */ @Override protected HTTPSampleResult sample(URL u, String method, boolean areFollowingRedirec, int depth) { HTTPSampleResult res = new HTTPSampleResult(); res.sampleStart(); res.setURL(u); res.sampleEnd(); return res; // throw new UnsupportedOperationException("For test purposes only"); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.protocol.http.sampler; import java.net.URL; /** * Dummy HTTPSampler class for use by classes that need an HTTPSampler, but that * don't need an actual sampler, e.g. for Parsing testing. */ public final class HTTPNullSampler extends HTTPSamplerBase { private static final long serialVersionUID = 240L; /* * (non-Javadoc) * * @see org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase#sample(java.net.URL, * java.lang.String, boolean, int) */ @Override protected HTTPSampleResult sample(URL u, String s, boolean b, int i) { throw new UnsupportedOperationException("For test purposes only"); } }
Make sure dependency are loaded on demand
'use strict'; function Yam(id, options) { if (!id) { throw new Error('You must specify an id.'); } var path = require('path'); var merge = require('lodash.merge'); var Config = require('./config'); var configUtils = require('./utils/config-utils'); var projectPath = configUtils.getCurrentPath(); var homePath = configUtils.getUserHomeDirectory(); var localOptions = {}; var localHomePath = homePath + '/.' + id; var localProjectPath = projectPath + '/.' + id; if (options && options.primary) { localProjectPath = options.primary + '/.' + id; } if (options && options.secondary) { localHomePath = options.secondary + '/.' + id; } localOptions = { primary: path.normalize(localProjectPath), secondary: path.normalize(localHomePath) }; this.id = id; this.options = merge( new Config(localOptions.secondary), new Config(localOptions.primary) ); return this; } Yam.prototype.getAll = function getAll() { return this.options; }; Yam.prototype.get = function get(key) { var value = this.options[key]; return value ? value : undefined; }; module.exports = Yam;
'use strict'; var path = require('path'); var merge = require('lodash.merge'); var configUtils = require('./utils/config-utils'); var Config = require('./config'); var getCurrentPath = configUtils.getCurrentPath; var getUserHomeDirectory = configUtils.getUserHomeDirectory; function Yam(id, options) { if (!id) { throw new Error('You must specify an id.'); } var projectPath = getCurrentPath(); var homePath = getUserHomeDirectory(); var localOptions = {}; var localHomePath = homePath + '/.' + id; var localProjectPath = projectPath + '/.' + id; if (options && options.primary) { localProjectPath = options.primary + '/.' + id; } if (options && options.secondary) { localHomePath = options.secondary + '/.' + id; } localOptions = { primary: path.normalize(localProjectPath), secondary: path.normalize(localHomePath) }; this.id = id; this.options = merge( new Config(localOptions.secondary), new Config(localOptions.primary) ); return this; } Yam.prototype.getAll = function getAll() { return this.options; }; Yam.prototype.get = function get(key) { var value = this.options[key]; return value ? value : undefined; }; module.exports = Yam;
refactor(presentation): Move cursor functionality to presentation
import keypress from 'keypress'; import { Slide } from './Slide'; import { Cursor } from './Cursor'; export class Presentation { constructor() { this._slides = []; this._currentSlideIndex = 0; this._cursor = new Cursor([process.stdout], [process.stdin]); keypress(process.stdin); process.stdin.setRawMode(true); process.stdin.setEncoding('utf8'); } /** * Push slide instance * @param {Slide} slide * @returns {Presentation} */ pushSlide(slide) { if (!(slide instanceof Slide)) throw new Error('You must provide Slide instance'); this._slides.push(slide); return this; } /** * Renders specified slide * @param {Number} index Slide index in presentation * @returns {Presentation} */ renderSlide(index) { this._slides[index].render(); return this; } /** * Render the next slide * @returns {Presentation} */ nextSlide() { return this; } /** * Render the previous slide * @returns {Presentation} */ prevSlide() { return this; } }
import { Slide } from './Slide'; export class Presentation { constructor() { this._slides = []; this._currentSlideIndex = 0; } /** * Push slide instance * @param {Slide} slide * @returns {Presentation} */ pushSlide(slide) { if (!(slide instanceof Slide)) throw new Error('You must provide Slide instance'); this._slides.push(slide); return this; } /** * Renders specified slide * @param {Number} index Slide index in presentation * @returns {Presentation} */ renderSlide(index) { this._slides[index].render(); return this; } /** * Render the next slide * @returns {Presentation} */ nextSlide() { return this; } /** * Render the previous slide * @returns {Presentation} */ prevSlide() { return this; } }
Add raven.NewHttp capturing to non panic errors too
package sentry import ( "errors" "fmt" "net/http" "runtime/debug" "github.com/getsentry/raven-go" "github.com/gin-gonic/gin" ) func Recovery(client *raven.Client, onlyCrashes bool) gin.HandlerFunc { return func(c *gin.Context) { defer func() { flags := map[string]string{ "endpoint": c.Request.RequestURI, } if rval := recover(); rval != nil { debug.PrintStack() rvalStr := fmt.Sprint(rval) packet := raven.NewPacket(rvalStr, raven.NewException(errors.New(rvalStr), raven.NewStacktrace(2, 3, nil)), raven.NewHttp(c.Request)) client.Capture(packet, flags) c.AbortWithStatus(http.StatusInternalServerError) } if !onlyCrashes { for _, item := range c.Errors { packet := raven.NewPacket(item.Error(), &raven.Message{ Message: item.Error(), Params: []interface{}{item.Meta}, }, raven.NewHttp(c.Request)) client.Capture(packet, flags) } } }() c.Next() } }
package sentry import ( "errors" "fmt" "net/http" "runtime/debug" "github.com/getsentry/raven-go" "github.com/gin-gonic/gin" ) func Recovery(client *raven.Client, onlyCrashes bool) gin.HandlerFunc { return func(c *gin.Context) { defer func() { flags := map[string]string{ "endpoint": c.Request.RequestURI, } if rval := recover(); rval != nil { debug.PrintStack() rvalStr := fmt.Sprint(rval) packet := raven.NewPacket(rvalStr, raven.NewException(errors.New(rvalStr), raven.NewStacktrace(2, 3, nil)), raven.NewHttp(c.Request)) client.Capture(packet, flags) c.AbortWithStatus(http.StatusInternalServerError) } if !onlyCrashes { for _, item := range c.Errors { packet := raven.NewPacket(item.Error(), &raven.Message{ Message: item.Error(), Params: []interface{}{item.Meta}, }) client.Capture(packet, flags) } } }() c.Next() } }
Handle situation when kwargs is None
from django.conf import settings from django.core import urlresolvers from django.utils import translation from localeurl import utils def reverse(*args, **kwargs): reverse_kwargs = kwargs.get('kwargs', {}) if reverse_kwargs!=None: locale = utils.supported_language(reverse_kwargs.pop('locale', translation.get_language())) else: locale = translation.get_language() url = django_reverse(*args, **kwargs) _, path = utils.strip_script_prefix(url) return utils.locale_url(path, locale) django_reverse = None def patch_reverse(): """ Monkey-patches the urlresolvers.reverse function. Will not patch twice. """ global django_reverse if urlresolvers.reverse is not reverse: django_reverse = urlresolvers.reverse urlresolvers.reverse = reverse if settings.USE_I18N: patch_reverse()
from django.conf import settings from django.core import urlresolvers from django.utils import translation from localeurl import utils def reverse(*args, **kwargs): reverse_kwargs = kwargs.get('kwargs', {}) locale = utils.supported_language(reverse_kwargs.pop('locale', translation.get_language())) url = django_reverse(*args, **kwargs) _, path = utils.strip_script_prefix(url) return utils.locale_url(path, locale) django_reverse = None def patch_reverse(): """ Monkey-patches the urlresolvers.reverse function. Will not patch twice. """ global django_reverse if urlresolvers.reverse is not reverse: django_reverse = urlresolvers.reverse urlresolvers.reverse = reverse if settings.USE_I18N: patch_reverse()
fix(email): Remove flash until author required bug is fixed
export function ifNoUserRedirectTo(url, message, type = 'errors') { return function(req, res, next) { const { path } = req; if (req.user) { return next(); } req.flash(type, { msg: message || `You must be signed in to access ${path}` }); return res.redirect(url); }; } export function ifNoUserSend(sendThis) { return function(req, res, next) { if (req.user) { return next(); } return res.status(200).send(sendThis); }; } export function ifNoUser401(req, res, next) { if (req.user) { return next(); } return res.status(401).end(); } export function flashIfNotVerified(req, res, next) { return next(); /* // disabled until authorized required bug is fixed const user = req.user; if (!user) { return next(); } const email = req.user.email; const emailVerified = req.user.emailVerified; if (!email || !emailVerified) { req.flash('info', { msg: 'Please verify your email address ' + '<a href="/update-email">here</a>.' }); } */ }
export function ifNoUserRedirectTo(url, message, type = 'errors') { return function(req, res, next) { const { path } = req; if (req.user) { return next(); } req.flash(type, { msg: message || `You must be signed in to access ${path}` }); return res.redirect(url); }; } export function ifNoUserSend(sendThis) { return function(req, res, next) { if (req.user) { return next(); } return res.status(200).send(sendThis); }; } export function ifNoUser401(req, res, next) { if (req.user) { return next(); } return res.status(401).end(); } export function flashIfNotVerified(req, res, next) { const user = req.user; if (!user) { return next(); } const email = req.user.email; const emailVerified = req.user.emailVerified; if (!email || !emailVerified) { req.flash('info', { msg: 'Please verify your email address ' + '<a href="/update-email">here</a>.' }); } return next(); }
Increase the height of the Iframe Signed-off-by: Brianna Major <6a62c0472e857db5994824f147beeb095c78d3a5@kitware.com>
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Iframe from 'react-iframe' import { Typography, withStyles } from '@material-ui/core'; import PageHead from './page-head'; import PageBody from './page-body'; const styles = () => ({ iframe: { border: 0, left: 0, position: 'absolute', top: 0, width:'100%', height:'100%' }, container: { overflow: 'hidden', position: 'relative', paddingTop: '100%' } }); class Notebook extends Component { render = () => { const { fileId, classes } = this.props; const baseUrl = `${window.location.origin}/api/v1`; return ( <div> <PageHead> <Typography color="inherit" gutterBottom variant="display1"> Notebook </Typography> </PageHead> <PageBody> <div className={classes.container}> <Iframe id='iframe' url={`${baseUrl}/notebooks/${fileId}/html`} className={classes.iframe}/> </div> </PageBody> </div> ); } } Notebook.propTypes = { fileId: PropTypes.string } Notebook.defaultProps = { fileId: null, } export default withStyles(styles)(Notebook)
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Iframe from 'react-iframe' import { Typography, withStyles } from '@material-ui/core'; import PageHead from './page-head'; import PageBody from './page-body'; const styles = () => ({ iframe: { border: 0, left: 0, position: 'absolute', top: 0, width:'100%', height:'100%' }, container: { overflow: 'hidden', position: 'relative', paddingTop: '72%' } }); class Notebook extends Component { render = () => { const { fileId, classes } = this.props; const baseUrl = `${window.location.origin}/api/v1`; return ( <div> <PageHead> <Typography color="inherit" gutterBottom variant="display1"> Notebook </Typography> </PageHead> <PageBody> <div className={classes.container}> <Iframe id='iframe' url={`${baseUrl}/notebooks/${fileId}/html`} className={classes.iframe}/> </div> </PageBody> </div> ); } } Notebook.propTypes = { fileId: PropTypes.string } Notebook.defaultProps = { fileId: null, } export default withStyles(styles)(Notebook)
Fix broken test due to version update
<?php namespace Stripe; class BankAccountTest extends TestCase { public function testVerify() { self::authorizeFromEnv(); $customer = self::createTestCustomer(); $bankAccount = $customer->sources->create(array( 'source' => array( 'object' => 'bank_account', 'account_holder_type' => 'individual', 'account_number' => '000123456789', 'account_holder_name' => 'John Doe', 'routing_number' => '110000000', 'country' => 'US' ) )); $this->assertSame($bankAccount->status, 'new'); $bankAccount = $bankAccount->verify(array( 'amounts' => array(32, 45) )); $this->assertSame($bankAccount->status, 'verified'); } }
<?php namespace Stripe; class BankAccountTest extends TestCase { public function testVerify() { self::authorizeFromEnv(); $customer = self::createTestCustomer(); $bankAccount = $customer->sources->create(array( 'source' => array( 'object' => 'bank_account', 'account_holder_type' => 'individual', 'account_number' => '000123456789', 'name' => 'John Doe', 'routing_number' => '110000000', 'country' => 'US' ) )); $this->assertSame($bankAccount->status, 'new'); $bankAccount = $bankAccount->verify(array( 'amounts' => array(32, 45) )); $this->assertSame($bankAccount->status, 'verified'); } }
Add yields to avoid race conditions
import Component from '@ember/component'; import { inject as service } from '@ember/service'; import { task } from 'ember-concurrency'; export default Component.extend({ currentUser: service(), store: service(), flashMessages: service(), startRoundModal: false, startRoundModalError: false, startRound: task(function *() { try { let round = yield this.model.start({ 'by': this.get('currentUser.user.id') }); yield this.model.reload(); yield this.get('store').pushPayload('round', round); yield this.get('model.session.competitors').invoke('reload'); yield this.get('model.appearances').invoke('reload'); yield this.get('model.panelists').invoke('reload'); this.set('startRoundModal', false); this.set('startRoundModalError', false); this.get('flashMessages').success("Started!"); } catch(e) { this.set('startRoundModalError', true); } }).drop(), });
import Component from '@ember/component'; import { inject as service } from '@ember/service'; import { task } from 'ember-concurrency'; export default Component.extend({ currentUser: service(), store: service(), flashMessages: service(), startRoundModal: false, startRoundModalError: false, startRound: task(function *() { try { let round = yield this.model.start({ 'by': this.get('currentUser.user.id') }); this.model.reload(); this.get('store').pushPayload('round', round); this.get('model.session.competitors').invoke('reload'); this.get('model.appearances').invoke('reload'); this.set('startRoundModal', false); this.set('startRoundModalError', false); this.get('flashMessages').success("Started!"); } catch(e) { this.set('startRoundModalError', true); } }).drop(), });
Fix warning in eclipse (missing ;)
#set( $prefix=$className.toLowerCase()) #set( $symbol_dollar = '$' ) 'use strict'; function ${className}ListController($scope, $location, ${className}) { $scope.${prefix}s = ${className}.query(); $scope.goto${className}NewPage = function () { ${symbol_dollar}location.path("/${prefix}/new"); }; $scope.delete${className} = function (${prefix}) { ${prefix}.$delete({'id':${prefix}.id}, function () { $location.path('/'); }); }; } function ${className}DetailController($scope, $routeParams, $location, ${className}) { $scope.${prefix} = ${className}.get({id:$routeParams.id}, function (${prefix}) { }); $scope.goto${className}ListPage = function () { $location.path("/"); }; } function ${className}NewController($scope, $location, ${className}) { $scope.submit = function () { ${className}.save($scope.$prefix, function ($prefix) { $location.path('/'); }); }; $scope.gotoTodoListPage = function () { $location.path("/"); }; }
#set( $prefix=$className.toLowerCase()) #set( $symbol_dollar = '$' ) 'use strict'; function ${className}ListController($scope, $location, ${className}) { $scope.${prefix}s = ${className}.query(); $scope.goto${className}NewPage = function () { ${symbol_dollar}location.path("/${prefix}/new") }; $scope.delete${className} = function (${prefix}) { ${prefix}.$delete({'id':${prefix}.id}, function () { $location.path('/'); }); }; } function ${className}DetailController($scope, $routeParams, $location, ${className}) { $scope.${prefix} = ${className}.get({id:$routeParams.id}, function (${prefix}) { }); $scope.goto${className}ListPage = function () { $location.path("/") }; } function ${className}NewController($scope, $location, ${className}) { $scope.submit = function () { ${className}.save($scope.$prefix, function ($prefix) { $location.path('/'); }); }; $scope.gotoTodoListPage = function () { $location.path("/") }; }
Update telescope-search for iron:router 1.0
adminNav.push({ route: 'searchLogs', label: 'Search Logs' }); Meteor.startup(function () { PostsSearchController = PostsListController.extend({ view: 'search', onBeforeAction: function() { if ("q" in this.params) { Session.set("searchQuery", this.params.q); } this.next(); } }); Router.onBeforeAction(Router._filters.isAdmin, {only: ['logs']}); // Search Router.route('/search/:limit?', { name: 'search', controller: PostsSearchController }); // Search Logs Router.route('/logs/:limit?', { name: 'searchLogs', waitOn: function () { var limit = this.params.limit || 100; if(Meteor.isClient) { Session.set('logsLimit', limit); } return Meteor.subscribe('searches', limit); }, data: function () { return Searches.find({}, {sort: {timestamp: -1}}); }, fastRender: true }); });
adminNav.push({ route: 'searchLogs', label: 'Search Logs' }); Meteor.startup(function () { PostsSearchController = PostsListController.extend({ view: 'search', onBeforeAction: function() { if ("q" in this.params) { Session.set("searchQuery", this.params.q); } } }); Router.onBeforeAction(Router._filters.isAdmin, {only: ['logs']}); // Search Router.route('/search/:limit?', { name: 'search', controller: PostsSearchController }); // Search Logs Router.route('/logs/:limit?', { name: 'searchLogs', waitOn: function () { var limit = this.params.limit || 100; if(Meteor.isClient) { Session.set('logsLimit', limit); } return Meteor.subscribe('searches', limit); }, data: function () { return Searches.find({}, {sort: {timestamp: -1}}); }, fastRender: true }); });
Improve error report on failed sbp command load
var fs = require('fs') var path = require('path'); var log = require('../../../log').logger('opensbp'); // Load all the files in the 'routes' directory and process them as route-producing modules exports.load = function() { var commandDir = __dirname; var files = fs.readdirSync(commandDir); var retval = {} files.forEach(function (file) { filePath = path.resolve('./', commandDir, file) if((path.extname(filePath) == '.js') && (path.basename(filePath) != 'index.js')) { try { commands = require(filePath); for(var attr in commands) { retval[attr] = commands[attr]; } log.debug('Loaded OpenSBP commands from "' + filePath + '"'); } catch(e) { log.warn('Could not load OpenSBP Commands from "' + filePath + '": ' + e); log.error(e); } } }); return retval; }
var fs = require('fs') var path = require('path'); var log = require('../../../log').logger('opensbp'); // Load all the files in the 'routes' directory and process them as route-producing modules exports.load = function() { var commandDir = __dirname; var files = fs.readdirSync(commandDir); var retval = {} files.forEach(function (file) { filePath = path.resolve('./', commandDir, file) if((path.extname(filePath) == '.js') && (path.basename(filePath) != 'index.js')) { try { commands = require(filePath); for(var attr in commands) { retval[attr] = commands[attr]; } log.debug('Loaded OpenSBP commands from "' + filePath + '"'); } catch(e) { log.warn('Could not load OpenSBP Commands from "' + filePath + '": ' + e); } } }); return retval; }
Prepend 'Advanced' instead of replacing the carat span
// Thanks to GVSU https://github.com/gvsulib/Summon-2.0-Scripts) and others for sharing your summon hacks $(document).ready(function() { //Dev // var cssPath = '//bypass.hazchem.library.uq.edu.au/summonhacks/summonhacks/',libDetailPageId, newHref, libCurrentURL, record, recordParts, thisID,libCurrentURL = window.location.hash.substring(1); //Staging var cssPath = '//libio.library.uq.edu.au/summonhacks/',libDetailPageId, newHref, libCurrentURL, record, recordParts, thisID,libCurrentURL = window.location.hash.substring(1); // Add custom styles $('head').append('<link rel="stylesheet" type="text/css" href="' + cssPath + 'summon2mods.css" />'); // Accessibility added for advanced search titles $('div.searchBox div.queryBox span.caret').parent().attr('title','advanced search'); $('div.search div.queryBox span.caret').parent().attr('title','advanced search'); //Add text to the advanced search button to clearly indicate what it is $('div.search div.queryBox span.caret').parent().prepend('Advanced'); });
// Thanks to GVSU https://github.com/gvsulib/Summon-2.0-Scripts) and others for sharing your summon hacks $(document).ready(function() { //Dev // var cssPath = '//bypass.hazchem.library.uq.edu.au/summonhacks/summonhacks/',libDetailPageId, newHref, libCurrentURL, record, recordParts, thisID,libCurrentURL = window.location.hash.substring(1); //Staging var cssPath = '//libio.library.uq.edu.au/summonhacks/',libDetailPageId, newHref, libCurrentURL, record, recordParts, thisID,libCurrentURL = window.location.hash.substring(1); // Add custom styles $('head').append('<link rel="stylesheet" type="text/css" href="' + cssPath + 'summon2mods.css" />'); // Accessibility added for advanced search titles $('div.searchBox div.queryBox span.caret').parent().attr('title','advanced search'); $('div.search div.queryBox span.caret').parent().attr('title','advanced search'); //Add text to the advanced search button to clearly indicate what it is $('div.search div.queryBox span.caret').parent().attr('value', 'Advanced'); });
[*] Make nullable fields in channels schema
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateChannelTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('channels', function (Blueprint $table) { $table->increments('id'); $table->string('name', 64); $table->string('password')->nullable(); $table->unsignedInteger('creator_id')->index(); $table->boolean('hidden')->default(false); $table->string('image_url')->nullable(); $table->timestamps(); $table->foreign('creator_id')->references('id')->on('users')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('channels'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateChannelTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('channels', function (Blueprint $table) { $table->increments('id'); $table->string('name', 64); $table->string('password'); $table->unsignedInteger('creator_id')->index(); $table->boolean('hidden')->default(false); $table->string('image_url'); $table->timestamps(); $table->foreign('creator_id')->references('id')->on('users')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('channels'); } }
Set a minimum height to prevent the menu from surrendering it's entire space
package org.pentaho.ui.xul.swing.tags; import java.awt.Dimension; import java.awt.GridBagLayout; import java.util.ArrayList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPanel; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.containers.XulMenubar; import org.pentaho.ui.xul.swing.SwingElement; public class SwingMenubar extends SwingElement implements XulMenubar{ private JMenuBar menuBar; public SwingMenubar(XulComponent parent, XulDomContainer domContainer, String tagName) { super("menubar"); children = new ArrayList<XulComponent>(); menuBar = new JMenuBar(); menuBar.setMinimumSize(new Dimension(20,20)); managedObject = menuBar; } @Override public void layout(){ for(XulComponent comp : children){ if(comp instanceof SwingMenu){ this.menuBar.add((JMenu) ((SwingMenu) comp).getManagedObject()); } } } }
package org.pentaho.ui.xul.swing.tags; import java.awt.GridBagLayout; import java.util.ArrayList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPanel; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.containers.XulMenubar; import org.pentaho.ui.xul.swing.SwingElement; public class SwingMenubar extends SwingElement implements XulMenubar{ private JMenuBar menuBar; public SwingMenubar(XulComponent parent, XulDomContainer domContainer, String tagName) { super("menubar"); children = new ArrayList<XulComponent>(); menuBar = new JMenuBar(); managedObject = menuBar; } @Override public void layout(){ for(XulComponent comp : children){ if(comp instanceof SwingMenu){ this.menuBar.add((JMenu) ((SwingMenu) comp).getManagedObject()); } } } }
Use gomegamatcher.MatchYAML instead of gomega's MatchYAML [#129671425] Signed-off-by: Angela Chin <09c3fe443cd90255b3ab6945ab331bb5cdf11ccb@pivotal.io>
package core_test import ( "github.com/pivotal-cf-experimental/destiny/core" "github.com/pivotal-cf-experimental/gomegamatchers" "gopkg.in/yaml.v2" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Manifest", func() { Describe("PropertiesTurbulenceAgentAPI", func() { It("serializes the turbulence properties", func() { expectedYAML := `host: 1.2.3.4 password: secret ca_cert: some-cert` actualYAML, err := yaml.Marshal(core.PropertiesTurbulenceAgentAPI{ Host: "1.2.3.4", Password: "secret", CACert: "some-cert", }) Expect(err).NotTo(HaveOccurred()) Expect(actualYAML).To(gomegamatchers.MatchYAML(expectedYAML)) }) }) })
package core_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/pivotal-cf-experimental/destiny/core" . "github.com/pivotal-cf-experimental/gomegamatchers" "gopkg.in/yaml.v2" ) var _ = Describe("Manifest", func() { Describe("PropertiesTurbulenceAgentAPI", func() { It("serializes the turbulence properties", func() { expectedYAML := `host: 1.2.3.4 password: secret ca_cert: some-cert` actualYAML, err := yaml.Marshal(core.PropertiesTurbulenceAgentAPI{ Host: "1.2.3.4", Password: "secret", CACert: "some-cert", }) Expect(err).NotTo(HaveOccurred()) Expect(actualYAML).To(MatchYAML(expectedYAML)) }) }) })
Update dsub version to 0.3.0.dev0 PiperOrigin-RevId: 241419925
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.3.0.dev0'
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.2.6'
Read long description from readme always
"""Setup for drewtils project.""" try: from setuptools import setup setupTools = True except ImportError: from distutils.core import setup setupTools = False _classifiers = [ 'License :: OSI Approved :: MIT License', ] with open('README.rst') as readme: long_description = readme.read() setupArgs = { 'name': 'drewtils', 'version': "0.1.9", 'packages': ['drewtils'], 'author': 'Andrew Johnson', 'author_email': 'drewej@protonmail.com', 'description': 'Simple tools to make testing and file parsing easier', 'long_description': long_description, 'license': 'MIT', 'keywords': 'parsing files', 'url': 'https://github.com/drewejohnson/drewtils', 'classifiers': _classifiers, } if setupTools: setupArgs.update(**{ 'test_suite': 'drewtils.tests', 'python_requires': '>=2.7,!=3.1,!=3.2,!=3.3,!=3.4' }) setup(**setupArgs)
"""Setup for drewtils project.""" import os try: from setuptools import setup setupTools = True except ImportError: from distutils.core import setup setupTools = False _classifiers = [ 'License :: OSI Approved :: MIT License', ] if os.path.exists('README.rst'): with open('README.rst') as readme: long_description = readme.read() else: long_description = '' setupArgs = { 'name': 'drewtils', 'version': "0.1.9", 'packages': ['drewtils'], 'author': 'Andrew Johnson', 'author_email': 'drewej@protonmail.com', 'description': 'Simple tools to make testing and file parsing easier', 'long_description': long_description, 'license': 'MIT', 'keywords': 'parsing files', 'url': 'https://github.com/drewejohnson/drewtils', 'classifiers': _classifiers, } if setupTools: setupArgs.update(**{ 'test_suite': 'drewtils.tests', 'python_requires': '>=2.7,!=3.1,!=3.2,!=3.3,!=3.4' }) setup(**setupArgs)
Save action meat as JSON
<?php namespace BenAllfree\Trackable\Models; use Illuminate\Database\Eloquent\Model; class Action extends Model { protected $fillable = ['contact_id', 'event', 'ip_address', 'user_agent', 'referer', 'url', 'exited_at', 'request_method']; protected $dates = ['created_at', 'updated_at', 'exited_at']; static function goal($contact_id, $event, $data=[]) { $a = self::create([ 'contact_id'=>$contact_id, 'event'=>$event, 'ip_address'=>\Request::server('REMOTE_ADDR'), 'user_agent'=>\Request::server('HTTP_USER_AGENT'), 'referer'=>\Request::server('HTTP_REFERER'), 'url'=>\Request::url(), 'request_method'=>\Request::server('REQUEST_METHOD'), ]); foreach($data as $k=>$v) { \ActionMeta::create([ 'action_id'=>$a->id, 'key'=>$k, 'value'=>json_encode($v), ]); } return $a; } }
<?php namespace BenAllfree\Trackable\Models; use Illuminate\Database\Eloquent\Model; class Action extends Model { protected $fillable = ['contact_id', 'event', 'ip_address', 'user_agent', 'referer', 'url', 'exited_at', 'request_method']; protected $dates = ['created_at', 'updated_at', 'exited_at']; static function goal($contact_id, $event, $data=[]) { $a = self::create([ 'contact_id'=>$contact_id, 'event'=>$event, 'ip_address'=>\Request::server('REMOTE_ADDR'), 'user_agent'=>\Request::server('HTTP_USER_AGENT'), 'referer'=>\Request::server('HTTP_REFERER'), 'url'=>\Request::url(), 'request_method'=>\Request::server('REQUEST_METHOD'), ]); foreach($data as $k=>$v) { \ActionMeta::create([ 'action_id'=>$a->id, 'key'=>$k, 'value'=>$v, ]); } return $a; } }
Use pandoc to convert README from MD to RST.
#!/usr/bin/env python from setuptools import setup try: import pypandoc description = pypandoc.convert('README.md', 'rst') except (IOError, ImportError): description = open('README.md').read() setup( name='djoser', version='0.0.1', packages=['djoser'], license='MIT', author='SUNSCRAPERS', description='REST version of Django authentication system.', author_email='info@sunscrapers.com', long_description=description, install_requires=[ 'Django>=1.5', 'djangorestframework>=2.4.0', ], tests_require=[ 'djet>=0.0.10' ], include_package_data=True, zip_safe=False, url='https://github.com/sunscrapers/djoser', classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ] )
#!/usr/bin/env python from setuptools import setup setup( name='djoser', version='0.0.1', packages=['djoser'], license='MIT', author='SUNSCRAPERS', description='REST version of Django authentication system.', author_email='info@sunscrapers.com', long_description=open('README.md').read(), install_requires=[ 'Django>=1.5', 'djangorestframework>=2.4.0', ], tests_require=[ 'djet>=0.0.10' ], include_package_data=True, zip_safe=False, url='https://github.com/sunscrapers/djoser', classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ] )
Revert "Removing a few lines that had to do with a different project" This reverts commit 27252a00156f27a96df7acd8ae5f7450d84c7cc0.
<?php include_once('phpviddler.php'); // uses('RequestCache'); loadModels(); $GLOBALS['total_requests'] = 0; $GLOBALS['total_request_time'] = 0; class Php5viddler extends Phpviddler { var $requireCache = false; function sendRequest($method=null,$args=null,$postmethod='get',$tryagain=true) { $result = parent::sendRequest($method, $args, $postmethod); if($tryagain && is_null($result)) { $result = parent::sendRequest($method, $args, $postmethod, false); } elseif(is_null($result)) { throw new ViddlerException("No response", $method, 8888, 'n/a'); } if(is_array($result) && $result['error']) { throw new ViddlerException($result['error']['description'], $method, $result['error']['code'], $result['error']['details']); } return $result; } } class ViddlerException extends Exception { var $details; var $method; public function __construct($message, $method, $code=0, $details='') { $this->details = $details; $this->method = $method; parent::__construct($message, $code); } public function getDetails() { return $this->details; } public function __toString() { return "{$this->method} exception [{$this->code}]: {$this->getMessage()} ({$this->details})\n"; } } ?>
<?php include_once('phpviddler.php'); class Php5viddler extends Phpviddler { function sendRequest($method=null,$args=null,$postmethod='get',$tryagain=true) { $result = parent::sendRequest($method, $args, $postmethod); if($tryagain && is_null($result)) { $result = parent::sendRequest($method, $args, $postmethod, false); } elseif(is_null($result)) { throw new ViddlerException("No response", $method, 8888, 'n/a'); } if(is_array($result) && $result['error']) { throw new ViddlerException($result['error']['description'], $method, $result['error']['code'], $result['error']['details']); } return $result; } } class ViddlerException extends Exception { var $details; var $method; public function __construct($message, $method, $code=0, $details='') { $this->details = $details; $this->method = $method; parent::__construct($message, $code); } public function getDetails() { return $this->details; } public function __toString() { return "{$this->method} exception [{$this->code}]: {$this->getMessage()} ({$this->details})\n"; } } ?>
Make MongoDb config's dependencies optional
/* * Copyright © 2017 the original authors (http://cereebro.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.cereebro.spring.boot.autoconfigure.mongo; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.mongodb.MongoClient; /** * MongoDB detector auto configuration, depending on MongoDb classes being * available on the classpath. Requires a separate configuration class to * prevent issues with optional classes. * * @author lwarrot */ @Configuration @ConditionalOnClass(MongoClient.class) public class MongoDbRelationshipDetectorAutoConfiguration { @Autowired(required = false) private List<MongoClient> clients; @Bean public MongoDbRelationshipDetector mongoDBRelationshipDetector() { return new MongoDbRelationshipDetector(clients); } }
/* * Copyright © 2017 the original authors (http://cereebro.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.cereebro.spring.boot.autoconfigure.mongo; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.mongodb.MongoClient; /** * MongoDB detector auto configuration, depending on MongoDb classes being * available on the classpath. Requires a separate configuration class to * prevent issues with optional classes. * * @author lwarrot */ @Configuration @ConditionalOnClass(MongoClient.class) public class MongoDbRelationshipDetectorAutoConfiguration { @Autowired private List<MongoClient> clients; @Bean public MongoDbRelationshipDetector mongoDBRelationshipDetector() { return new MongoDbRelationshipDetector(clients); } }
Extend ServletModule instead of HttpPluginModule As described in I3b89150d1. Change-Id: Ic91ce95719c6bccc73cc29a2139a2274f20d1939
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.deleteproject; import com.google.gerrit.extensions.registration.DynamicSet; import com.google.gerrit.extensions.webui.JavaScriptPlugin; import com.google.gerrit.extensions.webui.WebUiPlugin; import com.google.inject.Inject; import com.google.inject.servlet.ServletModule; public class HttpModule extends ServletModule { private final Configuration cfg; @Inject HttpModule(Configuration cfg) { this.cfg = cfg; } @Override protected void configureServlets() { if (cfg.enablePreserveOption()) { DynamicSet.bind(binder(), WebUiPlugin.class) .toInstance(new JavaScriptPlugin("delete-project.js")); } else { DynamicSet.bind(binder(), WebUiPlugin.class) .toInstance(new JavaScriptPlugin("delete-project-with-preserve-disabled.js")); } } }
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.deleteproject; import com.google.gerrit.extensions.registration.DynamicSet; import com.google.gerrit.extensions.webui.JavaScriptPlugin; import com.google.gerrit.extensions.webui.WebUiPlugin; import com.google.gerrit.httpd.plugins.HttpPluginModule; import com.google.inject.Inject; public class HttpModule extends HttpPluginModule { private final Configuration cfg; @Inject HttpModule(Configuration cfg) { this.cfg = cfg; } @Override protected void configureServlets() { if (cfg.enablePreserveOption()) { DynamicSet.bind(binder(), WebUiPlugin.class) .toInstance(new JavaScriptPlugin("delete-project.js")); } else { DynamicSet.bind(binder(), WebUiPlugin.class) .toInstance(new JavaScriptPlugin("delete-project-with-preserve-disabled.js")); } } }
Add alt attribute to etalab logo
import React from 'react' import PropTypes from 'prop-types' import { translate } from 'react-i18next' import Container from '../../container' import Social from './social' import Sitemap from './sitemap' const Footer = ({ t }) => ( <footer> <Container> <div className='content'> <div> <img src='/static/images/etalab.png' alt='Etalab' /> <Social /> </div> <Sitemap /> </div> </Container> <style jsx>{` @import 'colors'; footer { background: $darkblue; color: $white; padding: 2em 0; line-height: 2em; } .content { display: flex; flex-direction: row; justify-content: space-between; align-items: center; @media (max-width: 551px) { flex-direction: column; align-items: flex-start; } } `}</style> </footer> ) Footer.propTypes = { t: PropTypes.func.isRequired } export default translate()(Footer)
import React from 'react' import PropTypes from 'prop-types' import { translate } from 'react-i18next' import Container from '../../container' import Social from './social' import Sitemap from './sitemap' const Footer = ({ t }) => ( <footer> <Container> <div className='content'> <div> <img src='/static/images/etalab.png' /> <Social /> </div> <Sitemap /> </div> </Container> <style jsx>{` @import 'colors'; footer { background: $darkblue; color: $white; padding: 2em 0; line-height: 2em; } .content { display: flex; flex-direction: row; justify-content: space-between; align-items: center; @media (max-width: 551px) { flex-direction: column; align-items: flex-start; } } `}</style> </footer> ) Footer.propTypes = { t: PropTypes.func.isRequired } export default translate()(Footer)
Core: Remove bytes from migration 0028
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from decimal import Decimal import shoop.core.models import enumfields.fields class Migration(migrations.Migration): dependencies = [ ('shoop', '0027_contact_group_behavior'), ] operations = [ migrations.CreateModel( name='RoundingBehaviorComponent', fields=[ ('servicebehaviorcomponent_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='shoop.ServiceBehaviorComponent')), ('quant', models.DecimalField(default=Decimal('0.05'), verbose_name='rounding quant', max_digits=36, decimal_places=9)), ('mode', enumfields.fields.EnumField(default='ROUND_HALF_UP', max_length=10, verbose_name='rounding mode', enum=shoop.core.models.RoundingMode)), ], options={ 'abstract': False, }, bases=('shoop.servicebehaviorcomponent',), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from decimal import Decimal import shoop.core.models import enumfields.fields class Migration(migrations.Migration): dependencies = [ ('shoop', '0027_contact_group_behavior'), ] operations = [ migrations.CreateModel( name='RoundingBehaviorComponent', fields=[ ('servicebehaviorcomponent_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='shoop.ServiceBehaviorComponent')), ('quant', models.DecimalField(default=Decimal('0.05'), verbose_name='rounding quant', max_digits=36, decimal_places=9)), ('mode', enumfields.fields.EnumField(default=b'ROUND_HALF_UP', max_length=10, verbose_name='rounding mode', enum=shoop.core.models.RoundingMode)), ], options={ 'abstract': False, }, bases=('shoop.servicebehaviorcomponent',), ), ]
Return true instead of $bar.
<?php if (!defined('MEDIAWIKI')) die(); /** * Class file for the GoogleAdSense extension * * @addtogroup Extensions * @author Siebrand Mazeland * @license MIT */ class GoogleAdSense { static function GoogleAdSenseInSidebar( $skin, &$bar ) { global $wgGoogleAdSenseWidth, $wgGoogleAdSenseID, $wgGoogleAdSenseHeight, $wgGoogleAdSenseClient, $wgGoogleAdSenseSlot, $wgGoogleAdSenseSrc; // Return $bar unchanged if not all values have been set. // FIXME: signal incorrect configuration nicely? if( $wgGoogleAdSenseClient == 'none' || $wgGoogleAdSenseSlot == 'none' || $wgGoogleAdSenseID == 'none' ) return $bar; wfLoadExtensionMessages( 'GoogleAdSense' ); $bar['googleadsense'] = "<script type=\"text/javascript\"><!-- google_ad_client = \"$wgGoogleAdSenseClient\"; /* $wgGoogleAdSenseID */ google_ad_slot = \"$wgGoogleAdSenseSlot\"; google_ad_width = $wgGoogleAdSenseWidth; google_ad_height = $wgGoogleAdSenseHeight; //--> </script> <script type=\"text/javascript\" src=\"$wgGoogleAdSenseSrc\"> </script>"; return true; } }
<?php if (!defined('MEDIAWIKI')) die(); /** * Class file for the GoogleAdSense extension * * @addtogroup Extensions * @author Siebrand Mazeland * @license MIT */ class GoogleAdSense { static function GoogleAdSenseInSidebar( $skin, &$bar ) { global $wgGoogleAdSenseWidth, $wgGoogleAdSenseID, $wgGoogleAdSenseHeight, $wgGoogleAdSenseClient, $wgGoogleAdSenseSlot, $wgGoogleAdSenseSrc; // Return $bar unchanged if not all values have been set. // FIXME: signal incorrect configuration nicely? if( $wgGoogleAdSenseClient == 'none' || $wgGoogleAdSenseSlot == 'none' || $wgGoogleAdSenseID == 'none' ) return $bar; wfLoadExtensionMessages( 'GoogleAdSense' ); $bar['googleadsense'] = "<script type=\"text/javascript\"><!-- google_ad_client = \"$wgGoogleAdSenseClient\"; /* $wgGoogleAdSenseID */ google_ad_slot = \"$wgGoogleAdSenseSlot\"; google_ad_width = $wgGoogleAdSenseWidth; google_ad_height = $wgGoogleAdSenseHeight; //--> </script> <script type=\"text/javascript\" src=\"$wgGoogleAdSenseSrc\"> </script>"; return $bar; } }
Switch to GitHub Pages as Host
window.onload = initialize; var DATAFILE = "research.json"; var DONE_READYSTATE = 4; var DONE_STATUS = 200; var OFFICIAL_URL = "https://kbuffardi.github.io/ScholarWebsite/"; var OFFICIAL_HOST = "kbuffardi.github.io" var references = {}; function initialize() { validateHost(); //loadExternalData(); } function validateHost() { if( window.location.hostname != OFFICIAL_HOST ) { window.location.href = OFFICIAL_URL; } } function loadExternalData() { var json = new XMLHttpRequest(); json.overrideMimeType("application/json"); //event listener: when json file load is "done" json.onreadystatechange = function() { if (this.readyState == DONE_READYSTATE && this.status == DONE_STATUS) { references=JSON.parse(this.responseText); console.log(references); } } json.open("GET", DATAFILE); json.send(); }
window.onload = initialize; var DATAFILE = "research.json"; var DONE_READYSTATE = 4; var DONE_STATUS = 200; var OFFICIAL_URL = "http://www.ecst.csuchico.edu/~kbuffardi/"; var OFFICIAL_HOST = "www.ecst.csuchico.edu" var references = {}; function initialize() { validateHost(); //loadExternalData(); } function validateHost() { if( window.location.hostname != OFFICIAL_HOST ) { window.location.href = OFFICIAL_URL; } } function loadExternalData() { var json = new XMLHttpRequest(); json.overrideMimeType("application/json"); //event listener: when json file load is "done" json.onreadystatechange = function() { if (this.readyState == DONE_READYSTATE && this.status == DONE_STATUS) { references=JSON.parse(this.responseText); console.log(references); } } json.open("GET", DATAFILE); json.send(); }
Allow falsy values to be passed as defaults
module.exports = { safe: function (thing, path, otherwise) { thing = (typeof thing === 'object' && thing != null) ? thing : {}; var props = path.split('.'); if (props.length === 1) { return typeof thing[props[0]] === 'undefined' ? otherwise : thing[props.shift()]; } else { var prop = props.shift(); return (typeof thing[prop] === 'object' && thing != null) ? this.safe(thing[prop], props.join('.'), otherwise) : otherwise; } }, expand: function (obj, path, thing) { obj = (typeof obj === 'object' && obj != null) ? obj : {}; var props = path.split('.'); if (props.length === 1) { obj[props.shift()] = thing; } else { var prop = props.shift(); if (!obj[prop]) { obj[prop] = {}; } this.expand(obj[prop], props.join('.'), thing); } } };
module.exports = { safe: function (thing, path, otherwise) { thing = (typeof thing === 'object' && thing != null) ? thing : {}; var props = path.split('.'); if (props.length === 1) { return typeof thing[props[0]] === 'undefined' ? otherwise : thing[props.shift()]; } else { var prop = props.shift(); return (typeof thing[prop] === 'object' && thing != null) ? this.safe(thing[prop], props.join('.'), otherwise) : otherwise || undefined; } }, expand: function (obj, path, thing) { obj = (typeof obj === 'object' && obj != null) ? obj : {}; var props = path.split('.'); if (props.length === 1) { obj[props.shift()] = thing; } else { var prop = props.shift(); if (!obj[prop]) { obj[prop] = {}; } this.expand(obj[prop], props.join('.'), thing); } } };
Use more general bower syntax to import antiscroll
module.exports = { normalizeEntityName: function() {}, afterInstall: function(options) { // We assume that handlebars, ember, and jquery already exist // FIXME(azirbel): Do we need to install lodash too? return this.addBowerPackagesToProject([ { 'name': 'git://github.com/azirbel/antiscroll.git#90391fb371c7be769bc32e7287c5271981428356' }, { 'name': 'jquery-mousewheel', 'target': '~3.1.4' }, { 'name': 'jquery-ui', // FIXME(azirbel): Can we use a newer version? 'target': '1.10.1' } ]); } };
module.exports = { normalizeEntityName: function() {}, afterInstall: function(options) { // We assume that handlebars, ember, and jquery already exist // FIXME(azirbel): Do we need to install lodash too? return this.addBowerPackagesToProject([ { 'name': 'git@github.com:azirbel/antiscroll.git#90391fb371c7be769bc32e7287c5271981428356' }, { 'name': 'jquery-mousewheel', 'target': '~3.1.4' }, { 'name': 'jquery-ui', // FIXME(azirbel): Can we use a newer version? 'target': '1.10.1' } ]); } };
Fix checkList problem in seq test class
package com.jmonad.seq; import com.jmonad.seq.lambda.Function; import org.junit.Test; public class SeqSomeTest { private Integer[] numbers = {100, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; private Function trueFunc = new Function<Boolean, Integer>() { @Override public Boolean call(Integer param) { return param > 10; } }; private Function falseFunc = new Function<Boolean, Integer>() { @Override public Boolean call(Integer param) { return param > 100; } }; @Test public void expectTrueFromSomeFunctionTest() { assert new Seq<>(numbers).some(trueFunc); } @Test public void expectFalseFromSomeFunctionTest() { assert !new Seq<>(numbers).some(falseFunc); } }
package com.jmonad.seq; import com.jmonad.seq.lambda.Function; import org.junit.Test; public class SeqSomeTest { private Integer[] numbers = {100, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; private Function trueFunc = new Function<Boolean, Integer>() { @Override public Boolean call(Integer param) { return param > 10; } }; private Function falseFunc = new Function<Boolean, Integer>() { @Override public Boolean call(Integer param) { return param > 100; } }; @Test public void expectTrueFromSomeFunctionTest() { assert new Seq<>(numbers).some(trueFunc); } @Test public void expectFalseFromSomeFunctionTest() { assert !new Seq<>(numbers).some(falseFunc); } }
Add correct reset-sent and reset-done redirect views, tidy regex
from django.conf.urls import patterns, url from .views import RegistrationView, PasswordChangeView, password_reset_sent, password_reset_done urlpatterns = patterns('', url('^new/$', RegistrationView.as_view(), name='register'), url('^password/reset/$', 'django.contrib.auth.views.password_reset', { 'template_name': 'accounts/reset_form.html', 'email_template_name': 'accounts/reset_email.txt', 'subject_template_name': 'accounts/reset_subject.txt', 'current_app': 'cellcounter.accounts', 'post_reset_redirect': 'password-reset-sent', }, name='password-reset'), url('^password/reset/sent/$', password_reset_sent, name='password-reset-sent'), url('^password/reset/done/$', password_reset_done, name='password-reset-done'), url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[\d\w\-]+)/$', 'django.contrib.auth.views.password_reset_confirm', { 'template_name': 'accounts/reset_confirm.html', 'post_reset_redirect': 'password-reset-done', }, name='password-reset-confirm'), url('^password/change/$', PasswordChangeView.as_view(), name='change-password'), )
from django.conf.urls import patterns, url from django.core.urlresolvers import reverse from .views import RegistrationView, PasswordChangeView, password_reset_done urlpatterns = patterns('', url('^new/$', RegistrationView.as_view(), name='register'), url('^password/reset/$', 'django.contrib.auth.views.password_reset', { 'template_name': 'accounts/reset_form.html', 'email_template_name': 'accounts/reset_email.txt', 'subject_template_name': 'accounts/reset_subject.txt', 'current_app': 'cellcounter.accounts', 'post_reset_redirect': '/', }, name='reset-request'), url('^password/reset/confirm/(?P<uidb64>\d+)/(?P<token>[\d\w-]+)/$', 'django.contrib.auth.views.password_reset_confirm', { 'template_name': 'accounts/reset_confirm.html', 'post_reset_redirect': password_reset_done, }, name='password-reset-confirm'), url('^password/change/$', PasswordChangeView.as_view(), name='change-password'), )
Use var to satisfy tests for prehistoric nodejs versions
'use strict' // FIXME leaving var to satisfy tests for node v0.10 and v0.12 var packageJson = require('../package') var channelHeader = `Node.js-${process.version}-SDK-v${packageJson.version}` module.exports = { reqWithBody: { reqheaders: { 'X-App-Id': 'node-sdk-test-id', 'X-App-Token': 'node-sdk-test-secret', 'X-Voucherify-Channel': channelHeader, 'accept': 'application/json', 'content-type': 'application/json' } }, reqWithoutBody: { reqheaders: { 'X-App-Id': 'node-sdk-test-id', 'X-App-Token': 'node-sdk-test-secret', 'X-Voucherify-Channel': channelHeader, 'accept': 'application/json' } } }
'use strict' const packageJson = require('../package') const channelHeader = `Node.js-${process.version}-SDK-v${packageJson.version}` module.exports = { reqWithBody: { reqheaders: { 'X-App-Id': 'node-sdk-test-id', 'X-App-Token': 'node-sdk-test-secret', 'X-Voucherify-Channel': channelHeader, 'accept': 'application/json', 'content-type': 'application/json' } }, reqWithoutBody: { reqheaders: { 'X-App-Id': 'node-sdk-test-id', 'X-App-Token': 'node-sdk-test-secret', 'X-Voucherify-Channel': channelHeader, 'accept': 'application/json' } } }
Revert "install_requires is a list now, not iterator" This reverts commit d36bcafb69a67d623c9e28f7dad5113783246419.
from distutils.core import setup with open('README.md') as description: long_description = description.read() setup( name='rmr_django', version='0.0.1', author='Rinat Khabibiev', author_email='rh@redmadrobot.com', packages=[ 'rmr', 'rmr/django', 'rmr/django/middleware', 'rmr/django/middleware/request', 'rmr/models', 'rmr/models/fields', 'rmr/views', ], url='https://github.com/RedMadRobot/rmr_django', license='MIT', description='rmr_django', long_description=long_description, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.4', ], install_requires=iter(open('requirements.txt', 'r').readline, ''), )
from distutils.core import setup with open('README.md') as description: long_description = description.read() setup( name='rmr_django', version='0.0.1', author='Rinat Khabibiev', author_email='rh@redmadrobot.com', packages=[ 'rmr', 'rmr/django', 'rmr/django/middleware', 'rmr/django/middleware/request', 'rmr/models', 'rmr/models/fields', 'rmr/views', ], url='https://github.com/RedMadRobot/rmr_django', license='MIT', description='rmr_django', long_description=long_description, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.4', ], install_requires=list(iter(open('requirements.txt', 'r').readline, '')), )
Change method param name & todo
package com.xamoom.android.xamoomsdk.Storage.Database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.xamoom.android.xamoomsdk.Storage.TableContracts.OfflineEnduserContract; public class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, OfflineEnduserContract.DATABASE_NAME, null, OfflineEnduserContract.DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(OfflineEnduserContract.SystemEntry.CREATE_TABLE); sqLiteDatabase.execSQL(OfflineEnduserContract.StyleEntry.CREATE_TABLE); sqLiteDatabase.execSQL(OfflineEnduserContract.SettingEntry.CREATE_TABLE); sqLiteDatabase.execSQL(OfflineEnduserContract.ContentEntry.CREATE_TABLE); sqLiteDatabase.execSQL(OfflineEnduserContract.ContentBlockEntry.CREATE_TABLE); sqLiteDatabase.execSQL(OfflineEnduserContract.MenuEntry.CREATE_TABLE); sqLiteDatabase.execSQL(OfflineEnduserContract.MarkerEntry.CREATE_TABLE); sqLiteDatabase.execSQL(OfflineEnduserContract.SpotEntry.CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVesion) { // TODO: implement upgrading when needed } }
package com.xamoom.android.xamoomsdk.Storage.Database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.xamoom.android.xamoomsdk.Storage.TableContracts.OfflineEnduserContract; public class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, OfflineEnduserContract.DATABASE_NAME, null, OfflineEnduserContract.DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(OfflineEnduserContract.SystemEntry.CREATE_TABLE); sqLiteDatabase.execSQL(OfflineEnduserContract.StyleEntry.CREATE_TABLE); sqLiteDatabase.execSQL(OfflineEnduserContract.SettingEntry.CREATE_TABLE); sqLiteDatabase.execSQL(OfflineEnduserContract.ContentEntry.CREATE_TABLE); sqLiteDatabase.execSQL(OfflineEnduserContract.ContentBlockEntry.CREATE_TABLE); sqLiteDatabase.execSQL(OfflineEnduserContract.MenuEntry.CREATE_TABLE); sqLiteDatabase.execSQL(OfflineEnduserContract.MarkerEntry.CREATE_TABLE); sqLiteDatabase.execSQL(OfflineEnduserContract.SpotEntry.CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { // TODO: implement upgrading } }
Add done() and modify query
//----------------------------------------------------------------------------// var express = require('express'); var router = express.Router(); var pg = require('pg'); var connectionString = require('../modules/db-config.module'); //----------------------------------------------------------------------------// // Gets a user's profile info and FAQ entries router.get('/:id', function(req, res) { var userId = parseInt(req.params.id); pg.connect(connectionString, function(error, client, done) { connectionErrorCheck(error); client.query( 'SELECT * FROM mentors ' + 'FULL OUTER JOIN faq ON mentors.id = faq.mentor_id ' + 'WHERE mentors.id = $1', [userId], function(error, result) { done(); if(error) { console.log('Error when searching mentors and FAQ tables: ', error); res.sendStatus(500); } else { res.send(result.rows); } } ); }); }); module.exports = router; // Checks for errors connecting to the database function connectionErrorCheck(error) { if (error) { console.log('Database connection error: ', error); res.sendStatus(500); } }
//----------------------------------------------------------------------------// var express = require('express'); var router = express.Router(); var pg = require('pg'); var connectionString = require('../modules/db-config.module'); //----------------------------------------------------------------------------// // Gets a user's profile info and FAQ entries router.get('/:id', function(req, res) { var userId = parseInt(req.params.id); pg.connect(connectionString, function(error, client, done) { connectionErrorCheck(error); client.query( 'SELECT * FROM mentors ' + 'JOIN faq ON mentors.id = faq.mentor_id ' + 'WHERE mentors.id = $1', [userId], function(error, result) { if(error) { console.log('Error when searching mentors and FAQ tables: ', error); res.sendStatus(500); } else { res.send(result.rows); } } ); }); }); module.exports = router; // Checks for errors connecting to the database function connectionErrorCheck(error) { if (error) { console.log('Database connection error: ', error); res.sendStatus(500); } }
Update failing Fetcher get() test
const assert = require('assert') const Fetcher = require('../../src/models/Fetcher') const fetchMock = require('fetch-mock') describe('Fetcher', () => { describe('get', () => { before(() => { fetchMock.get('http://example.com', { foo: 'bar' }) }) it('returns a promise that resolves with the JSON response', done => { const fetcher = new Fetcher() fetcher.get('http://example.com').then(({ json }) => { assert.deepEqual({ foo: 'bar' }, json) fetchMock.restore() done() }) }) }) describe('getStatus', () => { it('includes status and statusText properties', () => { const fakeResponse = { status: '404', statusText: 'Not Found', } const expected = '404 Not Found' const fetcher = new Fetcher() assert.equal(expected, fetcher.getStatus(fakeResponse)) }) }) })
const assert = require('assert') const Fetcher = require('../../src/models/Fetcher') const fetchMock = require('fetch-mock') describe('Fetcher', () => { describe('get', () => { before(() => { fetchMock.get('http://example.com', { foo: 'bar' }) }) it('returns a promise that resolves with the JSON response', done => { const fetcher = new Fetcher() fetcher.get('http://example.com').then(json => { assert.deepEqual({ foo: 'bar' }, json) fetchMock.restore() done() }) }) }) describe('getStatus', () => { it('includes status and statusText properties', () => { const fakeResponse = { status: '404', statusText: 'Not Found', } const expected = '404 Not Found' const fetcher = new Fetcher() assert.equal(expected, fetcher.getStatus(fakeResponse)) }) }) })
Correct UCI parsing in board state evaluation function
import subprocess import re ENGINE_BIN = "stockfish" DEPTH = 20 def evaluate_position(board, depth=DEPTH): """Evaluates the board's current position. Returns the Stockfish scalar score, at the given depth, in centipawns. """ engine = subprocess.Popen(ENGINE_BIN, bufsize=0, universal_newlines=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) # take care of initial (credits) line engine.stdout.readline() # search from current position to given depth engine.stdin.write("position fen "+board.fen()+"\n") engine.stdin.write("go depth "+str(DEPTH)+"\n") while True: line = engine.stdout.readline().strip() if line.startswith("info") and (" depth "+str(DEPTH)) in line \ and "score cp" in line and "bound" not in line: break engine.stdin.write("quit\n") # score in centipawns matcher = re.match(".*score cp ([0-9]+).*", line) score = int(matcher.group(1)) return score
import subprocess ENGINE_BIN = "stockfish" DEPTH = 20 def evaluate_position(board, depth=DEPTH): """Evaluates the board's current position. Returns the Stockfish scalar score, at the given depth, in centipawns. """ engine = subprocess.Popen(ENGINE_BIN, bufsize=0, universal_newlines=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) # take care of initial (credits) line engine.stdout.readline() # search from current position to given depth engine.stdin.write("position fen "+board.fen()+"\n") engine.stdin.write("go depth "+str(DEPTH)+"\n") last_line = "" while True: line = engine.stdout.readline().strip() if "bestmove" in line: break else: last_line = line engine.stdin.write("quit\n") # score in centipawns score = last_line.split()[9] return score
Disable auto-reloader in debug mode This was causing issues with plugin initialisation happening twice and was getting rate limited by Telegram Bot API.
import argparse from alerta.app import app from alerta.app import db from alerta.version import __version__ LOG = app.logger def main(): parser = argparse.ArgumentParser( prog='alertad', description='Alerta server (for development purposes only)', formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( '-H', '--host', type=str, default='0.0.0.0', help='Bind host' ) parser.add_argument( '-P', '--port', type=int, default=8080, help='Listen port' ) parser.add_argument( '--debug', action='store_true', default=False, help='Debug output' ) args = parser.parse_args() LOG.info('Starting alerta version %s ...', __version__) app.run(host=args.host, port=args.port, debug=args.debug, threaded=True, use_reloader=False)
import argparse from alerta.app import app from alerta.app import db from alerta.version import __version__ LOG = app.logger def main(): parser = argparse.ArgumentParser( prog='alertad', description='Alerta server (for development purposes only)', formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( '-H', '--host', type=str, default='0.0.0.0', help='Bind host' ) parser.add_argument( '-P', '--port', type=int, default=8080, help='Listen port' ) parser.add_argument( '--debug', action='store_true', default=False, help='Debug output' ) args = parser.parse_args() LOG.info('Starting alerta version %s ...', __version__) app.run(host=args.host, port=args.port, debug=args.debug, threaded=True)
Join existing game using a game code is now working. Next...fix socket issues.
package handlers; import org.atmosphere.config.service.AtmosphereHandlerService; import org.atmosphere.cpr.*; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import java.io.IOException; /** * Created by rostifar on 6/14/16. */ @AtmosphereHandlerService public class ScrabbleGameHandler implements AtmosphereHandler { //action when connection is made to the backend @Override public void onRequest(AtmosphereResource atmosphereResource) throws IOException { AtmosphereRequest request = atmosphereResource.getRequest(); AtmosphereResponse response = atmosphereResource.getResponse(); System.out.println("Called:" + this.getClass().getName()); // request.get RequestDispatcher reqDispatcher = request.getRequestDispatcher("/Index.html"); try { reqDispatcher.forward(request, response); } catch (ServletException e) { e.printStackTrace(); } } //called when Broadcaster broadcasts an event @Override public void onStateChange(AtmosphereResourceEvent atmosphereResourceEvent) throws IOException { } @Override public void destroy() { } }
package handlers; import org.atmosphere.config.service.AtmosphereHandlerService; import org.atmosphere.cpr.AtmosphereHandler; import org.atmosphere.cpr.AtmosphereRequest; import org.atmosphere.cpr.AtmosphereResource; import org.atmosphere.cpr.AtmosphereResourceEvent; import java.io.IOException; /** * Created by rostifar on 6/14/16. */ @AtmosphereHandlerService public class ScrabbleGameHandler implements AtmosphereHandler { //action when connection is made to the backend @Override public void onRequest(AtmosphereResource atmosphereResource) throws IOException { AtmosphereRequest request = atmosphereResource.getRequest(); System.out.println("hi"); } //called when Broadcaster broadcasts an event @Override public void onStateChange(AtmosphereResourceEvent atmosphereResourceEvent) throws IOException { } @Override public void destroy() { } }
Add test for start/end values
import datetime as dt from .context import tohu from tohu.v6.primitive_generators import Date def test_single_date(): g = Date(start="2018-01-01", end="2018-01-01") dates = g.generate(100, seed=12345) assert all([x == dt.date(2018, 1, 1) for x in dates]) def test_date_range(): g = Date(start="1999-11-28", end="1999-12-01") dates = g.generate(1000, seed=12345) dates_expected = [ dt.date(1999, 11, 28), dt.date(1999, 11, 29), dt.date(1999, 11, 30), dt.date(1999, 12, 1), ] assert set(dates_expected) == set(dates) def test_start_and_end(): g = Date(start="1999-11-28", end="1999-12-01") assert g.start == dt.date(1999, 11, 28) assert g.end == dt.date(1999, 12, 1)
import datetime as dt from .context import tohu from tohu.v6.primitive_generators import Date def test_single_date(): g = Date(start="2018-01-01", end="2018-01-01") dates = g.generate(100, seed=12345) assert all([x == dt.date(2018, 1, 1) for x in dates]) def test_date_range(): g = Date(start="1999-11-28", end="1999-12-01") dates = g.generate(1000, seed=12345) dates_expected = [ dt.date(1999, 11, 28), dt.date(1999, 11, 29), dt.date(1999, 11, 30), dt.date(1999, 12, 1), ] assert set(dates_expected) == set(dates)
Declare subclass of `UploadType` to be `str` * Fixes issues with JSON serializing * Revert `__repr__` string format changes as the newlines created large gaps of whitespace
import enum from sqlalchemy import Column, String, Boolean, Integer, DateTime, Enum from virtool.postgres import Base class UploadType(str, enum.Enum): hmm = "hmm" reference = "reference" reads = "reads" subtraction = "subtraction" null = None class Upload(Base): __tablename__ = "uploads" id = Column(Integer, primary_key=True) created_at = Column(DateTime) name = Column(String) name_on_disk = Column(String, unique=True) ready = Column(Boolean) removed = Column(Boolean) reserved = Column(Boolean) size = Column(Integer) type = Column(Enum(UploadType)) user = Column(String) uploaded_at = Column(DateTime) def __repr__(self): return f"<Upload(id={self.id}, created_at={self.created_at}, name={self.name}, " \ f"name_on_disk={self.name_on_disk}, ready={self.ready}, removed={self.removed}, " \ f"reserved={self.reserved}, " f"size={self.size}, type={self.type}, user={self.user}, " \ f"uploaded_at={self.uploaded_at}>"
import enum from sqlalchemy import Column, String, Boolean, Integer, DateTime, Enum from virtool.postgres import Base class UploadType(enum.Enum): hmm = "hmm" reference = "reference" reads = "reads" subtraction = "subtraction" null = None class Upload(Base): __tablename__ = "uploads" id = Column(Integer, primary_key=True) created_at = Column(DateTime) name = Column(String) name_on_disk = Column(String, unique=True) ready = Column(Boolean) removed = Column(Boolean) reserved = Column(Boolean) size = Column(Integer) type = Column(Enum(UploadType)) user = Column(String) uploaded_at = Column(DateTime) def __repr__(self): return """<Upload(id= {self.id}, created_at={self.created_at}, name={self.name}, \ name_on_disk={self.name_on_disk}, ready={self.ready}, removed={self.removed}, reserved={self.reserved}, \ size={self.size}, type={self.type}, user={self.user}, uploaded_at={self.uploaded_at}>"""
Switch internal templater to handlebars
module.exports = { options : { latedef : true, noempty : true, undef : true, strict : false, node : true, browser : true, eqnull : true, scripturl : true, predef : [ "$", "jQuery", "Classify", "Avalon", "Page", "Highcharts", "Recaptcha", "alert", "confirm", "SWFUpload", "Handlebars" ] }, format : "JS Lint {{type}}: [{{file}}:{{line}}] {{message}}", skippedFiles : [ ".build/csslint/csslint-node.js", ".build/jshint/jshint.js", "public/static/javascript/lib/classify.min.js", "public/static/javascript/lib/utils.min.js" ], skippedDirectories : [ ".build/uglify", "public/static/javascript/vendor", "tmp" ] };
module.exports = { options : { latedef : true, noempty : true, undef : true, strict : false, node : true, browser : true, eqnull : true, scripturl : true, predef : [ "$", "jQuery", "Classify", "Avalon", "Page", "Highcharts", "Recaptcha", "alert", "confirm", "SWFUpload" ] }, format : "JS Lint {{type}}: [{{file}}:{{line}}] {{message}}", skippedFiles : [ ".build/csslint/csslint-node.js", ".build/jshint/jshint.js", "public/static/javascript/lib/classify.min.js", "public/static/javascript/lib/utils.min.js" ], skippedDirectories : [ ".build/uglify", "public/static/javascript/vendor", "tmp" ] };
Update build script to use package.json from the project root.
/* * Copyright 2011 Twitter, Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var Hogan = require(__dirname + '/../lib/hogan.js'); var fs = require('fs'); var path = require('path'); // Substitute variables in the homepage with values from package.json var homeTemplatePath = __dirname + '/../build/gh-pages/index.html.mustache'; var contextPath = __dirname + '/../package.json'; var homepage = fs.readFileSync(homeTemplatePath).toString(); var context = JSON.parse(fs.readFileSync(contextPath).toString()); var template = Hogan.compile(homepage); fs.writeFileSync(path.dirname(homeTemplatePath) + '/index.html', template.render(context)); fs.unlinkSync(homeTemplatePath);
/* * Copyright 2011 Twitter, Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var Hogan = require(__dirname + '/../lib/hogan.js'); var fs = require('fs'); var path = require('path'); // Substitute variables in the homepage with values from package.json var homeTemplatePath = __dirname + '/../build/gh-pages/index.html.mustache'; var contextPath = __dirname + '/../dist/nodejs/package.json'; var homepage = fs.readFileSync(homeTemplatePath).toString(); var context = JSON.parse(fs.readFileSync(contextPath).toString()); var template = Hogan.compile(homepage); fs.writeFileSync(path.dirname(homeTemplatePath) + '/index.html', template.render(context)); fs.unlinkSync(homeTemplatePath);
Update home page redirecting (ordered by header menu list)
<?php /*********************************************************************** Elf Web App Copyright (C) 2013-2015 Kazuichi Takashiro This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. takashiro@qq.com ************************************************************************/ if(!defined('IN_ADMINCP')) exit('access denied'); class HomeModule extends AdminControlPanelModule{ public function getAlias(){ return 'public'; } public function defaultAction(){ global $_G, $cpmenu_list; foreach($cpmenu_list as $module){ if(!empty($module['admin_modules']) && $_G['admin']->hasPermission($module['name'])){ redirect('admin.php?mod='.$module['name']); } } redirect('admin.php?mod=cp'); } } ?>
<?php /*********************************************************************** Elf Web App Copyright (C) 2013-2015 Kazuichi Takashiro This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. takashiro@qq.com ************************************************************************/ if(!defined('IN_ADMINCP')) exit('access denied'); class HomeModule extends AdminControlPanelModule{ public function getAlias(){ return 'public'; } public function defaultAction(){ global $_G; foreach(Administrator::$Permissions as $perm => $v){ if($perm == 'home' || $perm == 'cp') continue; if($_G['admin']->hasPermission($perm)){ redirect('admin.php?mod='.$perm); } } redirect('admin.php?mod=cp'); } } ?>
Fix segfault caused by using incorrect clear method
var Graphite = require('graphite'); var Measured = require('measured'); var reportInterval = 5000; var graphiteHost = process.env.GRAPHITE_HOST || null; var graphitePort = process.env.GRAPHITE_PORT || 2003; var envName = process.env.NODE_ENV || "unknown"; var processIdentifier = 'pid-' + process.pid; var timer = null; var graphite = null; var data = Measured.createCollection('origami.polyfill.' + envName + '.' + processIdentifier); if (graphiteHost) { graphite = Graphite.createClient('plaintext://'+graphiteHost+':'+graphitePort); timer = setInterval(function() { graphite.write(data.toJSON(), function(err) { if (err) { // Ignore timeouts if (err.code === 'ETIMEDOUT') return; console.error(err, err.stack); console.warn('Disabling graphite reporting due to error'); clearInterval(timer); } }); }, reportInterval); timer.unref(); } module.exports = data;
var Graphite = require('graphite'); var Measured = require('measured'); var reportInterval = 5000; var graphiteHost = process.env.GRAPHITE_HOST || null; var graphitePort = process.env.GRAPHITE_PORT || 2003; var envName = process.env.NODE_ENV || "unknown"; var processIdentifier = 'pid-' + process.pid; var timer = null; var graphite = null; var data = Measured.createCollection('origami.polyfill.' + envName + '.' + processIdentifier); if (graphiteHost) { graphite = Graphite.createClient('plaintext://'+graphiteHost+':'+graphitePort); timer = setInterval(function() { graphite.write(data.toJSON(), function(err) { if (err) { // Ignore timeouts if (err.code === 'ETIMEDOUT') return; console.error(err, err.stack); console.warn('Disabling graphite reporting due to error'); clearTimeout(timer); } }); }, reportInterval); timer.unref(); } module.exports = data;
Set name as mandatory element for form creation
<?php namespace GoalioForgotPassword\Form; use Laminas\Form\Element; use Laminas\Form\Form; use GoalioForgotPassword\Options\ForgotOptionsInterface; class Forgot extends Form { /** * @var AuthenticationOptionsInterface */ protected $forgotOptions; public function __construct($name, ForgotOptionsInterface $options) { $this->setForgotOptions($options); parent::__construct($name); $this->add(array( 'name' => 'email', 'options' => array( 'label' => 'Email', ), )); $submitElement = new Element\Button('submit'); $submitElement ->setLabel('Request new password') ->setAttributes(array( 'type' => 'submit', )); $this->add($submitElement, array( 'priority' => -100, )); } public function setForgotOptions(ForgotOptionsInterface $forgotOptions) { $this->forgotOptions = $forgotOptions; return $this; } public function getForgotOptions() { return $this->forgotOptions; } }
<?php namespace GoalioForgotPassword\Form; use Laminas\Form\Element; use Laminas\Form\Form; use GoalioForgotPassword\Options\ForgotOptionsInterface; class Forgot extends Form { /** * @var AuthenticationOptionsInterface */ protected $forgotOptions; public function __construct($name = null, ForgotOptionsInterface $options) { $this->setForgotOptions($options); parent::__construct($name); $this->add(array( 'name' => 'email', 'options' => array( 'label' => 'Email', ), )); $submitElement = new Element\Button('submit'); $submitElement ->setLabel('Request new password') ->setAttributes(array( 'type' => 'submit', )); $this->add($submitElement, array( 'priority' => -100, )); } public function setForgotOptions(ForgotOptionsInterface $forgotOptions) { $this->forgotOptions = $forgotOptions; return $this; } public function getForgotOptions() { return $this->forgotOptions; } }
Fix condition for fetching content
import { contentsRef, routesRef } from '@/admin/firebase_config/index' import contentFetch from '@/admin/mixins/contentFetch' import _ from 'lodash' export default { mixins: [contentFetch], firebase: { routes: routesRef, contents: contentsRef }, computed: { content () { const params = this.$route.params let path = this.$route.path if (params) { _.forIn(params, (value, key) => { path = path.replace(value, ':' + key) }) } let currentRoute = this.routes.filter((route) => { return route.path === path })[0] let contentType = currentRoute.contentType let contentId = currentRoute.content !== 'none' ? currentRoute.content : (_.has(params, 'id') ? params.id : 'none') return this.selectContentByTypeAndId(contentType, contentId) } } }
import { contentsRef, routesRef } from '@/admin/firebase_config/index' import contentFetch from '@/admin/mixins/contentFetch' import _ from 'lodash' export default { mixins: [contentFetch], firebase: { routes: routesRef, contents: contentsRef }, computed: { content () { const params = this.$route.params let path = this.$route.path if (params) { _.forIn(params, (value, key) => { path = path.replace(value, ':' + key) }) } let currentRoute = this.routes.filter((route) => { return route.path === path })[0] let contentType = currentRoute.contentType let contentId = currentRoute.content || (_.has(params, 'id') ? params.id : 'none') return this.selectContentByTypeAndId(contentType, contentId) } } }
Update job task 6.1 lesson 1
package ru.spoddubnyak; public class CheckString { public String sub; public String origin; public CheckString(String origin, String sub) { this.sub = sub; this.origin = origin; } public boolean checkLineEntyAnotherLine() { char[] subArray = this.sub.toCharArray(); char[] originArray = this.origin.toCharArray(); int count = 0; int i = 0; while ((i < originArray.length - subArray.length + 1) && (count != subArray.length)) { if ((originArray[i] == subArray[0]) && (subArray.length + i <= originArray.length)) { count = 1; for (int j = 1; j < subArray.length; j++) { if (originArray[i + j] != subArray[j]) { break; } count++; } } i++; } return (count == subArray.length) ? true : false; } }
package ru.spoddubnyak; public class CheckString { public String sub; public String origin; public CheckString(String origin, String sub) { this.sub = sub; this.origin = origin; } public boolean checkLineEntyAnotherLine() { char[] subArray = this.sub.toCharArray(); char[] originArray = this.origin.toCharArray(); int count = 0; for (int i = 0; i < originArray.length - subArray.length + 1; i++ ) { if ((originArray[i] == subArray[0]) && (subArray.length + i <= originArray.length)) { count = 1; for (int j = 1; j < subArray.length; j++) { if (originArray[i + j] != subArray[j]) { break; } count++; } if (count == subArray.length) { return true; } } } return false; } }
Document the FirstPassCache helper class
/** * Helper class to keep track of files that * have passed through the stream. */ export default class FirstPassCache { constructor() { this._passedFiles = []; this._firstPassHandled = false; } /** * Marks that the given file has passed through. * @param {string} filePath File that is passing through * @return {boolean} True if this is still the first pass, * false if ANY file (this or previous) has already * been passed through twice. */ pass(filePath) { if (this._firstPassHandled) { // Return false to indicate that this is the // first pass thru for this file. return false; } else if (this._passedFiles.indexOf(filePath) !== -1) { // Mark that the first pass is over and return true. this._firstPassHandled = true; this._passedFiles = null; return false; } else { // Mark that this file has passed once already. this._passedFiles.push(filePath); return true; } } };
export default class FirstPassCache { constructor() { this._passedFiles = []; this._firstPassHandled = false; } pass(filePath) { if (this._firstPassHandled) { // Return false to indicate that this is the // first pass thru for this file. return false; } else if (this._passedFiles.indexOf(filePath) !== -1) { // Mark that the first pass is over and return true. this._firstPassHandled = true; this._passedFiles = null; return false; } else { // Mark that this file has passed once already. this._passedFiles.push(filePath); return true; } } };
Update overlay positioning to fixed
(function() { function onPlayerReady() { var overlay = videoPlayer.overlay(); $(overlay).html('<img id="overlaylogo" src="http://cs1.brightcodes.net/ben/img/genericlogo.png" />') .css({ position:"fixed", height:"100%", width:"100%" }); $("#overlaylogo").css({ position:"absolute", bottom:"50px", right:"10px" }); } player = brightcove.api.getExperience(); videoPlayer = player.getModule(brightcove.api.modules.APIModules.VIDEO_PLAYER); experience = player.getModule(brightcove.api.modules.APIModules.EXPERIENCE); if (experience.getReady()) { onPlayerReady(); } else { experience.addEventListener(brightcove.player.events.ExperienceEvent.TEMPLATE_READY, onPlayerReady); } }());
(function() { function onPlayerReady() { var overlay = videoPlayer.overlay(); $(overlay).html('<img id="overlaylogo" src="http://cs1.brightcodes.net/ben/img/genericlogo.png" />') .css({ position:"relative" }); $("#overlaylogo").css({ position:"absolute", bottom:"50px", right:"10px" }); } player = brightcove.api.getExperience(); videoPlayer = player.getModule(brightcove.api.modules.APIModules.VIDEO_PLAYER); experience = player.getModule(brightcove.api.modules.APIModules.EXPERIENCE); if (experience.getReady()) { onPlayerReady(); } else { experience.addEventListener(brightcove.player.events.ExperienceEvent.TEMPLATE_READY, onPlayerReady); } }());
Handle webservice problems in ChEBI client
import suds import re import logging logger = logging.getLogger('suds') logger.setLevel(logging.ERROR) chebi_wsdl = 'http://www.ebi.ac.uk/webservices/chebi/2.0/webservice?wsdl' try: chebi_client = suds.client.Client(chebi_wsdl) except Exception as e: logger.error('ChEBI web service is unavailable.') chebi_client = None def get_id(name, max_results=1): # TODO: reimplement to get result from actual returned object # not based on string matching if chebi_client is None: return None res = chebi_client.service.getLiteEntity(name, 'CHEBI NAME', max_results, 'ALL') res_str = str(res) if res_str == '': return None match = re.search(r'"CHEBI:(.*)"', res_str) chebi_id = match.groups()[0] return chebi_id
import suds import re import logging logger = logging.getLogger('suds') logger.setLevel(logging.ERROR) chebi_wsdl = 'http://www.ebi.ac.uk/webservices/chebi/2.0/webservice?wsdl' chebi_client = suds.client.Client(chebi_wsdl) def get_id(name, max_results=1): # TODO: reimplement to get result from actual returned object # not based on string matching res = chebi_client.service.getLiteEntity(name, 'CHEBI NAME', max_results, 'ALL') res_str = str(res) if res_str == '': return None match = re.search(r'"CHEBI:(.*)"', res_str) chebi_id = match.groups()[0] return chebi_id
Reset data before reading file contents
<?php namespace DataStream; /** * Data source loader */ class Source { protected $data = null; /** * @var boolean Whether the file should be read once or every time getData is called */ public $loadOnce; /** * @var string Path to the last file loaded */ public $filePath = null; /** * @var array Array of file paths to be read and concatenated */ public $filePaths = null; function __construct($loadOnce = true) { $this->loadOnce = $loadOnce; } public function loadFromFile($filePath) { $this->filePath = $filePath; $this->data = file_get_contents($filePath); } public function loadFromFiles(array $filePaths) { $this->data = ''; foreach ($filePaths as $filePath) { $this->data .= file_get_contents($filePath); } } public function getData() { if (!$this->loadOnce && $this->filePath) { $this->loadFromFile($this->filePath); }elseif (!$this->loadOnce && is_array($this->filePaths)) { $this->loadFromFiles($this->filePaths); } return $this->data; } public function setData($data) { $this->data = $data; return $this; } }
<?php namespace DataStream; /** * Data source loader */ class Source { protected $data = null; /** * @var boolean Whether the file should be read once or every time getData is called */ public $loadOnce; /** * @var string Path to the last file loaded */ public $filePath = null; /** * @var array Array of file paths to be read and concatenated */ public $filePaths = null; function __construct($loadOnce = true) { $this->loadOnce = $loadOnce; } public function loadFromFile($filePath) { $this->filePath = $filePath; $this->data = file_get_contents($filePath); } public function loadFromFiles(array $filePaths) { foreach ($filePaths as $filePath) { $this->data .= file_get_contents($filePath); } } public function getData() { if (!$this->loadOnce && $this->filePath) { $this->loadFromFile($this->filePath); }elseif (!$this->loadOnce && is_array($this->filePaths)) { $this->loadFromFiles($this->filePaths); } return $this->data; } public function setData($data) { $this->data = $data; return $this; } }
Refresh model when pressing escape within validated input.
core.directive("validatedinput", function() { return { template: '<span ng-include src="view"></span>', restrict: 'E', scope: { "type": "@", "model": "=", "property": "@", "label": "@", "placeholder": "@", "truevalue": "@", "falsevalue": "@", "blur": "&", "results": "=" }, link: function ($scope, element, attr) { $scope.view = attr.view ? attr.view : "bower_components/core/app/views/directives/validatedInput.html"; $scope.keydown = function($event) { // enter(13): submit value to be persisted if($event.which == 13) { $event.target.blur(); } // escape(27): reset value using shadow if($event.which == 27) { $scope.model.refresh(); } }; } }; });
core.directive("validatedinput", function() { return { template: '<span ng-include src="view"></span>', restrict: 'E', scope: { "type": "@", "model": "=", "property": "@", "label": "@", "placeholder": "@", "truevalue": "@", "falsevalue": "@", "blur": "&", "results": "=" }, link: function ($scope, element, attr) { $scope.view = attr.view ? attr.view : "bower_components/core/app/views/directives/validatedInput.html"; $scope.keydown = function($event) { if($event.which == 13) { $event.target.blur(); } }; } }; });
Create input for submit button
document.getElementById("ayuda").setAttribute("aria-current", "page"); var aside = document.getElementById("complementario"); var form = document.createElement("FORM"); var p = document.createElement("P"); var label = document.createElement("LABEL"); label.setAttribute("for", "repo"); t = document.createTextNode("cuenta/repositorio de GitHub"); label.appendChild(t); var input = document.createElement("INPUT"); input.setAttribute("type", "text"); input.setAttribute("id", "repo"); input.setAttribute("name", "repo"); label.appendChild(input); var submit = document.createElement("INPUT"); submit.setAttribute("id", "submit"); submit.setAttribute("type", "button"); var t = document.createTextNode("Consultar descargas de última versión"); submit.appendChild(t); p.appendChild(label); form.appendChild(p); form.appendChild(submit); $(document).ready(function () { $("#submit").click(function () { $.getJSON("https://api.github.com/repos/releases/latest", function(json) { var name = json.name; }); }); });
document.getElementById("ayuda").setAttribute("aria-current", "page"); var aside = document.getElementById("complementario"); var form = document.createElement("FORM"); var p = document.createElement("P"); var label = document.createElement("LABEL"); label.setAttribute("for", "repo"); t = document.createTextNode("cuenta/repositorio de GitHub"); label.appendChild(t); var input = document.createElement("INPUT"); input.setAttribute("type", "text"); input.setAttribute("id", "repo"); input.setAttribute("name", "repo"); label.appendChild(input); var submit = document.createElement("BUTTON"); submit.setAttribute("id", "submit"); submit.setAttribute("type", "button"); var t = document.createTextNode("Consultar descargas de última versión"); submit.appendChild(t); p.appendChild(label); form.appendChild(p); form.appendChild(submit); $(document).ready(function () { $("#submit").click(function () { $.getJSON("https://api.github.com/repos/releases/latest", function(json) { var name = json.name; }); }); });