text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix tests to check status code, and not expect exception
package keywhiz.service.resources; import com.codahale.metrics.health.HealthCheck; import com.codahale.metrics.health.HealthCheckRegistry; import io.dropwizard.setup.Environment; import java.util.TreeMap; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.core.Response; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class StatusResponseTest { HealthCheckRegistry registry; Environment environment; StatusResource status; @Before public void setUp() throws Exception { this.registry = mock(HealthCheckRegistry.class); this.environment = mock(Environment.class); this.status = new StatusResource(environment); when(environment.healthChecks()).thenReturn(registry); } @Test public void testStatusOk() throws Exception { when(registry.runHealthChecks()).thenReturn(new TreeMap<>()); Response r = status.get(); assertThat(r.getStatus()).isEqualTo(200); } @Test public void testStatusWarn() throws Exception { TreeMap<String, HealthCheck.Result> map = new TreeMap<>(); map.put("test", HealthCheck.Result.unhealthy("failing")); when(registry.runHealthChecks()).thenReturn(map); Response r = status.get(); assertThat(r.getStatus()).isEqualTo(500); } }
package keywhiz.service.resources; import com.codahale.metrics.health.HealthCheck; import com.codahale.metrics.health.HealthCheckRegistry; import io.dropwizard.setup.Environment; import java.util.TreeMap; import javax.ws.rs.InternalServerErrorException; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class StatusResponseTest { HealthCheckRegistry registry; Environment environment; StatusResource status; @Before public void setUp() throws Exception { this.registry = mock(HealthCheckRegistry.class); this.environment = mock(Environment.class); this.status = new StatusResource(environment); when(environment.healthChecks()).thenReturn(registry); } @Test public void testStatusOk() throws Exception { when(registry.runHealthChecks()).thenReturn(new TreeMap<>()); status.get(); } @Test(expected = InternalServerErrorException.class) public void testStatusWarn() throws Exception { TreeMap<String, HealthCheck.Result> map = new TreeMap<>(); map.put("test", HealthCheck.Result.unhealthy("failing")); when(registry.runHealthChecks()).thenReturn(map); status.get(); } }
Change interface for make change in implementation
'use strict'; const EventEmitter = require('events'); /** * Tracker Manager * @interface */ class ITrackerManager extends EventEmitter { constructor() { super(); if (this.constructor === ITrackerManager) { throw new TypeError('Can not create new instance of interface'); } } /** * Include tracker in search * @param {ITracker} tracker * @return {string|undefined} UID of tracker in list */ include(tracker) { throw new TypeError('Method "include" is not implemented.'); } /** * Exclude tracker from search * @param {string} uid * @return {ITracker|undefined} Excluded Tracker instance */ exclude(uid) { throw new TypeError('Method "exclude" is not implemented.'); } /** * Search in all included trackers * @param {SearchParams} searchParams */ search(searchParams) { throw new TypeError('Method "search" is not implemented.'); } } module.exports = ITrackerManager;
'use strict'; const EventEmitter = require('events'); /** * Tracker Manager * @interface */ class ITrackerManager extends EventEmitter { constructor() { super(); if (this.constructor === ITrackerManager) { throw new TypeError('Can not create new instance of interface'); } } /** * Include tracker in search * @param {ITracker} tracker * @return {number|undefined} Index of tracker in array */ include(tracker) { throw new TypeError('Method "include" is not implemented.'); } /** * Exclude tracker from search * @param {number} index * @return {ITracker|undefined} Excluded Tracker instance */ exclude(index) { throw new TypeError('Method "exclude" is not implemented.'); } /** * Search in all included trackers * @param {SearchParams} searchParams */ search(searchParams) { throw new TypeError('Method "search" is not implemented.'); } } module.exports = ITrackerManager;
Change \dt syntax to add an optional table name.
import logging from .main import special_command, RAW_QUERY, PARSED_QUERY log = logging.getLogger(__name__) @special_command('\\dt', '\\dt [table]', 'List or describe tables.', arg_type=PARSED_QUERY, case_sensitive=True) def list_tables(cur, arg=None, arg_type=PARSED_QUERY): if arg: query = 'SHOW FIELDS FROM {0}'.format(arg) else: query = 'SHOW TABLES' log.debug(query) cur.execute(query) if cur.description: headers = [x[0] for x in cur.description] return [(None, cur, headers, '')] else: return [(None, None, None, '')] @special_command('\\l', '\\l', 'List databases.', arg_type=RAW_QUERY, case_sensitive=True) def list_databases(cur, **_): query = 'SHOW DATABASES' log.debug(query) cur.execute(query) if cur.description: headers = [x[0] for x in cur.description] return [(None, cur, headers, '')] else: return [(None, None, None, '')]
import logging from .main import special_command, RAW_QUERY, PARSED_QUERY log = logging.getLogger(__name__) @special_command('\\dt', '\\dt', 'List or describe tables.', arg_type=PARSED_QUERY, case_sensitive=True) def list_tables(cur, arg=None, arg_type=PARSED_QUERY): if arg: query = 'SHOW FIELDS FROM {0}'.format(arg) else: query = 'SHOW TABLES' log.debug(query) cur.execute(query) if cur.description: headers = [x[0] for x in cur.description] return [(None, cur, headers, '')] else: return [(None, None, None, '')] @special_command('\\l', '\\l', 'List databases.', arg_type=RAW_QUERY, case_sensitive=True) def list_databases(cur, **_): query = 'SHOW DATABASES' log.debug(query) cur.execute(query) if cur.description: headers = [x[0] for x in cur.description] return [(None, cur, headers, '')] else: return [(None, None, None, '')]
Revert "use only one expectation" This reverts commit 21b733c10c04691717e49bd8a03b83b21976e4b5.
<?php namespace PHPSpec2\Mocker\Mockery; use Mockery; use PHPSpec2\Mocker\MockProxyInterface; use PHPSpec2\Stub\ArgumentsResolver; class MockProxy implements MockProxyInterface { private $originalMock; public function __construct($classOrInterface) { $this->originalMock = Mockery::mock($classOrInterface); $this->originalMock->shouldIgnoreMissing(); } public function getOriginalMock() { return $this->originalMock; } public function mockMethod($method, array $arguments, ArgumentsResolver $resolver) { return new ExpectationProxy( $this->originalMock->shouldReceive($method), $arguments, $resolver ); } }
<?php namespace PHPSpec2\Mocker\Mockery; use Mockery; use PHPSpec2\Mocker\MockProxyInterface; use PHPSpec2\Stub\ArgumentsResolver; class MockProxy implements MockProxyInterface { private $originalMock; public function __construct($classOrInterface) { $this->originalMock = Mockery::mock($classOrInterface); $this->originalMock->shouldIgnoreMissing(); } public function getOriginalMock() { return $this->originalMock; } public function mockMethod($method, array $arguments, ArgumentsResolver $resolver) { if ($director = $this->originalMock->mockery_getExpectationsFor($method)) { $expectations = $director->getExpectations(); $expectation = end($expectations); } else { $expectation = $this->originalMock->shouldReceive($method); } return new ExpectationProxy($expectation, $arguments, $resolver); } }
Check to ensure that we're dealing with "green" threads
from guv.green import threading, time def f1(): """A simple function """ print('Hello, world!') def f2(): """A simple function that sleeps for a short period of time """ time.sleep(0.1) class TestThread: def test_thread_create(self): t = threading.Thread(target=f1) assert 'green' in repr(t) def test_thread_start(self): t = threading.Thread(target=f1) assert 'green' in repr(t) t.start() def test_thread_join(self): t = threading.Thread(target=f1) assert 'green' in repr(t) t.start() t.join() def test_thread_active(self): initial_count = threading.active_count() t = threading.Thread(target=f2) assert 'green' in repr(t) t.start() assert threading.active_count() > initial_count t.join() assert threading.active_count() == initial_count
from guv.green import threading, time def f1(): """A simple function """ print('Hello, world!') def f2(): """A simple function that sleeps for a short period of time """ time.sleep(0.1) class TestThread: def test_thread_create(self): t = threading.Thread(target=f1) assert t def test_thread_start(self): t = threading.Thread(target=f1) t.start() assert t def test_thread_join(self): t = threading.Thread(target=f1) t.start() t.join() assert t def test_thread_active(self): initial_count = threading.active_count() t = threading.Thread(target=f2) t.start() assert threading.active_count() > initial_count t.join() assert threading.active_count() == initial_count
Resolve Minor Issues with Test Ensure that the tensorflow tests run on the CPU
# Lint as: python3 """Tests for spectral.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np import os import layers class LayersTest(tf.test.TestCase): def test_conv_transpose_shape(self): inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32) conv_transpose = layers.Conv1DTranspose( filters=2, kernel_size=1, strides=1 ) outputs = conv_transpose(inputs) self.assertShapeEqual(inputs, outputs) if __name__ == '__main__': os.environ["CUDA_VISIBLE_DEVICES"] = '' tf.test.main()
# Lint as: python3 """Tests for spectral.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np import layers class LayersTest(tf.test.TestCase): def test_conv_transpose_shape(self): inputs = np.random.normal(size=(10, 5, 2)) conv_transpose = layers.Conv1DTranspose(filters=2, kernel_size=1, strides=1) outputs = conv_transpose(inputs) self.assertShapeEqual(inputs, outputs) if __name__ == '__main__': tf.test.main()
Update to SDK 1.0.0-M8 in integration test scope.
package controllers; import io.sphere.sdk.categories.Category; import io.sphere.sdk.categories.queries.CategoryQuery; import io.sphere.sdk.queries.PagedQueryResult; import org.junit.Test; import testutils.WithPlayJavaClient; import java.util.Locale; import static org.fest.assertions.Assertions.assertThat; public class ApplicationControllerIntegrationTest extends WithPlayJavaClient { @Test public void itFindsSomeCategories() throws Exception { final PagedQueryResult<Category> queryResult = client.execute(CategoryQuery.of()).get(2000); final int count = queryResult.size(); assertThat(count).isGreaterThan(3); //this is a project specific assertion as example assertThat(queryResult.getResults().get(0).getName().get(Locale.ENGLISH).get()).isEqualTo("Tank tops"); } }
package controllers; import io.sphere.sdk.categories.Category; import io.sphere.sdk.categories.queries.CategoryQuery; import io.sphere.sdk.queries.PagedQueryResult; import org.junit.Test; import testutils.WithPlayJavaClient; import java.util.Locale; import static org.fest.assertions.Assertions.assertThat; public class ApplicationControllerIntegrationTest extends WithPlayJavaClient { @Test public void itFindsSomeCategories() throws Exception { final PagedQueryResult<Category> queryResult = client.execute(new CategoryQuery()).get(2000); final int count = queryResult.size(); assertThat(count).isGreaterThan(3); //this is a project specific assertion as example assertThat(queryResult.getResults().get(0).getName().get(Locale.ENGLISH).get()).isEqualTo("Tank tops"); } }
Add a column for archive link
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateBookmarksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('bookmarks', function (Blueprint $table) { $table->increments('id'); $table->string('url'); $table->string('name')->nullable(); $table->text('content')->nullable(); $table->uuid('screenshot')->nullable(); $table->string('archve')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('bookmarks'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateBookmarksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('bookmarks', function (Blueprint $table) { $table->increments('id'); $table->string('url'); $table->string('name')->nullable(); $table->text('content')->nullable(); $table->uuid('screenshot')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('bookmarks'); } }
Fix problem with header lenght
<?php return [ 'settings' => [ 'determineRouteBeforeAppMiddleware' => false, 'displayErrorDetails' => true, 'events_upload' => __DIR__.'/../public/uploads/evenements/', 'addContentLengthHeader' => false, 'view' => [ 'template_path' => __DIR__ . '/../src/App/Resources/views', 'twig' => [ 'cache' => __DIR__ . '/../cache', 'debug' => true, 'auto_reload' => true, ], ], 'routes' => [ 'dir' => __DIR__ . '/../src/App/Resources/routes', 'files' => [ 'app', 'auth', 'evenement', 'user', 'epreuve' ] ], ], ];
<?php return [ 'settings' => [ 'determineRouteBeforeAppMiddleware' => false, 'displayErrorDetails' => true, 'events_upload' => __DIR__.'/../public/uploads/evenements/', 'view' => [ 'template_path' => __DIR__ . '/../src/App/Resources/views', 'twig' => [ 'cache' => __DIR__ . '/../cache', 'debug' => true, 'auto_reload' => true, ], ], 'routes' => [ 'dir' => __DIR__ . '/../src/App/Resources/routes', 'files' => [ 'app', 'auth', 'evenement', 'user', 'epreuve' ] ], ], ];
Fix error response not returning errors.
<?php namespace FluxBB\Server\Response; use FluxBB\Server\Request; use Illuminate\Support\Contracts\MessageProviderInterface; use Illuminate\Support\MessageBag; class Error extends Redirect implements MessageProviderInterface { protected $errors; public function __construct(Request $next, MessageBag $errors) { parent::__construct($next); $this->errors = $errors; } public function getErrors() { return $this->errors; } public function accept(HandlerInterface $handler) { return $handler->handleErrorResponse($this); } /** * Get the messages for the instance. * * @return \Illuminate\Support\MessageBag */ public function getMessageBag() { return $this->getErrors(); } }
<?php namespace FluxBB\Server\Response; use FluxBB\Server\Request; use Illuminate\Support\Contracts\MessageProviderInterface; use Illuminate\Support\MessageBag; class Error extends Redirect implements MessageProviderInterface { protected $errors; public function __construct(Request $next, MessageBag $errors) { parent::__construct($next); $this->errors = $errors; } public function getErrors() { return $this->errors; } public function accept(HandlerInterface $handler) { return $handler->handleErrorResponse($this); } /** * Get the messages for the instance. * * @return \Illuminate\Support\MessageBag */ public function getMessageBag() { $this->getErrors(); } }
[IMP] account_invoice_comment_template: Move comment_template_id field to the Invoicing tab [IMP] account_invoice_comment_template: rename partner field name from comment_template_id to invoice_comment_template_id [IMP] account_invoice_comment_template: Make partner field company_dependant and move domain definition of invoice fields from the view to the model [MOV] account_invoice_comment_template: comment_template_id to base_comment_template [IMP] account_invoice_comment_template: Translate templates when partner changes
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestResPartner(TransactionCase): def setUp(self): super(TestResPartner, self).setUp() self.template_id = self.env['base.comment.template'].create({ 'name': 'Comment before lines', 'position': 'before_lines', 'text': 'Text before lines', }) def test_commercial_partner_fields(self): # Azure Interior partner_id = self.env.ref('base.res_partner_12') partner_id.property_comment_template_id = self.template_id.id # Test childs propagation of commercial partner field for child_id in partner_id.child_ids: self.assertEqual( child_id.property_comment_template_id, self.template_id)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestResPartner(TransactionCase): def setUp(self): self.template_id = self.env['base.comment.template'].create({ 'name': 'Comment before lines', 'position': 'before_lines', 'text': 'Text before lines', }) def test_commercial_partner_fields(self): # Azure Interior partner_id = self.env.ref('base.res_partner_12') partner_id.property_comment_template_id = self.template_id.id # Test childs propagation of commercial partner field for child_id in partner_id.child_ids: self.assertEqual( child_id.property_comment_template_id == self.template_id)
Fix order for gulp modules - in task compile-sass
/** * Compile scss files listed in the config */ 'use strict'; const gulp = require('gulp'); const notify = require('gulp-notify'); const gulpif = require('gulp-if'); const sass = require('gulp-sass'); const autoprefixer = require('gulp-autoprefixer'); const gcmq = require('gulp-group-css-media-queries'); module.exports = function (options) { return (done) => { const { files, isGcmq } = options.sassFilesInfo; if (files.length > 0) { return gulp.src(files) .pipe(sass()) .on('error', notify.onError({ title: 'Sass compiling error', icon: './sys_icon/error_icon.png', wait: true })) .pipe(autoprefixer()) .pipe(gulpif(isGcmq, gcmq())) .pipe(gulp.dest(`./${options.dest}/css`)); } return done(); }; };
/** * Compile scss files listed in the config */ 'use strict'; const gulp = require('gulp'); const notify = require('gulp-notify'); const gulpif = require('gulp-if'); const sass = require('gulp-sass'); const autoprefixer = require('gulp-autoprefixer'); const gcmq = require('gulp-group-css-media-queries'); module.exports = function (options) { return (done) => { const { files, isGcmq } = options.sassFilesInfo; if (files.length > 0) { return gulp.src(files) .pipe(sass()) .on('error', notify.onError({ title: 'Sass compiling error', icon: './sys_icon/error_icon.png', wait: true })) .pipe(gulpif(isGcmq, gcmq())) .pipe(autoprefixer()) .pipe(gulp.dest(`./${options.dest}/css`)); } return done(); }; };
Fix task def for gulp 4
var log = require('color-log'), runSequenceGenerator = require('run-sequence'), createBundleTasks = require('./utils/createBundleTasks'); function build(callback) { var runSequence = runSequenceGenerator.use(gulp), buildTasks = [], browserifyCompleteFn = function() { log.mark('[BROWSERIFY] complete!'); callback(); }; if (!options.styles.skip) { buildTasks.push(options.taskPrefix + 'build-styles'); } if (!options.copy.skip) { buildTasks.push(options.taskPrefix + 'copy-resources'); } if (!options.browserify.skip) { buildTasks.push(options.taskPrefix + 'build-app'); tasks.browserify.createBundler(); } if (options.clean.skip) { runSequence(options.taskPrefix + 'jshint', buildTasks, browserifyCompleteFn); } else { runSequence(options.taskPrefix + 'jshint', options.taskPrefix + 'clean', buildTasks, browserifyCompleteFn); } } module.exports = function(gulp, options) { var tasks = createBundleTasks(gulp, options); /* Full build */ gulp.task(options.taskPrefix + 'build', build); // Alias default to do the build. After this file is run the default task can be overridden if desired. gulp.task('default', build); };
var log = require('color-log'), runSequenceGenerator = require('run-sequence'), createBundleTasks = require('./utils/createBundleTasks'); module.exports = function(gulp, options) { var tasks; tasks = createBundleTasks(gulp, options); /* Full build */ gulp.task(options.taskPrefix + 'build', function(callback) { var runSequence = runSequenceGenerator.use(gulp), buildTasks = [], browserifyCompleteFn = function() { log.mark('[BROWSERIFY] complete!'); callback(); }; if (!options.styles.skip) { buildTasks.push(options.taskPrefix + 'build-styles'); } if (!options.copy.skip) { buildTasks.push(options.taskPrefix + 'copy-resources'); } if (!options.browserify.skip) { buildTasks.push(options.taskPrefix + 'build-app'); tasks.browserify.createBundler(); } if (options.clean.skip) { runSequence(options.taskPrefix + 'jshint', buildTasks, browserifyCompleteFn); } else { runSequence(options.taskPrefix + 'jshint', options.taskPrefix + 'clean', buildTasks, browserifyCompleteFn); } }); // Alias default to do the build. After this file is run the default task can be overridden if desired. gulp.task('default', [options.taskPrefix + 'build']); };
Make the unit tests work with 2.6.
# Copyright (c) 2014, Matt Layman '''Tests for the StorageFactory.''' import unittest from markwiki.exceptions import ConfigurationError from markwiki.storage.factory import UserStorageFactory from markwiki.storage.fs.user import FileUserStorage class InitializeException(Exception): '''An exception to ensure storage initialization was invoked.''' class FakeUserStorage(object): def __init__(self, config): '''Do nothing.''' def initialize(self): raise InitializeException() class TestUserStorageFactory(unittest.TestCase): def setUp(self): self.factory = UserStorageFactory() def test_get_storage(self): config = { 'MARKWIKI_HOME': 'nothing', 'STORAGE_TYPE': 'file' } storage = self.factory._get_storage(config) self.assertTrue(isinstance(storage, FileUserStorage)) def test_invalid_storage(self): config = {} self.assertRaises(ConfigurationError, self.factory.get_storage, config) def test_storage_initializes(self): config = {'STORAGE_TYPE': 'file'} types = {'file': FakeUserStorage} factory = UserStorageFactory(storage_types=types) self.assertRaises(InitializeException, factory.get_storage, config)
# Copyright (c) 2014, Matt Layman '''Tests for the StorageFactory.''' import unittest from markwiki.exceptions import ConfigurationError from markwiki.storage.factory import UserStorageFactory from markwiki.storage.fs.user import FileUserStorage class InitializeException(Exception): '''An exception to ensure storage initialization was invoked.''' class FakeUserStorage(object): def __init__(self, config): '''Do nothing.''' def initialize(self): raise InitializeException() class TestUserStorageFactory(unittest.TestCase): def setUp(self): self.factory = UserStorageFactory() def test_get_storage(self): config = { 'MARKWIKI_HOME': 'nothing', 'STORAGE_TYPE': 'file' } storage = self.factory._get_storage(config) self.assertIsInstance(storage, FileUserStorage) def test_invalid_storage(self): config = {} self.assertRaises(ConfigurationError, self.factory.get_storage, config) def test_storage_initializes(self): config = {'STORAGE_TYPE': 'file'} types = {'file': FakeUserStorage} factory = UserStorageFactory(storage_types=types) self.assertRaises(InitializeException, factory.get_storage, config)
Make sure we use python2
#! /usr/bin/python2 # from the __future__ package, import division # to allow float division from __future__ import division def estimate_probs(trigram_counts_dict): ''' # Estimates probabilities of trigrams using # trigram_counts_dict and returns a new dictionary # with the probabilities. ''' trigram_probs_dict = dict.fromkeys(trigram_counts_dict) sum_counts = sum(trigram_counts_dict.values()) probs = [] for i in trigram_counts_dict.values(): i = i / sum_counts probs.append(i) i = 0 for key in trigram_probs_dict: trigram_probs_dict[key] = probs[i] i += 1 return trigram_probs_dict #--------------------------------------------------------# ''' # This is a test string ''' if __name__ == '__main__': s = { ' a ': 1, 's i': 1, 'his': 1, 'str': 1, 's a': 1, ' is': 1, 'ing': 1, ' st': 1, 'rin': 1, 'tri': 1, 'thi': 1, 'a s': 1, 'is ': 2 } print estimate_probs(s)
# from the __future__ package, import division # to allow float division from __future__ import division def estimate_probs(trigram_counts_dict): ''' # Estimates probabilities of trigrams using # trigram_counts_dict and returns a new dictionary # with the probabilities. ''' trigram_probs_dict = dict.fromkeys(trigram_counts_dict) sum_counts = sum(trigram_counts_dict.values()) probs = [] for i in trigram_counts_dict.values(): i = i / sum_counts probs.append(i) i = 0 for key in trigram_probs_dict: trigram_probs_dict[key] = probs[i] i += 1 return trigram_probs_dict #--------------------------------------------------------# ''' # This is a test string ''' if __name__ == '__main__': s = { ' a ': 1, 's i': 1, 'his': 1, 'str': 1, 's a': 1, ' is': 1, 'ing': 1, ' st': 1, 'rin': 1, 'tri': 1, 'thi': 1, 'a s': 1, 'is ': 2 } print estimate_probs(s)
Update copyright notice with MIT license
/*++ NASM Assembly Language Plugin Copyright (c) 2017-2018 Aidan Khoury Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --*/ package com.nasmlanguage.psi.impl; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.intellij.lang.ASTNode; import com.nasmlanguage.psi.NASMNamedElement; import org.jetbrains.annotations.NotNull; public abstract class NASMNamedElementImpl extends ASTWrapperPsiElement implements NASMNamedElement { public NASMNamedElementImpl(@NotNull ASTNode node) { super(node); } }
/*++ NASM Assembly Language Plugin Copyright (c) 2017-2018 Aidan Khoury. All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --*/ package com.nasmlanguage.psi.impl; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.intellij.lang.ASTNode; import com.nasmlanguage.psi.NASMNamedElement; import org.jetbrains.annotations.NotNull; public abstract class NASMNamedElementImpl extends ASTWrapperPsiElement implements NASMNamedElement { public NASMNamedElementImpl(@NotNull ASTNode node) { super(node); } }
Make Kirby cachbuster plugin compatible with PHP < 7.1
<?php /** * Kirby Asset Cachebuster Plugin * * @version 1.0.0 * @author Pedro Borges <oi@pedroborg.es> * @copyright Pedro Borges <oi@pedroborg.es> * @link https://github.com/pedroborges/kirby-asset-cachebuster * @license MIT */ if (! function_exists('asset')) { /** * Generate a versioned URL from a given asset path. * * @param string $path * @return string */ function asset($path) { if (! c::get('cachebuster')) return url($path); $file = kirby()->roots()->index().DS.$path; if (! file_exists($file)) { throw new Exception('The "'.$path.'" file does not exist.'); } $asset = dirname($path).'/'; $asset .= f::name($path).'.'; $asset .= filemtime($file).'.'; $asset .= f::extension($file); return url($asset); } }
<?php /** * Kirby Asset Cachebuster Plugin * * @version 1.0.0 * @author Pedro Borges <oi@pedroborg.es> * @copyright Pedro Borges <oi@pedroborg.es> * @link https://github.com/pedroborges/kirby-asset-cachebuster * @license MIT */ if (! function_exists('asset')) { /** * Generate a versioned URL from a given asset path. * * @param string $path * @return string */ function asset(string $path) { if (! c::get('cachebuster')) return url($path); $file = kirby()->roots()->index().DS.$path; if (! file_exists($file)) { throw new Exception('The "'.$path.'" file does not exist.'); } $asset = dirname($path).'/'; $asset .= f::name($path).'.'; $asset .= filemtime($file).'.'; $asset .= f::extension($file); return url($asset); } }
Remove todo: Renaming to uppercase breaks service discovery
<?php namespace Kibo\Phast\Services\Css; use Kibo\Phast\Filters\HTML\ImagesOptimizationService\ImageURLRewriter; use Kibo\Phast\Retrievers\Retriever; use Kibo\Phast\Security\ServiceSignature; use Kibo\Phast\Services\ProxyBaseService; use Kibo\Phast\Services\ServiceFilter; use Kibo\Phast\ValueObjects\Resource; class Service extends ProxyBaseService { /** * @var ImageURLRewriter */ private $imageUrlRewriter; public function __construct( ServiceSignature $signature, $whitelist, Retriever $retriever, ServiceFilter $filter, ImageURLRewriter $imageURLRewriter ) { parent::__construct($signature, $whitelist, $retriever, $filter); $this->imageUrlRewriter = $imageURLRewriter; } protected function makeResponse(Resource $resource, array $request) { $response = parent::makeResponse($resource, $request); $response->setHeader('Content-Type', 'text/css'); $response->setContent($this->imageUrlRewriter->rewriteStyle($response->getContent())); return $response; } }
<?php // TODO: Capitalize the css ns namespace Kibo\Phast\Services\Css; use Kibo\Phast\Filters\HTML\ImagesOptimizationService\ImageURLRewriter; use Kibo\Phast\Retrievers\Retriever; use Kibo\Phast\Security\ServiceSignature; use Kibo\Phast\Services\ProxyBaseService; use Kibo\Phast\Services\ServiceFilter; use Kibo\Phast\ValueObjects\Resource; class Service extends ProxyBaseService { /** * @var ImageURLRewriter */ private $imageUrlRewriter; public function __construct( ServiceSignature $signature, $whitelist, Retriever $retriever, ServiceFilter $filter, ImageURLRewriter $imageURLRewriter ) { parent::__construct($signature, $whitelist, $retriever, $filter); $this->imageUrlRewriter = $imageURLRewriter; } protected function makeResponse(Resource $resource, array $request) { $response = parent::makeResponse($resource, $request); $response->setHeader('Content-Type', 'text/css'); $response->setContent($this->imageUrlRewriter->rewriteStyle($response->getContent())); return $response; } }
Fix order of static and router to let static to handle static files first
/** * Module dependencies. */ var express = require('express') , routes = require('./routes') , http = require('http') , mongoose = require('mongoose'); // TODO: Refactor db connection string mongoose.connect('mongodb://localhost/nodewiki', function(err) { if (err) { console.log('Could not connect to database "' + 'mongodb://localhost/nodewiki' + '". Ensure that a mongo db instance is up and running.'); process.exit(1); } }); var app = express(); app.disable('x-powered-by'); app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.static(__dirname + '/public')); app.use(app.router); }); app.configure('development', function(){ app.use(express.errorHandler()); }); app.all('*', routes.loadPage); app.get('*', routes.showPage); app.post('*', routes.savePage); http.createServer(app).listen(app.get('port'), function(){ console.log("Express server listening on port " + app.get('port')); });
/** * Module dependencies. */ var express = require('express') , routes = require('./routes') , http = require('http') , mongoose = require('mongoose'); // TODO: Refactor db connection string mongoose.connect('mongodb://localhost/nodewiki', function(err) { if (err) { console.log('Could not connect to database "' + 'mongodb://localhost/nodewiki' + '". Ensure that a mongo db instance is up and running.'); process.exit(1); } }); var app = express(); app.disable('x-powered-by'); app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.configure('development', function(){ app.use(express.errorHandler()); }); app.all('*', routes.loadPage); app.get('*', routes.showPage); app.post('*', routes.savePage); http.createServer(app).listen(app.get('port'), function(){ console.log("Express server listening on port " + app.get('port')); });
Revert "Add Emoji list of `Binary_Property`s" This reverts commit 5dc3741e84f72e21a0376e2370475bd9691388bc.
const { assemble, writeFile, unicodeVersion } = require('./utils.js'); // This includes only the binary properties required by UTS18 RL1.2 for level 1 Unicode regex // support, minus `Assigned` which has special handling since it is the inverse of Unicode category // `Unassigned`. To include all binary properties, change this to: // `const properties = require(`${unicodeVersion}`).Binary_Property;` const properties = [ 'ASCII', 'Alphabetic', 'Any', 'Default_Ignorable_Code_Point', 'Lowercase', 'Noncharacter_Code_Point', 'Uppercase', 'White_Space' ]; const result = []; for (const property of properties) { const codePoints = require(`${unicodeVersion}/Binary_Property/${property}/code-points.js`); result.push(assemble({ name: property, codePoints })); } writeFile('properties.js', result);
const { assemble, writeFile, unicodeVersion } = require('./utils.js'); // This includes only the binary properties required by UTS18 RL1.2 for level 1 Unicode regex // support, minus `Assigned` which has special handling since it is the inverse of Unicode category // `Unassigned`. To include all binary properties, change this to: // `const properties = require(`${unicodeVersion}`).Binary_Property;` const properties = [ 'ASCII', 'Alphabetic', 'Any', 'Default_Ignorable_Code_Point', 'Emoji', 'Lowercase', 'Noncharacter_Code_Point', 'Uppercase', 'White_Space' ]; const result = []; for (const property of properties) { const codePoints = require(`${unicodeVersion}/Binary_Property/${property}/code-points.js`); result.push(assemble({ name: property, codePoints })); } writeFile('properties.js', result);
Check passed coordinates to be correct
import dataComplete from './actions/dataComplete'; import preprocessData from './actions/preprocessData'; import readFile from '../functions/file/readFile'; import preprocessFile from '../functions/file/preprocessFile'; import parseCoordinates from '../functions/parseCoordinates'; import issetCoordinates from '../functions/issetCoordinates'; import { PREPROCESSDATA, READDATA } from './constants'; const checkCoordinates = coordinates => issetCoordinates(parseCoordinates(coordinates)); const middleware = store => next => action => { const state = store.getState(); switch (action.type) { case READDATA: if (!state.coordIn || !state.fileIn || !checkCoordinates(state.coordIn)) { console.error('Input fields not filled properly!'); break; } next(action); readFile(state.fileInList) .then(data => { store.dispatch(preprocessData(data)); }).catch(error => { console.error(error.message); }); break; case PREPROCESSDATA: preprocessFile(action.payload) .then(data => { store.dispatch(dataComplete(data)); }).catch(error => { console.error(error.message); }); break; default: next(action); } }; export default middleware;
import dataComplete from './actions/dataComplete'; import preprocessData from './actions/preprocessData'; import readFile from '../functions/file/readFile'; import preprocessFile from '../functions/file/preprocessFile'; import { PREPROCESSDATA, READDATA } from './constants'; const middleware = store => next => action => { const state = store.getState(); switch (action.type) { case READDATA: if (!state.coordIn || !state.fileIn) { console.error('Input fields not filled properly!'); break; } next(action); readFile(state.fileInList) .then(data => { store.dispatch(preprocessData(data)); }).catch(error => { console.error(error.message); }); break; case PREPROCESSDATA: preprocessFile(action.payload) .then(data => { store.dispatch(dataComplete(data)); }).catch(error => { console.error(error.message); }); break; default: next(action); } }; export default middleware;
Validate slide max position and duration
<?php namespace Zeropingheroes\Lanager\Requests; class StoreSlideRequest extends Request { use LaravelValidation; /** * Whether the request is valid * * @return bool */ public function valid(): bool { $this->validationRules = [ 'lan_id' => ['required', 'numeric', 'exists:lans,id'], 'name' => ['required', 'max:255'], 'content' => ['required'], 'position' => ['integer', 'min:0', 'max:127'], 'duration' => ['integer', 'min:0', 'max:32767'], 'published' => ['boolean'], ]; if (!$this->laravelValidationPasses()) { return $this->setValid(false); } return $this->setValid(true); } }
<?php namespace Zeropingheroes\Lanager\Requests; class StoreSlideRequest extends Request { use LaravelValidation; /** * Whether the request is valid * * @return bool */ public function valid(): bool { $this->validationRules = [ 'lan_id' => ['required', 'numeric', 'exists:lans,id'], 'name' => ['required', 'max:255'], 'content' => ['required'], 'position' => ['integer'], 'duration' => ['integer'], 'published' => ['boolean'], ]; if (!$this->laravelValidationPasses()) { return $this->setValid(false); } return $this->setValid(true); } }
Add New Temps to Beginning
import time import requests class TemperatureMonitor: def __init__(self, temperature_sensor, interval=60, smoothing=5, observers=()): self.temperature_sensor = temperature_sensor self.interval = interval self.smoothing = smoothing self.observers = observers self.history = [] def run(self): while True: self.check_temp() time.sleep(self.interval) def check_temp(self): self.history = self.history[:self.smoothing-1] self.history.insert(0,self.temperature_sensor.get_temp()) sum = 0.0 for temp in self.history: sum += temp average = sum / len(self.history) self.report(average) def report(self, temp): for observer in self.observers: requests.post(observer, json={"temp": temp})
import time import requests class TemperatureMonitor: def __init__(self, temperature_sensor, interval=60, smoothing=5, observers=()): self.temperature_sensor = temperature_sensor self.interval = interval self.smoothing = smoothing self.observers = observers self.history = [] def run(self): while True: self.check_temp() time.sleep(self.interval) def check_temp(self): self.history = self.history[:self.smoothing-1] self.history.append(self.temperature_sensor.get_temp()) sum = 0.0 for temp in self.history: sum += temp average = sum / len(self.history) self.report(average) def report(self, temp): for observer in self.observers: requests.post(observer, json={"temp": temp})
Add to line 15 for testing.
import ephem from datetime import datetime def const(planet_name): # function name and parameters planet_class = getattr(ephem, planet_name) # sets ephem object class date_class = datetime.now() planet = planet_class() # sets planet variable south_bend = ephem.Observer() # Creates the Observer object south_bend.lat = '41.40' # latitude south_bend.lon = '-86.15' south_bend.date = date_class # sets date parameter planet.compute(south_bend) # calculates the location data print date_class print planet.ra, planet.dec print planet.alt, planet.az return ephem.constellation((planet.ra, planet.dec)) print const(raw_input('Planet: '))
import ephem from datetime import datetime def const(planet_name): # function name and parameters planet_class = getattr(ephem, planet_name) # sets ephem object class date_class = datetime.now() planet = planet_class() # sets planet variable south_bend = ephem.Observer() # Creates the Observer object south_bend.lat = '41.40' # latitude south_bend.lon = '-86.15' south_bend.date = date_class # sets date parameter planet.compute(south_bend) # calculates the location data print date_class print planet.ra, planet.dec return ephem.constellation((planet.ra, planet.dec)) print const(raw_input('Planet: '))
Use `CheckString` for test harness related func arguments.
package regexp_test import ( "github.com/Shopify/go-lua" "github.com/Shopify/goluago/regexp" "testing" ) func TestLuaRegexp(t *testing.T) { l := lua.NewState() lua.OpenLibraries(l) regexp.Open(l) failHook := func(l *lua.State) int { str := lua.CheckString(l, -1) lua.Pop(l, 1) t.Error(str) return 0 } lua.Register(l, "fail", failHook) wantTop := lua.Top(l) if err := lua.LoadFile(l, "testdata/regexptest.lua", "t"); err != nil { t.Fatalf("loading lua test script in VM, %v", err) } if err := lua.ProtectedCall(l, 0, 0, 0); err != nil { t.Errorf("executing lua test script, %v", err) } gotTop := lua.Top(l) if wantTop != gotTop { t.Errorf("Unbalanced stack!, want %d, got %d", wantTop, gotTop) } }
package regexp_test import ( "github.com/Shopify/go-lua" "github.com/Shopify/goluago/regexp" "testing" ) func TestLuaRegexp(t *testing.T) { l := lua.NewState() lua.OpenLibraries(l) regexp.Open(l) failHook := func(l *lua.State) int { str, ok := lua.ToString(l, -1) if !ok { t.Fatalf("need a string on the lua stack for calls to fail()") } lua.Pop(l, 1) t.Error(str) return 0 } lua.Register(l, "fail", failHook) wantTop := lua.Top(l) if err := lua.LoadFile(l, "testdata/regexptest.lua", "t"); err != nil { t.Fatalf("loading lua test script in VM, %v", err) } if err := lua.ProtectedCall(l, 0, 0, 0); err != nil { t.Errorf("executing lua test script, %v", err) } gotTop := lua.Top(l) if wantTop != gotTop { t.Errorf("Unbalanced stack!, want %d, got %d", wantTop, gotTop) } }
Switch test coverage reporting off for travis
if (!process.env.TRAVIS) { var semicov = require('semicov'); semicov.init('lib'); process.on('exit', semicov.report); } try { global.sinon = require('sinon'); } catch (e) { // ignore } var group_name = false, EXT_EXP; function it (should, test_case) { check_external_exports(); if (group_name) { EXT_EXP[group_name][should] = test_case; } else { EXT_EXP[should] = test_case; } } global.it = it; function context(name, tests) { check_external_exports(); EXT_EXP[name] = {}; group_name = name; tests({ before: function (f) { it('setUp', f); }, after: function (f) { it('tearDown', f); } }); group_name = false; } global.context = context; exports.init = function (external_exports) { EXT_EXP = external_exports; if (external_exports.done) { external_exports.done(); } }; function check_external_exports() { if (!EXT_EXP) throw new Error( 'Before run this, please ensure that ' + 'require("spec_helper").init(exports); called'); }
var semicov = require('semicov'); semicov.init('lib'); process.on('exit', semicov.report); try { global.sinon = require('sinon'); } catch (e) { // ignore } var group_name = false, EXT_EXP; function it (should, test_case) { check_external_exports(); if (group_name) { EXT_EXP[group_name][should] = test_case; } else { EXT_EXP[should] = test_case; } } global.it = it; function context(name, tests) { check_external_exports(); EXT_EXP[name] = {}; group_name = name; tests({ before: function (f) { it('setUp', f); }, after: function (f) { it('tearDown', f); } }); group_name = false; } global.context = context; exports.init = function (external_exports) { EXT_EXP = external_exports; if (external_exports.done) { external_exports.done(); } }; function check_external_exports() { if (!EXT_EXP) throw new Error( 'Before run this, please ensure that ' + 'require("spec_helper").init(exports); called'); }
Fix bug in language selection switching https://github.com/globaleaks/GlobaLeaks/issues/452
GLClient.controller('toolTipCtrl', ['$scope', '$rootScope', 'Authentication', '$location', '$cookies', 'Translations', 'Node', '$route', function($scope, $rootScope, Authentication, $location, $cookies, Translations, Node, $route) { if (!$cookies['language']) $cookies['language'] = 'en'; $scope.session_id = $cookies['session_id']; $scope.auth_landing_page = $cookies['auth_landing_page']; $scope.role = $cookies['role']; $scope.language = $cookies['language']; $rootScope.selected_language = $scope.language; Node.get(function(node_info) { $rootScope.available_languages = {}; $rootScope.languages_supported = Translations.supported_languages; $.each(node_info.languages_enabled, function(idx, lang) { $rootScope.available_languages[lang] = Translations.supported_languages[lang]; }); }); $scope.logout = Authentication.logout; $scope.$watch("language", function(){ $.cookie('language', $scope.language); $rootScope.selected_language = $scope.language; $route.reload(); }); $scope.$watch(function(scope){ return $cookies['session_id']; }, function(newVal, oldVal){ $scope.session_id = $cookies['session_id']; $scope.auth_landing_page = $cookies['auth_landing_page']; $scope.role = $cookies['role']; }); }]);
GLClient.controller('toolTipCtrl', ['$scope', '$rootScope', 'Authentication', '$location', '$cookies', 'Translations', 'Node', '$route', function($scope, $rootScope, Authentication, $location, $cookies, Translations, Node, $route) { if (!$cookies['language']) $cookies['language'] = 'en'; $scope.session_id = $cookies['session_id']; $scope.auth_landing_page = $cookies['auth_landing_page']; $scope.role = $cookies['role']; $scope.language = $cookies['language']; $rootScope.selected_language = $scope.language; Node.get(function(node_info) { $rootScope.available_languages = {}; $rootScope.languages_supported = Translations.supported_languages; $.each(node_info.languages_enabled, function(idx, lang) { $rootScope.available_languages[lang] = Translations.supported_languages[lang]; }); }); $scope.logout = Authentication.logout; $scope.$watch("language", function(){ $cookies['language'] = $scope.language; $route.reload(); }); $scope.$watch(function(scope){ return $cookies['session_id']; }, function(newVal, oldVal){ $scope.session_id = $cookies['session_id']; $scope.auth_landing_page = $cookies['auth_landing_page']; $scope.role = $cookies['role']; }); }]);
Use `Room.getCities` instead of checking each visible room controller
'use strict' /** * Top level program- it is responsible for launching everything else. */ class Player extends kernel.process { constructor (...args) { super(...args) this.priority = PRIORITIES_PLAYER } main () { this.launchChildProcess('respawner', 'respawner') this.launchChildProcess('intel', 'empire_intel') const cities = Room.getCities() let roomname for (roomname of cities) { /* Launch a "City" program for each city saved in memory. `Room.addCity` to add new rooms. */ if (Game.rooms[roomname].controller && Game.rooms[roomname].controller.my) { this.launchChildProcess(`room_${roomname}`, 'city', { 'room': roomname }) } } } } module.exports = Player
'use strict' /** * Top level program- it is responsible for launching everything else. */ class Player extends kernel.process { constructor (...args) { super(...args) this.priority = PRIORITIES_PLAYER } main () { this.launchChildProcess('respawner', 'respawner') this.launchChildProcess('intel', 'empire_intel') let roomname for (roomname of Object.keys(Game.rooms)) { /* Launch a "City" program for any room owned by this player */ if (Game.rooms[roomname].controller && Game.rooms[roomname].controller.my) { this.launchChildProcess(`room_${roomname}`, 'city', { 'room': roomname }) } } } } module.exports = Player
Check if array element is present before access Signed-off-by: Daniel Kesselberg <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@danielkesselberg.de>
<?php declare(strict_types=1); /** * @copyright Copyright (c) 2017 Joas Schilling <coding@schilljs.com> * * @author Joas Schilling <coding@schilljs.com> * * @license GNU AGPL version 3 or any later version * * 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/>. * */ namespace OCA\AdminAudit\Actions; class Console extends Action { /** * @param $arguments */ public function runCommand(array $arguments) { if (!isset($arguments[1]) || $arguments[1] === '_completion') { // Don't log autocompletion return; } // Remove `./occ` array_shift($arguments); $this->log('Console command executed: %s', ['arguments' => implode(' ', $arguments)], ['arguments'] ); } }
<?php declare(strict_types=1); /** * @copyright Copyright (c) 2017 Joas Schilling <coding@schilljs.com> * * @author Joas Schilling <coding@schilljs.com> * * @license GNU AGPL version 3 or any later version * * 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/>. * */ namespace OCA\AdminAudit\Actions; class Console extends Action { /** * @param $arguments */ public function runCommand(array $arguments) { if ($arguments[1] === '_completion') { // Don't log autocompletion return; } // Remove `./occ` array_shift($arguments); $this->log('Console command executed: %s', ['arguments' => implode(' ', $arguments)], ['arguments'] ); } }
Update Point to use normal dictionaries for its coordinates
class Point(object): """Contains information about for each scan point Attributes: positions (dict): Dict of str position_name -> float position for each scannable dimension. E.g. {"x": 0.1, "y": 2.2} lower (dict): Dict of str position_name -> float lower_bound for each scannable dimension. E.g. {"x": 0.95, "y": 2.15} upper (dict): Dict of str position_name -> float upper_bound for each scannable dimension. E.g. {"x": 1.05, "y": 2.25} indexes (list): List of int indexes for each dataset dimension, fastest changing last. E.g. [15] """ def __init__(self): self.positions = {} self.lower = {} self.upper = {} self.indexes = []
from collections import OrderedDict class Point(object): """Contains information about for each scan point Attributes: positions (dict): Dict of str position_name -> float position for each scannable dimension. E.g. {"x": 0.1, "y": 2.2} lower (dict): Dict of str position_name -> float lower_bound for each scannable dimension. E.g. {"x": 0.95, "y": 2.15} upper (dict): Dict of str position_name -> float upper_bound for each scannable dimension. E.g. {"x": 1.05, "y": 2.25} indexes (list): List of int indexes for each dataset dimension, fastest changing last. E.g. [15] """ def __init__(self): self.positions = OrderedDict() self.lower = OrderedDict() self.upper = OrderedDict() self.indexes = []
Fix kilikTable for Symfony 5.4
<?php namespace Kilik\TableBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() : TreeBuilder { $treeBuilder = new TreeBuilder('kilik_table'); $rootNode = $treeBuilder->getRootNode(); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
<?php namespace Kilik\TableBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('kilik_table'); $rootNode = $treeBuilder->getRootNode(); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
Fix typo in /data fixture.
import { Router, Route, connect } from '../../index'; // It expects a factory function that it can inject dependencies into. export default (React, browserHistory) => { const Home = React => { const component = ({ title }) => <h1 className="title">{ title }</h1>; const mapStateToProps = (state) => { const { title } = state; return { title }; }; return connect(mapStateToProps)(component); }; const Data = React => { const component = ({ data }) => <div className="data">{ data }</div>; const mapStateToProps = (state) => { const { data } = state; return { data }; }; return connect(mapStateToProps)(component); }; return ( <Router history={ browserHistory }> <Route path="/" component={ Home(React) } /> <Route path="/data" component={ Data(React) } /> </Router> ); };
import { Router, Route, connect } from '../../index'; // It expects a factory function that it can inject dependencies into. export default (React, browserHistory) => { const Home = React => { const component = ({ title }) => <h1 className="title">{ title }</h1>; const mapStateToProps = (state) => { const { title } = state; return { title }; }; return connect(mapStateToProps)(component); }; const Data = React => { const component = ({ data }) => <div className="data">{ data }</div>; const mapStateToProps = (state) => { const { title } = state; return { title }; }; return connect(mapStateToProps)(component); }; return ( <Router history={ browserHistory }> <Route path="/" component={ Home(React) } /> <Route path="/data" component={ Data(React) } /> </Router> ); };
Move default position of plot slightly (would cover visualization)
package edu.agh.tunev.ui.plot; import java.beans.PropertyVetoException; import javax.swing.JInternalFrame; import javax.swing.SwingUtilities; public abstract class AbstractPlot extends JInternalFrame { private static final long serialVersionUID = 1L; /** * Nazwa wykresu w UI. */ public static String PLOT_NAME; public AbstractPlot(int modelNumber, String modelName, int plotNumber, Class<? extends AbstractPlot> subclass) { String name = null; try { name = (String) subclass.getDeclaredField("PLOT_NAME").get(this); } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e1) { } setTitle(modelNumber + ": " + modelName + " - " + plotNumber + ": " + name); setSize(400, 300); setLocation(modelNumber * 20 + 400 + 20 + plotNumber * 20, modelNumber * 20 + 20 + plotNumber * 20); setFrameIcon(null); setResizable(true); setClosable(true); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setVisible(true); SwingUtilities.invokeLater(new Runnable() { public void run() { try { AbstractPlot.this.setSelected(true); } catch (PropertyVetoException e) { AbstractPlot.this.toFront(); } } }); } }
package edu.agh.tunev.ui.plot; import java.beans.PropertyVetoException; import javax.swing.JInternalFrame; import javax.swing.SwingUtilities; public abstract class AbstractPlot extends JInternalFrame { private static final long serialVersionUID = 1L; /** * Nazwa wykresu w UI. */ public static String PLOT_NAME; public AbstractPlot(int modelNumber, String modelName, int plotNumber, Class<? extends AbstractPlot> subclass) { String name = null; try { name = (String) subclass.getDeclaredField("PLOT_NAME").get(this); } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e1) { } setTitle(modelNumber + ": " + modelName + " - " + plotNumber + ": " + name); setSize(400, 300); setLocation(modelNumber * 20 + 400 + (plotNumber - 1) * 20, modelNumber * 20 + (plotNumber - 1) * 20); setFrameIcon(null); setResizable(true); setClosable(true); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setVisible(true); SwingUtilities.invokeLater(new Runnable() { public void run() { try { AbstractPlot.this.setSelected(true); } catch (PropertyVetoException e) { AbstractPlot.this.toFront(); } } }); } }
Mark output format as XML
'use strict'; var jade = require('jade'); var fs = require('fs'); exports.name = 'jade'; exports.outputFormat = 'xml'; exports.compile = function (source, options) { var fn = jade.compile(source, options); return {fn: fn, dependencies: fn.dependencies} }; exports.compileClient = function (source, options) { return jade.compileClientWithDependenciesTracked(source, options); }; exports.compileFile = function (path, options) { var fn = jade.compileFile(path, options); return {fn: fn, dependencies: fn.dependencies} }; exports.compileFileClient = function (path, options) { // There is no compileFileClientWithDependenciesTracked so gotta do it // manually. options = options || {}; options.filename = options.filename || path; return exports.compileClient(fs.readFileSync(path, 'utf8'), options); };
'use strict'; var jade = require('jade'); var fs = require('fs'); exports.name = 'jade'; exports.outputFormat = 'html'; exports.compile = function (source, options) { var fn = jade.compile(source, options); return {fn: fn, dependencies: fn.dependencies} }; exports.compileClient = function (source, options) { return jade.compileClientWithDependenciesTracked(source, options); }; exports.compileFile = function (path, options) { var fn = jade.compileFile(path, options); return {fn: fn, dependencies: fn.dependencies} }; exports.compileFileClient = function (path, options) { // There is no compileFileClientWithDependenciesTracked so gotta do it // manually. options = options || {}; options.filename = options.filename || path; return exports.compileClient(fs.readFileSync(path, 'utf8'), options); };
Remove unneeded call to Println
package cryptopals import ( "encoding/base64" "fmt" "math/big" "testing" ) func TestDecryptRsaParityOracle(t *testing.T) { priv := generateRsaPrivateKey(1024) pub := priv.public() encoded := "VGhhdCdzIHdoeSBJIGZvdW5kIHlvdSBkb24ndCBwbGF5IGFyb3VuZCB3aXRoIHRoZSBGdW5reSBDb2xkIE1lZGluYQ==" message, _ := base64.RawStdEncoding.DecodeString(encoded) m1 := new(big.Int).SetBytes(message) server := &parityOracleServer{priv: *priv} c := pub.encrypt(m1) m2 := challenge46{}.DecryptRsaParityOracle(server, pub, c) s1 := string(m1.Bytes()) s2 := string(m2.Bytes()) fmt.Println(s1) fmt.Println(s2) }
package cryptopals import ( "encoding/base64" "fmt" "math/big" "testing" ) func TestDecryptRsaParityOracle(t *testing.T) { priv := generateRsaPrivateKey(1024) pub := priv.public() fmt.Printf("n: %v\n\n", pub.n) encoded := "VGhhdCdzIHdoeSBJIGZvdW5kIHlvdSBkb24ndCBwbGF5IGFyb3VuZCB3aXRoIHRoZSBGdW5reSBDb2xkIE1lZGluYQ==" message, _ := base64.RawStdEncoding.DecodeString(encoded) m1 := new(big.Int).SetBytes(message) server := &parityOracleServer{priv: *priv} c := pub.encrypt(m1) m2 := challenge46{}.DecryptRsaParityOracle(server, pub, c) s1 := string(m1.Bytes()) s2 := string(m2.Bytes()) fmt.Println(s1) fmt.Println(s2) }
Change default layout to vertical Resolves #54
import { combineReducers } from 'redux' import { merge } from 'ramda' import { routerStateReducer } from 'redux-router' import { SETTINGS_CHANGE, DISPLAY_FILTERS_CHANGE } from '../constants/actionTypes' import data from './dataReducer' import ui from './uiReducer' import search from './searchReducer' import semester from './semesterReducer' import client from './clientReducer' import user from './userReducer' const initialSettings = { locale: 'cs', layout: 'vertical', eventsColors: false, fullWeek: false, facultyGrid: false, } const initialDisplayFilters = { /*eslint-disable */ laboratory: true, tutorial: true, lecture: true, exam: true, assessment: true, course_event: true, other: true, /*eslint-enable */ } function settings (state = initialSettings, action) { switch (action.type) { case SETTINGS_CHANGE: return merge(state, action.settings) default: return state } } function displayFilters (state = initialDisplayFilters, action) { switch (action.type) { case DISPLAY_FILTERS_CHANGE: return merge(state, action.displayFilters) default: return state } } const rootReducer = combineReducers({ router: routerStateReducer, settings, displayFilters, data, ui, search, semester, client, user, }) export default rootReducer
import { combineReducers } from 'redux' import { merge } from 'ramda' import { routerStateReducer } from 'redux-router' import { SETTINGS_CHANGE, DISPLAY_FILTERS_CHANGE } from '../constants/actionTypes' import data from './dataReducer' import ui from './uiReducer' import search from './searchReducer' import semester from './semesterReducer' import client from './clientReducer' import user from './userReducer' const initialSettings = { locale: 'cs', layout: 'horizontal', eventsColors: false, fullWeek: false, facultyGrid: false, } const initialDisplayFilters = { /*eslint-disable */ laboratory: true, tutorial: true, lecture: true, exam: true, assessment: true, course_event: true, other: true, /*eslint-enable */ } function settings (state = initialSettings, action) { switch (action.type) { case SETTINGS_CHANGE: return merge(state, action.settings) default: return state } } function displayFilters (state = initialDisplayFilters, action) { switch (action.type) { case DISPLAY_FILTERS_CHANGE: return merge(state, action.displayFilters) default: return state } } const rootReducer = combineReducers({ router: routerStateReducer, settings, displayFilters, data, ui, search, semester, client, user, }) export default rootReducer
GF-4248: Adjust main menu wide template. To be used in Activity one panel up sample, some code should be modified. Enyo-DCO-1.1-Signed-off-by: David Um <david.um@lge.com>
enyo.kind({ name: "moon.sample.video.MainMenuWideSample", kind: "moon.Panel", classes: "enyo-unselectable moon moon-video-mainmenu", titleAbove: "01", title: "Main Menu", components: [ /** If you want to use this template alone with spotlight, remove this comment out. {kind: "enyo.Spotlight"}, */ {kind: "FittableColumns", components: [ { classes: "moon-video-mainmenu-menu", components: [ {kind: "moon.Item", content: "Browser Movies"}, {kind: "moon.Item", content: "Browser TV Shows"}, {kind: "moon.Item", content: "Queue"}, {kind: "moon.Item", content: "Search"} ] }, { classes: "moon-video-mainmenu-content", content: "branding" } ]} ] });
enyo.kind({ name: "moon.sample.video.MainMenuWideSample", kind: "moon.Panel", classes: "enyo-unselectable moon moon-video-mainmenu", fit: true, titleAbove: "01", title: "Main Menu", components: [ {kind: "enyo.Spotlight"}, {kind: "FittableColumns", components: [ { classes: "moon-video-mainmenu-menu", components: [ {kind: "moon.Item", content: "Browser Movies", spotlight: true}, {kind: "moon.Item", content: "Browser TV Shows", spotlight: true}, {kind: "moon.Item", content: "Queue", spotlight: true}, {kind: "moon.Item", content: "Search", spotlight: true} ] }, { classes: "moon-video-mainmenu-content", content: "branding" } ]} ] });
Add data fetching for testing out Redis
import graphql from 'babel-plugin-relay/macro' import { createFragmentContainer } from 'react-relay' import Dashboard from 'js/components/Dashboard/DashboardComponent' export default createFragmentContainer(Dashboard, { app: graphql` fragment DashboardContainer_app on App { campaign { isLive numNewUsers # TODO: remove later. For testing Redis. } ...UserMenuContainer_app } `, user: graphql` fragment DashboardContainer_user on User { id experimentActions { referralNotification searchIntro } joined searches tabs ...WidgetsContainer_user ...UserBackgroundImageContainer_user ...UserMenuContainer_user ...LogTabContainer_user ...LogRevenueContainer_user ...LogConsentDataContainer_user ...LogAccountCreationContainer_user ...NewUserTourContainer_user ...AssignExperimentGroupsContainer_user } `, })
import graphql from 'babel-plugin-relay/macro' import { createFragmentContainer } from 'react-relay' import Dashboard from 'js/components/Dashboard/DashboardComponent' export default createFragmentContainer(Dashboard, { app: graphql` fragment DashboardContainer_app on App { campaign { isLive } ...UserMenuContainer_app } `, user: graphql` fragment DashboardContainer_user on User { id experimentActions { referralNotification searchIntro } joined searches tabs ...WidgetsContainer_user ...UserBackgroundImageContainer_user ...UserMenuContainer_user ...LogTabContainer_user ...LogRevenueContainer_user ...LogConsentDataContainer_user ...LogAccountCreationContainer_user ...NewUserTourContainer_user ...AssignExperimentGroupsContainer_user } `, })
Allow pngs to be the thumbnail.
// All JSON schemas related to ballot objects exports.candidates = { "title": "Ballot Candidates Schema", "type": "array", "minItems": 5, "items": { "type": "object", "properties": { "id": { "type": "string", "required":true }, "thumbnail": { "type": "string", "pattern": "^http:\/\/cf\.geekdo-images\.com\/images\/[a-z0-9]*_t\.(?:jpg|png)$", "required":true }, "name": { "type": "string", "required":true } }, "additionalProperties": false } };
// All JSON schemas related to ballot objects exports.candidates = { "title": "Ballot Candidates Schema", "type": "array", "minItems": 5, "items": { "type": "object", "properties": { "id": { "type": "string", "required":true }, "thumbnail": { "type": "string", "pattern": "^http:\/\/cf\.geekdo-images\.com\/images\/[a-z0-9]*_t\.jpg$", "required":true }, "name": { "type": "string", "required":true } }, "additionalProperties": false } };
Disable logging if NODE_ENV === 'test'.
const fs = require('fs') const _ = require('lodash') let isDisabled = false function buildMessage(obj) { if(typeof obj === 'string') { return obj + '\r\n' } else if(obj instanceof Array) { let str = '' _.each(obj, m => str += buildMessage(m)) return str } else if(obj instanceof Object) { return JSON.stringify(obj, null, 2) } } function log(message) { // Make sure the `log` directory exist. let root = process.cwd() try { fs.mkdirSync(`${root}/log`) } catch(err) { // Do nothing. `log` directory already exist. } finally { fs.appendFile(`${root}/log/${__ENV__}.log`, message, err => { if(err) throw err }) } } module.exports = { log(message) { if (__ENV__ === 'test') return message = buildMessage(message) + '\r\n' console.log(message) if (!isDisabled) log(message) }, disable(disable=true) { isDisabled = disable } }
const fs = require('fs') const _ = require('lodash') let isDisabled = false function buildMessage(obj) { if(typeof obj === 'string') { return obj + '\r\n' } else if(obj instanceof Array) { let str = '' _.each(obj, m => str += buildMessage(m)) return str } else if(obj instanceof Object) { return JSON.stringify(obj, null, 2) } } function log(message) { // Make sure the `log` directory exist. let root = process.cwd() try { fs.mkdirSync(`${root}/log`) } catch(err) { // Do nothing. `log` directory already exist. } finally { fs.appendFile(`${root}/log/${__ENV__}.log`, message, err => { if(err) throw err }) } } module.exports = { log(message) { message = buildMessage(message) + '\r\n' console.log(message) if (!isDisabled) log(message) }, disable(disable=true) { isDisabled = disable } }
Fix bug with google account refresh
'use strict'; angular.module('homepageApp') .controller('MainCtrl', function ($scope, $http, xmlFilter, Storage, Google, Gmail) { $scope.calendars = [ {src:'thibault.david@gmail.com', color: '#2952A3'}, {src:'2g5hhq1d0nk373earfrnlb37k8@group.calendar.google.com', color: '#B1365F'}, {src:'david.thibault@sigmund.ca', color: '#8C500B'} ]; $scope.addGoogleAccount = Google.newAccount; $scope.resetGoogleAccounts = function() { Storage.set("google_accounts", {}); } $scope.inboxes = []; var accounts = Google.getAccounts(); for (var id in accounts) { var a = accounts[id]; if (new Date() > new Date(a.expires)) { Google.refreshAccount(a); } else { Gmail.getUnreadInboxDetails(a) .then(function(details) { $scope.inboxes.push(details); }); } } });
'use strict'; angular.module('homepageApp') .controller('MainCtrl', function ($scope, $http, xmlFilter, Storage, Google, Gmail) { $scope.calendars = [ {src:'thibault.david@gmail.com', color: '#2952A3'}, {src:'2g5hhq1d0nk373earfrnlb37k8@group.calendar.google.com', color: '#B1365F'}, {src:'david.thibault@sigmund.ca', color: '#8C500B'} ]; $scope.addGoogleAccount = Google.newAccount; $scope.resetGoogleAccounts = function() { Storage.set("google_accounts", {}); } $scope.inboxes = []; var accounts = Google.getAccounts(); for (var id in accounts) { var a = accounts[id]; if (new Date() > a.expires) { Google.refreshAccount(a); } else { Gmail.getUnreadInboxDetails(a) .then(function(details) { $scope.inboxes.push(details); }); } } });
Remove unused functions in Expirer.js
var utils = require('./util'), util = require("util"), events = require("events"); function Expirer(collection, options){ var defaults = { expire_after_ms: 10 * 60 * 1000, time_attribute: 'touched' }, self = this, timer; options = utils.merge(defaults, options || {}); options.cleanup_interval = options.check_interval || options.expire_after_ms; function check_expiration(){ var i = 0, expire_time = new Date() - options.expire_after_ms, time_attr = options.time_attribute, keep_if = options.keep_if; for(var k in collection){ var obj = collection[k]; if(obj[time_attr] < expire_time && !(keep_if && keep_if(obj))){ self.emit('expired', obj); delete collection[k]; } } } timer = setInterval(check_expiration, options.cleanup_interval); } util.inherits(Expirer, events.EventEmitter); module.exports = Expirer;
var utils = require('./util'), util = require("util"), events = require("events"); function Expirer(collection, options){ var defaults = { expire_after_ms: 10 * 60 * 1000, time_attribute: 'touched' }, me = this, timer; options = utils.merge(defaults, options || {}); options.cleanup_interval = options.check_interval || options.expire_after_ms; function check_expiration(){ var i = 0, expire_time = new Date() - options.expire_after_ms, time_attr = options.time_attribute, keep_if = options.keep_if; for(var k in collection){ var obj = collection[k]; if(obj[time_attr] < expire_time && !(keep_if && keep_if(obj))){ me.emit('expired', obj); delete collection[k]; } } } this.pause = function(){ if(timer) clearInterval(timer); } this.start = function(){ if(!timer) timer = setInterval(check_expiration, options.cleanup_interval); } this.start(); } util.inherits(Expirer, events.EventEmitter); module.exports = Expirer;
Fix Firefox where 'onstorage' in window === false. Reversing the check works in all browsers
var support = module.exports = { // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting has: function(object, property){ var t = typeof object[property]; return t == 'function' || (!!(t == 'object' && object[property])) || t == 'unknown'; }, on: function(target, name, callback) { support.has(window, 'addEventListener') ? target.addEventListener(name, callback, false) : target.attachEvent('on' + name, callback); }, off: function(target, name, callback) { support.has(window, 'removeEventListener') ? target.removeEventListener(name, callback, false) : target.detachEvent('on' + name, callback); }, myWritesTrigger: ('onstoragecommit' in document), storageEventCanTriggerTwice: (navigator.userAgent.indexOf('Trident/7.0') >= 0), storageEventTarget: ('onstorage' in document ? document : window), storageEventProvidesKey: !('onstorage' in document) };
var support = module.exports = { // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting has: function(object, property){ var t = typeof object[property]; return t == 'function' || (!!(t == 'object' && object[property])) || t == 'unknown'; }, on: function(target, name, callback) { support.has(window, 'addEventListener') ? target.addEventListener(name, callback, false) : target.attachEvent('on' + name, callback); }, off: function(target, name, callback) { support.has(window, 'removeEventListener') ? target.removeEventListener(name, callback, false) : target.detachEvent('on' + name, callback); }, myWritesTrigger: ('onstoragecommit' in document), storageEventCanTriggerTwice: (navigator.userAgent.indexOf('Trident/7.0') >= 0), storageEventTarget: ('onstorage' in window ? window : document), storageEventProvidesKey: !('onstorage' in document) };
Fix case where there are no extension.
import sublime import os def getSetting(key,default=None): s = sublime.load_settings("Fuse.sublime-settings") return s.get(key, default) def getFusePathFromSettings(): path = getSetting("fuse_path_override") if path == "" or path == None: return "fuse" else: return path+"/fuse" def setSetting(key,value): s = sublime.load_settings("Fuse.sublime-settings") s.set(key, value) sublime.save_settings("Fuse.sublime-settings") def isSupportedSyntax(syntaxName): return syntaxName == "Uno" or syntaxName == "UX" def getExtension(path): base = os.path.basename(path) ext = os.path.splitext(base) if ext is None: return "" else: return ext[0] def getRowCol(view, pos): rowcol = view.rowcol(pos) rowcol = (rowcol[0] + 1, rowcol[1] + 1) return {"Line": rowcol[0], "Character": rowcol[1]}
import sublime import os def getSetting(key,default=None): s = sublime.load_settings("Fuse.sublime-settings") return s.get(key, default) def getFusePathFromSettings(): path = getSetting("fuse_path_override") if path == "" or path == None: return "fuse" else: return path+"/fuse" def setSetting(key,value): s = sublime.load_settings("Fuse.sublime-settings") s.set(key, value) sublime.save_settings("Fuse.sublime-settings") def isSupportedSyntax(syntaxName): return syntaxName == "Uno" or syntaxName == "UX" def getExtension(path): base = os.path.basename(path) return os.path.splitext(base)[0] def getRowCol(view, pos): rowcol = view.rowcol(pos) rowcol = (rowcol[0] + 1, rowcol[1] + 1) return {"Line": rowcol[0], "Character": rowcol[1]}
Handle some JEI stuff differently, still broken..
package codechicken.enderstorage.plugin.jei; import codechicken.enderstorage.recipe.RecipeBase; import com.google.common.collect.Sets; import mezz.jei.api.*; import mezz.jei.api.gui.ICraftingGridHelper; import mezz.jei.api.recipe.VanillaRecipeCategoryUid; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.registry.ForgeRegistries; import java.util.HashSet; import java.util.Set; /** * Created by covers1624 on 8/07/2017. */ @JEIPlugin//TODO FIXME TODO, Recipe handler for recoloring. public class EnderStorageJEIPlugin implements IModPlugin { public static ICraftingGridHelper gridHelper; @Override public void register(IModRegistry registry) { IJeiHelpers helpers = registry.getJeiHelpers(); IGuiHelper guiHelpers = helpers.getGuiHelper(); gridHelper = guiHelpers.createCraftingGridHelper(1, 0); registry.handleRecipes(RecipeBase.class, ESCraftingRecipeWrapper::new, VanillaRecipeCategoryUid.CRAFTING); } }
package codechicken.enderstorage.plugin.jei; import codechicken.enderstorage.recipe.RecipeBase; import mezz.jei.api.*; import mezz.jei.api.gui.ICraftingGridHelper; import mezz.jei.api.recipe.VanillaRecipeCategoryUid; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.registry.ForgeRegistries; import java.util.HashSet; import java.util.Set; /** * Created by covers1624 on 8/07/2017. */ @JEIPlugin//TODO FIXME TODO, Recipe handler for recoloring. public class EnderStorageJEIPlugin implements IModPlugin { public static ICraftingGridHelper gridHelper; @Override public void register(IModRegistry registry) { IJeiHelpers helpers = registry.getJeiHelpers(); IGuiHelper guiHelpers = helpers.getGuiHelper(); gridHelper = guiHelpers.createCraftingGridHelper(1, 0); Set<Object> recipes = new HashSet<>(); recipes.add(new ESCraftingRecipeWrapper((RecipeBase) ForgeRegistries.RECIPES.getValue(new ResourceLocation("enderstorage:ender_chest")))); recipes.add(new ESCraftingRecipeWrapper((RecipeBase) ForgeRegistries.RECIPES.getValue(new ResourceLocation("enderstorage:ender_tank")))); recipes.add(new ESCraftingRecipeWrapper((RecipeBase) ForgeRegistries.RECIPES.getValue(new ResourceLocation("enderstorage:ender_pouch")))); registry.addRecipes(recipes, VanillaRecipeCategoryUid.CRAFTING); } }
Delete existing files before downloading them again
package pl.niekoniecznie.p2e; import pl.niekoniecznie.polar.io.PolarEntry; import pl.niekoniecznie.polar.io.PolarFileSystem; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.FileTime; import java.util.function.Consumer; public class FileDownloader implements Consumer<PolarEntry> { private final Path backupDirectory; private final PolarFileSystem filesystem; public FileDownloader(Path backupDirectory, PolarFileSystem filesystem) { this.backupDirectory = backupDirectory; this.filesystem = filesystem; } @Override public void accept(PolarEntry entry) { if (entry.isDirectory()) { return; } InputStream source = filesystem.get(entry); Path destination = Paths.get(backupDirectory.toString(), entry.getPath()); try { Files.deleteIfExists(destination); Files.copy(source, destination); Files.setLastModifiedTime(destination, FileTime.from(entry.getModified())); } catch (IOException e) { throw new RuntimeException(e); } } }
package pl.niekoniecznie.p2e; import pl.niekoniecznie.polar.io.PolarEntry; import pl.niekoniecznie.polar.io.PolarFileSystem; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.FileTime; import java.util.function.Consumer; public class FileDownloader implements Consumer<PolarEntry> { private final Path backupDirectory; private final PolarFileSystem filesystem; public FileDownloader(Path backupDirectory, PolarFileSystem filesystem) { this.backupDirectory = backupDirectory; this.filesystem = filesystem; } @Override public void accept(PolarEntry entry) { if (entry.isDirectory()) { return; } InputStream source = filesystem.get(entry); Path destination = Paths.get(backupDirectory.toString(), entry.getPath()); try { Files.copy(source, destination); Files.setLastModifiedTime(destination, FileTime.from(entry.getModified())); } catch (IOException e) { throw new RuntimeException(e); } } }
Check if not using a mock fixed phpspec with hhvm
<?php namespace spec\League\Pipeline; use League\Pipeline\CallableOperation; use League\Pipeline\OperationInterface; use League\Pipeline\PipelineBuilder; use League\Pipeline\PipelineInterface; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class PipelineBuilderSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType(PipelineBuilder::class); } function it_should_build_a_pipeline() { $this->build()->shouldHaveType(PipelineInterface::class); } function it_should_collect_operations_for_a_pipeline() { $this->add(CallableOperation::forCallable(function ($p) { return $p * 2; })); $this->build()->process(4)->shouldBe(8); } function it_should_have_a_fluent_build_interface() { $operation = CallableOperation::forCallable(function () {}); $this->add($operation)->shouldBe($this); } }
<?php namespace spec\League\Pipeline; use League\Pipeline\CallableOperation; use League\Pipeline\OperationInterface; use League\Pipeline\PipelineBuilder; use League\Pipeline\PipelineInterface; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class PipelineBuilderSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType(PipelineBuilder::class); } function it_should_build_a_pipeline() { $this->build()->shouldHaveType(PipelineInterface::class); } function it_should_collect_operations_for_a_pipeline() { $this->add(CallableOperation::forCallable(function ($p) { return $p * 2; })); $this->build()->process(4)->shouldBe(8); } function it_should_have_a_fluent_build_interface(OperationInterface $operation) { $this->add($operation)->shouldBe($this); } }
Move from floats to Vectors
package main // Shifts all the values in xs by one and puts x at the beginning. func Shift(xs []Vector, x Vector) { for i := len(xs) - 1; i > 0; i-- { xs[i] = xs[i-1] } xs[0] = x } type Integrator func(xs, vs []Vector, a Vector, dt float64) // Performs a step of an Euler integration func Euler(xs, vs []Vector, a Vector, dt float64) { v := vs[0].Plus(a.Scale(dt)) x := xs[0].Plus(v.Scale(dt)) Shift(vs, v) Shift(xs, x) } // Performs a step of a Verlet integrator // // Note that v[0] will not be calculated until the next step func Verlet(xs, vs []Vector, a Vector, dt float64) { xNext := xs[0].Scale(2).Minus(xs[1]).Plus(a.Scale(dt * dt)) vs[0] = xNext.Minus(xs[1]).Scale(1 / (2 * dt)) Shift(vs, NewZeroVector()) Shift(xs, xNext) } func main() { }
package main // Shifts all the values in xs by one and puts x at the beginning. func Shift(xs []float64, x float64) { for i := len(xs) - 1; i > 0; i-- { xs[i] = xs[i-1] } xs[0] = x } type Integrator func(xs, vs []float64, a, dt float64) // Performs a step of an Euler integration func Euler(xs, vs []float64, a, dt float64) { v := vs[0] + dt*a x := xs[0] + dt*v Shift(vs, v) Shift(xs, x) } // Performs a step of a Verlet integrator // // Note that v[0] will not be calculated until the next step func Verlet(xs, vs []float64, a, dt float64) { xNext := 2*xs[0] - xs[1] + dt*dt*a v[0] = (xNext - xs[1]) / (2 * dt) Shift(vs, 0) Shift(xs, xNext) } func main() { }
Update cli for recently added models
import ujson as json from sift.build import DatasetBuilder from sift.models import links, text, embeddings class BuildDocModel(DatasetBuilder): """ Build a model over a corpus of text documents """ @classmethod def providers(cls): return [ links.EntityCounts, links.EntityNameCounts, links.EntityInlinks, links.EntityVocab, links.NamePartCounts, text.TermVocab, text.TermIdfs, text.TermFrequencies, text.TermDocumentFrequencies, text.EntityMentions, text.MappedEntityMentions, text.EntityMentionTermFrequency, text.TermEntityIndex, embeddings.EntitySkipGramEmbeddings, ]
import ujson as json from sift.build import DatasetBuilder from sift.models import links, text, embeddings class BuildDocModel(DatasetBuilder): """ Build a model over a corpus of text documents """ @classmethod def providers(cls): return [ links.EntityCounts, links.EntityNameCounts, links.EntityInlinks, text.TermIndicies, text.TermIdfs, text.TermFrequencies, text.TermDocumentFrequencies, text.EntityMentions, text.EntityMentionTermFrequency, text.TermEntityIndex, embeddings.EntitySkipGramEmbeddings, ]
Make the leap to v1
import setuptools REQUIREMENTS = [ "nose==1.3.0", "python-dateutil==1.5", ] if __name__ == "__main__": setuptools.setup( name="jsond", version="1.0.0", author="EDITD", author_email="engineering@editd.com", packages=setuptools.find_packages(), scripts=[], url="https://github.com/EDITD/jsond", license="LICENSE.txt", description="JSON (with dates)", long_description="View the github page (https://github.com/EDITD/jsond) for more details.", install_requires=REQUIREMENTS )
import setuptools REQUIREMENTS = [ "nose==1.3.0", "python-dateutil==1.5", ] if __name__ == "__main__": setuptools.setup( name="jsond", version="0.0.1", author="EDITD", author_email="engineering@editd.com", packages=setuptools.find_packages(), scripts=[], url="https://github.com/EDITD/jsond", license="LICENSE.txt", description="JSON (with dates)", long_description="View the github page (https://github.com/EDITD/jsond) for more details.", install_requires=REQUIREMENTS )
Update Target rendering to use gCamera.isInView
Target = function(x, y) { this.x = x; this.y = y; this.life = 11; this.size = 12; return this; } Target.prototype.render = (function(context) { function render() { var x = this.x - gCamera.x; var y = this.y - gCamera.y; // Only render if within the camera's bounds if (gCamera.isInView(this)) { context.beginPath(); context.arc(x + 2, y + 2, 13, 0, Math.PI * 2); context.fillStyle = '#222'; context.fill(); context.closePath(); context.beginPath(); context.arc(x, y, this.size, 0, Math.PI * 2); context.fillStyle = 'rgb(' + Math.round(255 * (this.life / this.size)) + ',' + Math.round(255 * ((this.size - this.life) / this.size)) + ',' + 0x22 + ')'; context.fill(); context.closePath(); } } return render; })(gRenderer.context);
Target = function(x, y) { this.x = x; this.y = y; this.life = 11; return this; } Target.prototype.render = (function(context) { function render() { var x = this.x - gCamera.x; var y = this.y - gCamera.y; // Only render if within the camera's bounds if (x + 12 > 0 && x - 12 < SCREEN_WIDTH && y + 12 > 0 && y - 12 < SCREEN_HEIGHT) { context.beginPath(); context.arc(x + 2, y + 2, 13, 0, Math.PI * 2); context.fillStyle = '#222'; context.fill(); context.closePath(); context.beginPath(); context.arc(x, y, 12, 0, Math.PI * 2); context.fillStyle = 'rgb(' + Math.round(255 * (this.life / 12)) + ',' + Math.round(255 * ((12 - this.life) / 12)) + ',' + 0x22 + ')'; context.fill(); context.closePath(); } } return render; })(gRenderer.context);
Add ID and timestamp for notifs from CB
package engine import ( "encoding/json" "time" "code.google.com/p/go-uuid/uuid" "iotrules/mylog" ) type NotifyContextRequest struct { SubscriptionId string Originator string ContextResponses []struct{ ContextElement ContextElement } } type ContextElement struct { Id string IsPattern string Type string Attributes []Attribute } type Attribute struct { Name string Type string Value string } func NewNotifFromCB(ngsi []byte, service int) (n *Notif, err error) { mylog.Debugf("enter NewNotifFromCB(%s,%d)\n", ngsi, service) defer func() { mylog.Debugf("exit NewNotifFromCB (%+v,%v)\n", n, err) }() n = &Notif{Data: map[string]interface{}{}} n.ID = uuid.New() n.Received = time.Now() var ncr NotifyContextRequest err = json.Unmarshal(ngsi, &ncr) if err != nil { return nil, err } mylog.Debugf("in NewNotifFromCB NotifyContextRequest: %+v\n", ncr) n.Data["id"] = ncr.ContextResponses[0].ContextElement.Id n.Data["type"] = ncr.ContextResponses[0].ContextElement.Type for _, attr := range ncr.ContextResponses[0].ContextElement.Attributes { n.Data[attr.Name] = attr.Value } return n, nil }
package engine import ( "encoding/json" "iotrules/mylog" ) type NotifyContextRequest struct { SubscriptionId string Originator string ContextResponses []struct{ ContextElement ContextElement } } type ContextElement struct { Id string IsPattern string Type string Attributes []Attribute } type Attribute struct { Name string Type string Value string } func NewNotifFromCB(ngsi []byte, service int) (n *Notif, err error) { mylog.Debugf("enter NewNotifFromCB(%s,%d)\n", ngsi, service) defer func() { mylog.Debugf("exit NewNotifFromCB (%+v,%v)\n", n, err) }() n = &Notif{Data: map[string]interface{}{}} var ncr NotifyContextRequest err = json.Unmarshal(ngsi, &ncr) if err != nil { return nil, err } mylog.Debugf("in NewNotifFromCB NotifyContextRequest: %+v\n", ncr) n.Data["id"] = ncr.ContextResponses[0].ContextElement.Id n.Data["type"] = ncr.ContextResponses[0].ContextElement.Type for _, attr := range ncr.ContextResponses[0].ContextElement.Attributes { n.Data[attr.Name] = attr.Value } return n, nil }
Add signature_request_invalid, template_created, and template_error event enum values.
package com.hellosign.sdk.resource.support.types; /** * The MIT License (MIT) * * Copyright (C) 2014 hellosign.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public enum EventType { signature_request_viewed, signature_request_signed, signature_request_sent, signature_request_all_signed, signature_request_invalid, template_created, template_error, file_error, test }
package com.hellosign.sdk.resource.support.types; /** * The MIT License (MIT) * * Copyright (C) 2014 hellosign.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public enum EventType { signature_request_viewed, signature_request_signed, signature_request_sent, signature_request_all_signed, file_error, test }
Return database results in root GET (3/16).
var express = require('express'); var cors = require('cors'); var bodyParser = require('body-parser'); var nano = require('nano')('http://localhost:5984'); var todo = nano.db.use('todo'); var app = express(); app.use(cors()); app.use(bodyParser.json()); app.get('/', function(req, res, next) { console.log('get triggered'); todo.view('todos', 'all_todos', function(err, body) { res.json(body.rows); }); }); app.post('/', function(req, res, next) { console.log('post triggered'); var task = {title: req.body.title}; todo.insert(task, function(err, body) { if (err) { console.log(err); } console.log(JSON.stringify(body)); task._id = body.id; task._rev = body.rev; res.json(task); }); }); app.delete('/', function(req, res, next) { console.log('delete triggered'); res.json([]); }); app.listen(3000, function() { console.log('Cors enabled server listening on port 3000'); });
var express = require('express'); var cors = require('cors'); var bodyParser = require('body-parser'); var nano = require('nano')('http://localhost:5984'); var todo = nano.db.use('todo'); var app = express(); app.use(cors()); app.use(bodyParser.json()); app.get('/', function(req, res, next) { console.log('get triggered'); res.json([]); }); app.post('/', function(req, res, next) { console.log('post triggered'); var task = {title: req.body.title}; todo.insert(task, function(err, body) { if (err) { console.log(err); } console.log(JSON.stringify(body)); task._id = body.id; task._rev = body.rev; res.json(task); }); }); app.delete('/', function(req, res, next) { console.log('delete triggered'); res.json([]); }); app.listen(3000, function() { console.log('Cors enabled server listening on port 3000'); });
Use current time if no arguments given
#!/bin/python import argparse import requests import timetable import datetime import time if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--day", default='', required=False, help="Day to check the timetable on. eg: Thursday") parser.add_argument("-t", "--time", default='', required=False, help="The time the block must be empty (HH:MM (24h))") args = parser.parse_args() time = args.time day = args.day if args.time == '': time = datetime.datetime.now().strftime("%H:%M") if args.day == '': day = datetime.datetime.now().strftime("%A") # print('Using ' + day + ' - ' + time) htmlRequest = requests.get("http://upnet.up.ac.za/tt/hatfield_timetable.html") timeTableObject = timetable.parseHTMLFile(htmlRequest.text) # Method 1 ; Elimination venueList = timetable.getVenueList(timeTableObject) filteredTimetable = timetable.getFilteredTimetable(day, time, timeTableObject, venueList) #for el in filteredTimetable: # print(el.venue) empty = timetable.getEmptyVenues(filteredTimetable, venueList) for el in empty: print(el)
#!/bin/python import argparse import requests import timetable if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--day", default='', required=True, help="Day to check the timetable on. eg: Thursday") parser.add_argument("-t", "--time", default='', required=True, help="The time the block must be empty (HH:MM (24h))") args = parser.parse_args() htmlRequest = requests.get("http://upnet.up.ac.za/tt/hatfield_timetable.html") timeTableObject = timetable.parseHTMLFile(htmlRequest.text) # Method 1 ; Elimination venueList = timetable.getVenueList(timeTableObject) filteredTimetable = timetable.getFilteredTimetable(args.day, args.time, timeTableObject, venueList) #for el in filteredTimetable: # print(el.venue) empty = timetable.getEmptyVenues(filteredTimetable, venueList) for el in empty: print(el)
Add default value in case missing. Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Foundation\Jobs; use Orchestra\Contracts\Authorization\Authorization; use Orchestra\Model\Role; class SyncDefaultAuthorization extends Job { /** * Re-sync administrator access control. * * @param \Orchestra\Contracts\Authorization\Authorization $acl * * @return void */ public function handle(Authorization $acl) { $actions = \config('orchestra/foundation::actions', [ 'Manage Users', 'Manage Orchestra', 'Manage Roles', 'Manage Acl', ]); $attaches = []; foreach ($actions as $action) { if (! $acl->actions()->has($action)) { $attaches[] = $action; } } if (! empty($attaches)) { $acl->actions()->attach($attaches); } $admin = Role::hs()->admin(); $acl->allow($admin->name, $actions); } }
<?php namespace Orchestra\Foundation\Jobs; use Orchestra\Contracts\Authorization\Authorization; use Orchestra\Model\Role; class SyncDefaultAuthorization extends Job { /** * Re-sync administrator access control. * * @param \Orchestra\Contracts\Authorization\Authorization $acl * * @return void */ public function handle(Authorization $acl) { $actions = \config('orchestra/foundation::actions', []); $attaches = []; foreach ($actions as $action) { if (! $acl->actions()->has($action)) { $attaches[] = $action; } } if (! empty($attaches)) { $acl->actions()->attach($attaches); } $admin = Role::hs()->admin(); $acl->allow($admin->name, $actions); } }
Add decimal and integer regex
/* * regex-pill * https://github.com/lgoldstien/regex-pill * * Copyright (c) 2014 Lawrence Goldstien * Licensed under the MIT license. */ 'use strict'; var RegexLibraryContents = { "hostnames/databases/mongodb": /^(mongodb:\/\/)([a-z0-9]+:[a-z0-9]+@)?([a-zA-Z0-9-_.]+)(:[0-9]+)?(\/[a-z_-]+)?$/g, "primatives/numerical/integerdecimal": /\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g, }; var RegexLibrary = function(name) { if (!name) { throw new ReferenceError("A regex name should be passed to this constructor."); } this.setRegex(name); return this._regex; }; RegexLibrary.prototype.setRegex = function(name) { if (RegexLibraryContents[name]) { this._regex = RegexLibraryContents[name]; } else { this._regex = ""; } }; module.exports = RegexLibrary;
/* * regex-pill * https://github.com/lgoldstien/regex-pill * * Copyright (c) 2014 Lawrence Goldstien * Licensed under the MIT license. */ 'use strict'; var RegexLibraryContents = { "hostnames/databases/mongodb": /^(mongodb:\/\/)([a-z0-9]+:[a-z0-9]+@)?([a-zA-Z0-9-_.]+)(:[0-9]+)?(\/[a-z_-]+)?$/g, }; var RegexLibrary = function(name) { if (!name) { throw new ReferenceError("A regex name should be passed to this constructor."); } this.setRegex(name); return this._regex; }; RegexLibrary.prototype.setRegex = function(name) { if (RegexLibraryContents[name]) { this._regex = RegexLibraryContents[name]; } else { this._regex = ""; } }; module.exports = RegexLibrary;
Update test code to compare with real type rather than string value.
package net.folab.fo.runtime; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import java.lang.reflect.Field; import net.folab.fo.runtime._fo._lang.Boolean; import net.folab.fo.runtime._fo._lang.Integer; import org.junit.Test; import org.junit.Before; public class GeneratedCodeTest { private Class<?> genClass; @Before public void setUp() throws ClassNotFoundException { genClass = Class.forName("net.folab.fo.runtime._"); } @Test public void test() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { test("_a", Integer.valueOf(1)); test("_b", Integer.valueOf(2)); test("_c", Integer.valueOf(3)); test("_d", Integer.valueOf(4)); test("_e", Integer.valueOf(5)); test("_f", Boolean.FALSE); test("_t", Boolean.TRUE); } public <T extends Evaluable<T>> void test(String name, Evaluable<T> expected) throws NoSuchFieldException, IllegalAccessException { Field field = genClass.getField(name); @SuppressWarnings("unchecked") Evaluable<T> value = (Evaluable<T>) field.get(null); assertThat(value.evaluate(), is(expected)); } }
package net.folab.fo.runtime; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import java.lang.reflect.Field; import org.junit.Test; import org.junit.Before; public class GeneratedCodeTest { private Class<?> genClass; @Before public void setUp() throws ClassNotFoundException { genClass = Class.forName("net.folab.fo.runtime._"); } @Test public void test() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { test("_a", "1"); test("_b", "2"); test("_c", "3"); test("_d", "4"); test("_e", "5"); test("_f", "false"); test("_t", "true"); } public void test(String name, String string) throws NoSuchFieldException, IllegalAccessException { Field field = genClass.getField(name); Evaluable<?> value = (Evaluable<?>) field.get(null); assertThat(value.evaluate().toString(), is(string)); } }
Remove this. on gpio ref
const WebSocket = require('ws'); const gpio = require('rpi-gpio') const wss = new WebSocket.Server({ port: 8080 }); var power = false; var mute = false; const pinConfig = { power: 18, mute: 17 } wss.on('connection', function connection(ws) { gpio.setMode(gpio.MODE_BCM); ws.on('message', function incoming(message) { if (message == 'powerToggle') { power = !power; writePin(pinConfig.mute, true); writePin(pinConfig.power, power); } if (message == 'muteToggle') { mute = !mute; writePin(pinConfig.mute, mute); } }); ws.send('something'); }); function writePin(pinNumber, value) { gpio.setup(pinNumber, gpio.DIR_OUT, write); function write() { gpio.write(pinNumber, value, function (err) { if (err) throw err; console.log('Written to pin ' + pinNumber); }); } }
const WebSocket = require('ws'); const gpio = require('rpi-gpio') const wss = new WebSocket.Server({ port: 8080 }); var power = false; var mute = false; const pinConfig = { power: 18, mute: 17 } wss.on('connection', function connection(ws) { gpio.setMode(gpio.MODE_BCM); ws.on('message', function incoming(message) { if (message == 'powerToggle') { power = !power; writePin(pinConfig.mute, true); writePin(pinConfig.power, power); } if (message == 'muteToggle') { mute = !mute; writePin(pinConfig.mute, mute); } }); ws.send('something'); }); function writePin(pinNumber, value) { gpio.setup(pinNumber, gpio.DIR_OUT, write); function write() { this.gpio.write(pinNumber, value, function (err) { if (err) throw err; console.log('Written to pin ' + pinNumber); }); } }
Add image fields to v2/groupRequests response
import _ from 'lodash' import { dbAdapter } from '../../../models' import exceptions from '../../../support/exceptions' export default class GroupsController { static async groupRequests(req, res) { if (!req.user) return res.status(401).jsonp({ err: 'Unauthorized', status: 'fail'}) try { let managedGroups = await req.user.getManagedGroups() let groupsJson = [] let promises = managedGroups.map(async (group)=>{ let groupDescr = _.pick(group, ['id', 'username', 'screenName', 'isPrivate', 'isRestricted']) let unconfirmedFollowerIds = await group.getSubscriptionRequestIds() let unconfirmedFollowers = await dbAdapter.getUsersByIds(unconfirmedFollowerIds) let requests = unconfirmedFollowers.map( async (user)=>{ let request = _.pick(user, ['id', 'username', 'screenName']) request.profilePictureLargeUrl = await user.getProfilePictureLargeUrl() request.profilePictureMediumUrl = await user.getProfilePictureMediumUrl() return request }) groupDescr.requests = await Promise.all(requests) return groupDescr }) groupsJson = await Promise.all(promises) res.jsonp(groupsJson) } catch(e) { exceptions.reportError(res)(e) } } }
import _ from 'lodash' import { dbAdapter } from '../../../models' import exceptions from '../../../support/exceptions' export default class GroupsController { static async groupRequests(req, res) { if (!req.user) return res.status(401).jsonp({ err: 'Unauthorized', status: 'fail'}) try { let managedGroups = await req.user.getManagedGroups() let groupsJson = [] let promises = managedGroups.map(async (group)=>{ let groupDescr = _.pick(group, ['id', 'username', 'screenName', 'isPrivate', 'isRestricted']) let unconfirmedFollowerIds = await group.getSubscriptionRequestIds() let unconfirmedFollowers = await dbAdapter.getUsersByIds(unconfirmedFollowerIds) groupDescr.requests = _.map(unconfirmedFollowers, (user)=>{ return _.pick(user, ['id', 'username', 'screenName']) }) return groupDescr }) groupsJson = await Promise.all(promises) res.jsonp(groupsJson) } catch(e) { exceptions.reportError(res)(e) } } }
Use custom config page hosted on gh-pages. The config page is hosted on the gh-pages branch of this repo. This allows it to be HTTPS, and much lighter than the predecessor.
var UI = require('ui'); var Vibe = require('ui/vibe'); var ajax = require('ajax'); var host; Pebble.addEventListener('showConfiguration', function(e) { // TODO - This only works over HTTP. A much simpler config site can be made and hosted on github pages. Pebble.openURL('https://qubyte.github.io/pebble-presenter/'); }); Pebble.addEventListener('webviewclosed', function(e) { host = JSON.parse(decodeURIComponent(e.response)).host; }); function navigate(by) { if (!host) { return; } ajax( { url: host, method: 'post', type: 'json', data: { by: by } }, function success() { Vibe.vibrate('short'); }, function failure() { Vibe.vibrate('long'); } ); } var main = new UI.Card({ title: 'Simple Presenter', body: 'Press up for forward, down for backward.' }); main.on('click', 'up', function forward() { navigate(1); }); main.on('click', 'down', function backward() { navigate(-1); }); main.show();
var UI = require('ui'); var Vibe = require('ui/vibe'); var ajax = require('ajax'); var host; Pebble.addEventListener('showConfiguration', function(e) { Pebble.openURL('https://pebble-config.herokuapp.com/config?title=Pebble%20Presenter%20Config&fields=host'); }); Pebble.addEventListener('webviewclosed', function(e) { host = JSON.parse(decodeURIComponent(e.response)).host; }); function navigate(by) { if (!host) { return; } ajax( { url: host, method: 'post', type: 'json', data: { by: by } }, function success() { Vibe.vibrate('short'); }, function failure() { Vibe.vibrate('long'); } ); } var main = new UI.Card({ title: 'Simple Presenter', body: 'Press up for forward, down for backward.' }); main.on('click', 'up', function forward() { navigate(1); }); main.on('click', 'down', function backward() { navigate(-1); }); main.show();
Update constants for Laravel 5.2.
<?php namespace App\Http\Middleware; use Illuminate\Http\Request; use Fideloper\Proxy\TrustProxies as Middleware; class TrustProxies extends Middleware { /** * The trusted proxies for this application, * sourced from 'config/trustedproxy.php'. * * @var array */ protected $proxies; /** * The current proxy header mappings. * * @var array */ protected $headers = [ Request::HEADER_FORWARDED => null, // Not set on AWS or Heroku. Request::HEADER_CLIENT_IP => 'X_FORWARDED_FOR', Request::HEADER_CLIENT_HOST => null, // Not set on AWS or Heroku. Request::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO', Request::HEADER_CLIENT_PORT => 'X_FORWARDED_PORT', ]; }
<?php namespace App\Http\Middleware; use Illuminate\Http\Request; use Fideloper\Proxy\TrustProxies as Middleware; class TrustProxies extends Middleware { /** * The trusted proxies for this application, * sourced from 'config/trustedproxy.php'. * * @var array */ protected $proxies; /** * The current proxy header mappings. * * @var array */ protected $headers = [ Request::HEADER_FORWARDED => null, // Not set on AWS or Heroku. Request::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR', Request::HEADER_X_FORWARDED_HOST => null, // Not set on AWS or Heroku. Request::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT', Request::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO', ]; }
Remove unnecessary check in distinct operator
package com.annimon.stream.operator; import com.annimon.stream.iterator.LsaExtIterator; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class ObjDistinct<T> extends LsaExtIterator<T> { private final Iterator<? extends T> iterator; private final Set<T> set; public ObjDistinct(Iterator<? extends T> iterator) { this.iterator = iterator; set = new HashSet<T>(); } @Override protected void nextIteration() { while (hasNext = iterator.hasNext()) { next = iterator.next(); if (set.add(next)) { return; } } } }
package com.annimon.stream.operator; import com.annimon.stream.iterator.LsaExtIterator; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class ObjDistinct<T> extends LsaExtIterator<T> { private final Iterator<? extends T> iterator; private final Set<T> set; public ObjDistinct(Iterator<? extends T> iterator) { this.iterator = iterator; set = new HashSet<T>(); } @Override protected void nextIteration() { while (hasNext = iterator.hasNext()) { next = iterator.next(); if (!set.contains(next)) { set.add(next); return; } } } }
Fix target_id support in JenkinsGenericBuilder
from .builder import JenkinsBuilder class JenkinsGenericBuilder(JenkinsBuilder): def __init__(self, *args, **kwargs): self.script = kwargs.pop('script') self.cluster = kwargs.pop('cluster') super(JenkinsGenericBuilder, self).__init__(*args, **kwargs) def get_job_parameters(self, job, script=None, target_id=None): params = super(JenkinsGenericBuilder, self).get_job_parameters( job, target_id=target_id) if script is None: script = self.script project = job.project repository = project.repository vcs = repository.get_vcs() if vcs: repo_url = vcs.remote_url else: repo_url = repository.url params.extend([ {'name': 'CHANGES_PID', 'value': project.slug}, {'name': 'REPO_URL', 'value': repo_url}, {'name': 'SCRIPT', 'value': script}, {'name': 'REPO_VCS', 'value': repository.backend.name}, {'name': 'CLUSTER', 'value': self.cluster}, ]) return params
from .builder import JenkinsBuilder class JenkinsGenericBuilder(JenkinsBuilder): def __init__(self, *args, **kwargs): self.script = kwargs.pop('script') self.cluster = kwargs.pop('cluster') super(JenkinsGenericBuilder, self).__init__(*args, **kwargs) def get_job_parameters(self, job, script=None): params = super(JenkinsGenericBuilder, self).get_job_parameters(job) if script is None: script = self.script project = job.project repository = project.repository vcs = repository.get_vcs() if vcs: repo_url = vcs.remote_url else: repo_url = repository.url params.extend([ {'name': 'CHANGES_PID', 'value': project.slug}, {'name': 'REPO_URL', 'value': repo_url}, {'name': 'SCRIPT', 'value': script}, {'name': 'REPO_VCS', 'value': repository.backend.name}, {'name': 'CLUSTER', 'value': self.cluster}, ]) return params
Revert "Add the EC2 instance ID to the automatic metadata" This reverts commit 189f0fa7ed0bd4b656e5eb9e3c8db3ad6605e92b.
package agent import ( "errors" "fmt" "time" "github.com/AdRoll/goamz/aws" "github.com/AdRoll/goamz/ec2" ) type EC2Tags struct { } func (e EC2Tags) Get() (map[string]string, error) { tags := make(map[string]string) // Passing blank values here instructs the AWS library to look at the // current instances meta data for the security credentials. auth, err := aws.GetAuth("", "", "", time.Time{}) if err != nil { return tags, errors.New(fmt.Sprintf("Error creating AWS authentication: %s", err.Error())) } // Find the current region and create a new EC2 connection region := aws.GetRegion(aws.InstanceRegion()) ec2Client := ec2.New(auth, region) // Filter by the current machines instance-id filter := ec2.NewFilter() filter.Add("resource-id", aws.InstanceId()) // Describe the tags for the current instance resp, err := ec2Client.DescribeTags(filter) if err != nil { return tags, errors.New(fmt.Sprintf("Error downloading tags: %s", err.Error())) } // Collect the tags for _, tag := range resp.Tags { tags[tag.Key] = tag.Value } return tags, nil }
package agent import ( "errors" "fmt" "time" "github.com/AdRoll/goamz/aws" "github.com/AdRoll/goamz/ec2" ) type EC2Tags struct { } func (e EC2Tags) Get() (map[string]string, error) { tags := make(map[string]string) // Passing blank values here instructs the AWS library to look at the // current instances meta data for the security credentials. auth, err := aws.GetAuth("", "", "", time.Time{}) if err != nil { return tags, errors.New(fmt.Sprintf("Error creating AWS authentication: %s", err.Error())) } // Find the current region and create a new EC2 connection region := aws.GetRegion(aws.InstanceRegion()) ec2Client := ec2.New(auth, region) // Filter by the current machines instance-id filter := ec2.NewFilter() filter.Add("resource-id", aws.InstanceId()) // Describe the tags for the current instance resp, err := ec2Client.DescribeTags(filter) if err != nil { return tags, errors.New(fmt.Sprintf("Error downloading tags: %s", err.Error())) } // Collect the tags for _, tag := range resp.Tags { tags[tag.Key] = tag.Value } // We set this manually, it's not a standard tag tags["aws:instance-id"] = aws.InstanceId() return tags, nil }
Fix (Observation test): change method name
<?php namespace AppBundle\TestsService; use AppBundle\Service\ObservationService; use AppBundle\Entity\Observation; use PHPUnit\Framework\TestCase; use OC\BookingBundle\Service\Utils; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; class ObservationTest extends WebTestCase { protected static $translation; protected static $em; public static function setUpBeforeClass() { $kernel = static::createKernel(); $kernel->boot(); self::$translation = $kernel->getContainer()->get('translator'); self::$em = $kernel->getContainer()->get('doctrine.orm.entity_manager'); } /** * Get last 3 Observations * * @return [type] [description] */ public function testObservations() { $ts = new TokenStorage(); $obs = new ObservationService(self::$em, $ts); $result = $obs->getLastObersations(2); $this->assertCount(2, $result); } }
<?php namespace AppBundle\TestsService; use AppBundle\Service\ObservationService; use AppBundle\Entity\Observation; use PHPUnit\Framework\TestCase; use OC\BookingBundle\Service\Utils; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; class ObservationTest extends WebTestCase { protected static $translation; protected static $em; public static function setUpBeforeClass() { $kernel = static::createKernel(); $kernel->boot(); self::$translation = $kernel->getContainer()->get('translator'); self::$em = $kernel->getContainer()->get('doctrine.orm.entity_manager'); } /** * Get last 3 Observations * * @return [type] [description] */ public function testObservations() { $ts = new TokenStorage(); $obs = new ObservationService(self::$em, $ts); $result = $obs->getLastObersations(2); $this->assertCount(2, $result); } }
Add test expectations to error test
/* * grunt-external-daemon * https://github.com/jlindsey/grunt-external-daemon * * Copyright (c) 2013 Joshua Lindsey * Licensed under the MIT license. */ 'use strict'; var grunt = require('grunt'), exec = require('child_process').exec; exports.missing_cmd = function(test) { test.expect(1); exec('grunt external_daemon:server_4', function(err, stdout, stderr) { var check = stdout.indexOf('Warning: You must specify "cmd" for task server_4'); test.ok((check > -1), 'correct error'); test.done(); }); }; exports.wrong_args = function(test) { test.expect(1); exec('grunt external_daemon:server_4a', function(err, stdout, stderr) { var check = stdout.indexOf('Warning: You must specify "args" as an array for task server_4a'); test.ok((check > -1), 'correct error'); test.done(); }); }; exports.bad_start_check = function(test) { test.expect(1); exec('grunt external_daemon:server_4b', function(err, stdout, stderr) { var check = stdout.indexOf('Warning: You must specify "startCheck" as a function for task server_4b'); test.ok((check > -1), 'correct error'); test.done(); }); };
/* * grunt-external-daemon * https://github.com/jlindsey/grunt-external-daemon * * Copyright (c) 2013 Joshua Lindsey * Licensed under the MIT license. */ 'use strict'; var grunt = require('grunt'), exec = require('child_process').exec; exports.missing_cmd = function(test) { exec('grunt external_daemon:server_4', function(err, stdout, stderr) { var check = stdout.indexOf('Warning: You must specify "cmd" for task server_4'); test.ok((check > -1), 'correct error'); test.done(); }); }; exports.wrong_args = function(test) { exec('grunt external_daemon:server_4a', function(err, stdout, stderr) { var check = stdout.indexOf('Warning: You must specify "args" as an array for task server_4a'); test.ok((check > -1), 'correct error'); test.done(); }); }; exports.bad_start_check = function(test) { exec('grunt external_daemon:server_4b', function(err, stdout, stderr) { var check = stdout.indexOf('Warning: You must specify "startCheck" as a function for task server_4b'); test.ok((check > -1), 'correct error'); test.done(); }); };
Update service provider to use tags for publish
<?php namespace Conner\Tagging\Providers; use Illuminate\Support\ServiceProvider; use Conner\Tagging\Contracts\TaggingUtility; use Conner\Tagging\Util; /** * Copyright (C) 2014 Robert Conner */ class TaggingServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. */ protected $defer = true; /** * Bootstrap the application events. */ public function boot() { $this->publishes([ __DIR__.'/../../config/tagging.php' => config_path('tagging.php') ], 'config'); $this->publishes([ __DIR__.'/../../migrations/' => database_path('migrations') ], 'migrations'); } /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton(TaggingUtility::class, function () { return new Util; }); } /** * (non-PHPdoc) * @see \Illuminate\Support\ServiceProvider::provides() */ public function provides() { return [TaggingUtility::class]; } }
<?php namespace Conner\Tagging\Providers; use Illuminate\Support\ServiceProvider; use Conner\Tagging\Contracts\TaggingUtility; use Conner\Tagging\Util; /** * Copyright (C) 2014 Robert Conner */ class TaggingServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. */ protected $defer = true; /** * Bootstrap the application events. */ public function boot() { $this->publishes([ __DIR__.'/../config/tagging.php' => config_path('tagging.php') ], 'config'); $this->publishes([ __DIR__.'/../migrations/' => database_path('migrations') ], 'migrations'); } /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton(TaggingUtility::class, function () { return new Util; }); } /** * (non-PHPdoc) * @see \Illuminate\Support\ServiceProvider::provides() */ public function provides() { return [TaggingUtility::class]; } }
Make sure to allow copy if only edges are selected
package org.cytoscape.editor.internal; import java.util.List; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNetworkManager; import org.cytoscape.model.CyNode; import org.cytoscape.model.CyTableUtil; import org.cytoscape.task.AbstractNetworkViewTaskFactory; import org.cytoscape.view.model.CyNetworkView; import org.cytoscape.work.TaskIterator; public class CopyTaskFactory extends AbstractNetworkViewTaskFactory { final CyNetworkManager netMgr; final ClipboardManagerImpl clipMgr; public CopyTaskFactory(final ClipboardManagerImpl clipboardMgr, final CyNetworkManager netMgr) { this.netMgr = netMgr; this.clipMgr = clipboardMgr; } @Override public boolean isReady(CyNetworkView networkView) { if (!super.isReady(networkView)) return false; // Make sure we've got something selected List<CyNode> selNodes = CyTableUtil.getNodesInState(networkView.getModel(), CyNetwork.SELECTED, true); if (selNodes != null && selNodes.size() > 0) return true; List<CyEdge> selEdges = CyTableUtil.getEdgesInState(networkView.getModel(), CyNetwork.SELECTED, true); if (selEdges != null && selEdges.size() > 0) return true; return false; } @Override public TaskIterator createTaskIterator(CyNetworkView networkView) { return new TaskIterator(new CopyTask(networkView, clipMgr)); } }
package org.cytoscape.editor.internal; import java.util.List; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNetworkManager; import org.cytoscape.model.CyNode; import org.cytoscape.model.CyTableUtil; import org.cytoscape.task.AbstractNetworkViewTaskFactory; import org.cytoscape.view.model.CyNetworkView; import org.cytoscape.work.TaskIterator; public class CopyTaskFactory extends AbstractNetworkViewTaskFactory { final CyNetworkManager netMgr; final ClipboardManagerImpl clipMgr; public CopyTaskFactory(final ClipboardManagerImpl clipboardMgr, final CyNetworkManager netMgr) { this.netMgr = netMgr; this.clipMgr = clipboardMgr; } @Override public boolean isReady(CyNetworkView networkView) { if (!super.isReady(networkView)) return false; // Make sure we've got something selected List<CyNode> selNodes = CyTableUtil.getNodesInState(networkView.getModel(), CyNetwork.SELECTED, true); if (selNodes != null && selNodes.size() > 0) return true; return false; } @Override public TaskIterator createTaskIterator(CyNetworkView networkView) { return new TaskIterator(new CopyTask(networkView, clipMgr)); } }
Remove "socialsharing_googleplus" from Social Sharing Bundle Signed-off-by: Marius Blüm <38edb439dbcce85f0f597d90d338db16e5438073@lineone.io>
<?php /** * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch> * * @license GNU AGPL version 3 or any later version * * 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/>. * */ namespace Test\App\AppStore\Bundles; use OC\App\AppStore\Bundles\SocialSharingBundle; class SocialSharingBundleTest extends BundleBase { public function setUp() { parent::setUp(); $this->bundle = new SocialSharingBundle($this->l10n); $this->bundleIdentifier = 'SocialSharingBundle'; $this->bundleName = 'Social sharing bundle'; $this->bundleAppIds = [ 'socialsharing_twitter', 'socialsharing_facebook', 'socialsharing_email', 'socialsharing_diaspora', ]; } }
<?php /** * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch> * * @license GNU AGPL version 3 or any later version * * 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/>. * */ namespace Test\App\AppStore\Bundles; use OC\App\AppStore\Bundles\SocialSharingBundle; class SocialSharingBundleTest extends BundleBase { public function setUp() { parent::setUp(); $this->bundle = new SocialSharingBundle($this->l10n); $this->bundleIdentifier = 'SocialSharingBundle'; $this->bundleName = 'Social sharing bundle'; $this->bundleAppIds = [ 'socialsharing_twitter', 'socialsharing_googleplus', 'socialsharing_facebook', 'socialsharing_email', 'socialsharing_diaspora', ]; } }
Test mocking classes with methods returning references
<?php declare(strict_types=1); namespace Moka\Tests; abstract class IncompleteAbstractTestClass implements TestInterface { public $public; protected $protected; private $private; public $isTrue; public static $getInt; public function isTrue(): bool { return true; } public function getInt(): int { return 11; } public function getSelf(): TestInterface { return $this; } public function getCallable(): callable { return function () { }; } public function & getReference(): array { return []; } public function withArgument(int $argument): int { return $argument; } public function withArguments( int $required, $nullable = null, string &$byReference = PHP_EOL, FooTestClass $class = null, array $array = [3], callable $callable = null, ...$variadic ): int { return $required; } public function throwException() { } abstract public function abstractMethod(); }
<?php declare(strict_types=1); namespace Moka\Tests; abstract class IncompleteAbstractTestClass implements TestInterface { public $public; protected $protected; private $private; public $isTrue; public static $getInt; public function isTrue(): bool { return true; } public function getInt(): int { return 11; } public function getSelf(): TestInterface { return $this; } public function getCallable(): callable { return function () { }; } public function withArgument(int $argument): int { return $argument; } public function withArguments( int $required, $nullable = null, string &$byReference = PHP_EOL, FooTestClass $class = null, array $array = [3], callable $callable = null, ...$variadic ): int { return $required; } public function throwException() { } abstract public function abstractMethod(); }
Enable method-level security by annotating the configuration class in *this* project. Works (for now), but not an ideal solution.
package ca.corefacility.bioinformatics.irida.web.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.SessionCreationPolicy; import ca.corefacility.bioinformatics.irida.config.IridaApiSecurityConfig; @Configuration @EnableWebSecurity // DO NOT WANT. For some reason, even though we import the // IridaApiSecurityConfig below (that already has @EnableGlobalMethodSecurity), // we must add the annotation again to this configuration class. That doesn't // allow us to turn method security on in the API project, then use the API // project configuration elsewhere. @EnableGlobalMethodSecurity(prePostEnabled = true) @Import(IridaApiSecurityConfig.class) public class IridaRestApiSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(HttpSecurity http) throws Exception { http.authorizeUrls().anyRequest().fullyAuthenticated().and().httpBasic().and().sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.stateless); } }
package ca.corefacility.bioinformatics.irida.web.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.SessionCreationPolicy; import ca.corefacility.bioinformatics.irida.config.IridaApiSecurityConfig; @Configuration @EnableWebSecurity @Import(IridaApiSecurityConfig.class) public class IridaRestApiSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(HttpSecurity http) throws Exception { http.authorizeUrls().anyRequest().fullyAuthenticated().and().httpBasic().and().sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.stateless); } @Override protected void registerAuthentication(AuthenticationManagerBuilder auth) { auth.parentAuthenticationManager(authenticationManager); } }
Update acceptance test task to work with selenium-standalone v3
var gulp = require('gulp'); var _ = require('lodash'); var Jasmine = require('jasmine'); var selenium = require('selenium-standalone'); // Defines Gulp tasks for running browser acceptance tests. // Takes an array of configuration objects: // [ // { // name: String - Task Name // deps: Array[String] - Tasks to run before executing specs // specs: String | Array[String] - Spec file globs // callback: Function(Boolean) - Called with whether the suite passes // } // ... // ] module.exports = function(acceptanceTasks) { _.each(acceptanceTasks, function(options) { if (_.isString(options.specs)) { options.specs = [options.specs]; } gulp.task(options.name, options.deps, function() { selenium.install(function() { selenium.start(function() { var jasmine = new Jasmine(); jasmine.configureDefaultReporter({ onComplete: options.callback }) jasmine.execute(options.specs); }); }); }); }); };
var gulp = require('gulp'); var _ = require('lodash'); var Jasmine = require('jasmine'); var selenium = require('selenium-standalone'); // Defines Gulp tasks for running browser acceptance tests. // Takes an array of configuration objects: // [ // { // name: String - Task Name // deps: Array[String] - Tasks to run before executing specs // specs: String | Array[String] - Spec file globs // callback: Function(Boolean) - Called with whether the suite passes // } // ... // ] module.exports = function(acceptanceTasks) { _.each(acceptanceTasks, function(options) { if (_.isString(options.specs)) { options.specs = [options.specs]; } gulp.task(options.name, options.deps, function() { selenium(function() { var jasmine = new Jasmine(); jasmine.configureDefaultReporter({ onComplete: options.callback }) jasmine.execute(options.specs); }); }); }); };
[Discord] Update CommandTree.on_error to only take two parameters Remove command parameter, matching discord.py update, and use Interaction.command instead
from discord import app_commands import logging import sys import traceback import sentry_sdk class CommandTree(app_commands.CommandTree): async def on_error(self, interaction, error): sentry_sdk.capture_exception(error) print( f"Ignoring exception in slash command {interaction.command.name}", # TODO: Use full name file = sys.stderr ) traceback.print_exception( type(error), error, error.__traceback__, file = sys.stderr ) logging.getLogger("errors").error( "Uncaught exception\n", exc_info = (type(error), error, error.__traceback__) )
from discord import app_commands import logging import sys import traceback import sentry_sdk class CommandTree(app_commands.CommandTree): async def on_error(self, interaction, command, error): sentry_sdk.capture_exception(error) print( f"Ignoring exception in slash command {command.name}", # TODO: Use full name file = sys.stderr ) traceback.print_exception( type(error), error, error.__traceback__, file = sys.stderr ) logging.getLogger("errors").error( "Uncaught exception\n", exc_info = (type(error), error, error.__traceback__) )
Fix green and yellow being opposites
// Package chalk lets you colour you // terminal string styles package chalk // Black colours your string black func Black(s string) string { return "\033[30m" + s + "\033[0m" } // Red colours your string red func Red(s string) string { return "\033[31m" + s + "\033[0m" } // Green colours your string green func Green(s string) string { return "\033[32m" + s + "\033[0m" } // Yellow colours your string yellow func Yellow(s string) string { return "\033[33m" + s + "\033[0m" } // Blue colours your string blue func Blue(s string) string { return "\033[34m" + s + "\033[0m" } // Magenta colours your string magenta func Magenta(s string) string { return "\033[35m" + s + "\033[0m" } // Cyan colours your string cyan func Cyan(s string) string { return "\033[36m" + s + "\033[0m" } // White colours your string white func White(s string) string { return "\033[37m" + s + "\033[0m" }
// Package chalk lets you colour you // terminal string styles package chalk // Black colours your string black func Black(s string) string { return "\033[30m" + s + "\033[0m" } // Red colours your string red func Red(s string) string { return "\033[31m" + s + "\033[0m" } // Yellow colours your string yellow func Yellow(s string) string { return "\033[32m" + s + "\033[0m" } // Green colours your string green func Green(s string) string { return "\033[33m" + s + "\033[0m" } // Blue colours your string blue func Blue(s string) string { return "\033[34m" + s + "\033[0m" } // Magenta colours your string magenta func Magenta(s string) string { return "\033[35m" + s + "\033[0m" } // Cyan colours your string cyan func Cyan(s string) string { return "\033[36m" + s + "\033[0m" } // White colours your string white func White(s string) string { return "\033[37m" + s + "\033[0m" }
Set a correct controller name
/** * @file Instantiates and configures angular modules for your module. */ define(['angular'], function (ng) { 'use strict'; ng.module('{{template_name}}.controllers', []); ng.module('{{template_name}}.providers', []); ng.module('{{template_name}}.services', []); ng.module('{{template_name}}.factories', []); ng.module('{{template_name}}.directives', []); var module = ng.module('{{template_name}}', [ 'cs_common', '{{template_name}}.controllers', '{{template_name}}.providers', '{{template_name}}.services', '{{template_name}}.factories', '{{template_name}}.directives' ]); module.config([ '$routeProvider', 'CSTemplateProvider', function ($routeProvider, CSTemplate) { // Set the subfolder of your module that contains all your view templates. CSTemplate.setPath('/modules/{{template_name}}/views'); // Register any routes you need for your module. $routeProvider .when('/example', { templateUrl: CSTemplate.view('{{Template}}-view'), controller: '{{Template}}Controller', public: true }); } ]); return module; });
/** * @file Instantiates and configures angular modules for your module. */ define(['angular'], function (ng) { 'use strict'; ng.module('{{template_name}}.controllers', []); ng.module('{{template_name}}.providers', []); ng.module('{{template_name}}.services', []); ng.module('{{template_name}}.factories', []); ng.module('{{template_name}}.directives', []); var module = ng.module('{{template_name}}', [ 'cs_common', '{{template_name}}.controllers', '{{template_name}}.providers', '{{template_name}}.services', '{{template_name}}.factories', '{{template_name}}.directives' ]); module.config([ '$routeProvider', 'CSTemplateProvider', function ($routeProvider, CSTemplate) { // Set the subfolder of your module that contains all your view templates. CSTemplate.setPath('/modules/{{template_name}}/views'); // Register any routes you need for your module. $routeProvider .when('/example', { templateUrl: CSTemplate.view('{{Template}}-view'), controller: '{{Template}}ExampleController', public: true }); } ]); return module; });
Adjust default anti-csrf token ttl to 15 minutes
<?php namespace BNETDocs\Libraries; use \CarlBennett\MVC\Libraries\Common; class CSRF { const TTL = 900; // 15 minutes private function __construct() {} public static function generate($id, $ttl = self::TTL) { $id = (int) $id; $t = microtime(true); $s = mt_rand(); $v = hash("sha256", $t * $s * $id); Common::$cache->set("bnetdocs-csrf-" . $id, $v, $ttl); return $v; } public static function invalidate($id) { $key = "bnetdocs-csrf-" . (int) $id; return Common::$cache->set($key, "", 1); } public static function validate($id, $token) { $key = "bnetdocs-csrf-" . (int) $id; $val = Common::$cache->get($key); if (is_null($val)) return false; return ($val === $token); } }
<?php namespace BNETDocs\Libraries; use \CarlBennett\MVC\Libraries\Common; class CSRF { const TTL = 300; private function __construct() {} public static function generate($id, $ttl = self::TTL) { $id = (int) $id; $t = microtime(true); $s = mt_rand(); $v = hash("sha256", $t * $s * $id); Common::$cache->set("bnetdocs-csrf-" . $id, $v, $ttl); return $v; } public static function invalidate($id) { $key = "bnetdocs-csrf-" . (int) $id; return Common::$cache->set($key, "", 1); } public static function validate($id, $token) { $key = "bnetdocs-csrf-" . (int) $id; $val = Common::$cache->get($key); if (is_null($val)) return false; return ($val === $token); } }
Use GitHub link shortener for comment link This makes the link a bit easier to copy/paste, but more importantly reduces the line width to a more manageable size.
Package.describe({ summary: "JavaScript.next-to-JavaScript-of-today compiler", version: "0.0.42" }); Package._transitional_registerBuildPlugin({ name: "harmony-compiler", use: [], sources: [ "plugin/compiler.js" ], npmDependencies: {"traceur": "0.0.42"} }); Package.on_use(function(api, where) { where = where || ['client', 'server']; // The location of this runtime file is not supposed to change: // http://git.io/B2s0Tg api.add_files(".npm/plugin/harmony-compiler/node_modules/traceur/bin/traceur-runtime.js", where); }); // Package.on_test(function (api) { // api.use(["harmony", "tinytest"]); // api.add_files("tests/test.js", ["client"]); // api.add_files([ // ], ["client", "server"]); // });
Package.describe({ summary: "JavaScript.next-to-JavaScript-of-today compiler", version: "0.0.42" }); Package._transitional_registerBuildPlugin({ name: "harmony-compiler", use: [], sources: [ "plugin/compiler.js" ], npmDependencies: {"traceur": "0.0.42"} }); Package.on_use(function(api, where) { where = where || ['client', 'server']; // The location of this runtime file is not supposed to change: // https://github.com/google/traceur-compiler/commit/49ad82f89c593b12ac0bcdfcfd05028e79676c78 api.add_files(".npm/plugin/harmony-compiler/node_modules/traceur/bin/traceur-runtime.js", where); }); // Package.on_test(function (api) { // api.use(["harmony", "tinytest"]); // api.add_files("tests/test.js", ["client"]); // api.add_files([ // ], ["client", "server"]); // });
Raise Temperature of space stations so snow stops forming everywhere
package zmaster587.advancedRocketry.world.biome; import java.util.LinkedList; import java.util.List; import net.minecraft.entity.EnumCreatureType; import net.minecraft.init.Blocks; import net.minecraft.world.biome.BiomeGenBase; public class BiomeGenSpace extends BiomeGenBase { public BiomeGenSpace(int biomeId, boolean register) { super(biomeId, register); //cold and dry enableRain = false; enableSnow = false; rootHeight=-2f; heightVariation=0.00f; rainfall = 0f; temperature = 1.0f; this.theBiomeDecorator.generateLakes=false; this.theBiomeDecorator.flowersPerChunk=0; this.theBiomeDecorator.grassPerChunk=0; this.theBiomeDecorator.treesPerChunk=0; this.fillerBlock = this.topBlock = Blocks.air; this.biomeName="Space"; } @Override public List getSpawnableList(EnumCreatureType p_76747_1_) { return new LinkedList<>(); } @Override public float getSpawningChance() { return 0f; //Nothing spawns } }
package zmaster587.advancedRocketry.world.biome; import java.util.LinkedList; import java.util.List; import net.minecraft.entity.EnumCreatureType; import net.minecraft.init.Blocks; import net.minecraft.world.biome.BiomeGenBase; public class BiomeGenSpace extends BiomeGenBase { public BiomeGenSpace(int biomeId, boolean register) { super(biomeId, register); //cold and dry enableRain = false; enableSnow = false; rootHeight=-2f; heightVariation=0.00f; rainfall = 0f; temperature = 0.0f; this.theBiomeDecorator.generateLakes=false; this.theBiomeDecorator.flowersPerChunk=0; this.theBiomeDecorator.grassPerChunk=0; this.theBiomeDecorator.treesPerChunk=0; this.fillerBlock = this.topBlock = Blocks.air; this.biomeName="Space"; } @Override public List getSpawnableList(EnumCreatureType p_76747_1_) { return new LinkedList<>(); } @Override public float getSpawningChance() { return 0f; //Nothing spawns } }
Rename function and update description
/** * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var FS_ALIASES = require( './fs_aliases.js' ); // MAIN // /** * Returns a list of argument completion flags for a specified file system API. * * @private * @param {string} alias - alias * @returns {(Array|null)} argument completion flags */ function argFlags( alias ) { var i; for ( i = 0; i < FS_ALIASES.length; i++ ) { if ( FS_ALIASES[ i ][ 0 ] === alias ) { return FS_ALIASES[ i ].slice( 1 ); } } return null; } // EXPORTS // module.exports = argFlags;
/** * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var FS_ALIASES = require( './fs_aliases.js' ); // MAIN // /** * Returns a list of argument types for a specified file system API. * * @private * @param {string} alias - alias * @returns {(Array|null)} argument types */ function argTypes( alias ) { var i; for ( i = 0; i < FS_ALIASES.length; i++ ) { if ( FS_ALIASES[ i ][ 0 ] === alias ) { return FS_ALIASES[ i ].slice( 1 ); } } return null; } // EXPORTS // module.exports = argTypes;
Remove token for absent panel in duplication frontend This should have been omitted from #2704
import mirrorCreator from 'mirror-creator'; export const duplicationModes = mirrorCreator([ 'OBJECT', 'COURSE', ]); // These are mirrored in app/helpers/course/object_duplications_helper.rb export const duplicableItemTypes = mirrorCreator([ 'ASSESSMENT', 'TAB', 'CATEGORY', 'SURVEY', 'ACHIEVEMENT', 'FOLDER', 'MATERIAL', 'VIDEO', 'VIDEO_TAB', ]); // These are mirrored in app/helpers/course/object_duplications_helper.rb export const itemSelectorPanels = mirrorCreator([ 'ASSESSMENTS', 'SURVEYS', 'ACHIEVEMENTS', 'MATERIALS', 'VIDEOS', ]); export const formNames = mirrorCreator([ 'NEW_COURSE', ]); const actionTypes = mirrorCreator([ 'LOAD_OBJECTS_LIST_REQUEST', 'LOAD_OBJECTS_LIST_SUCCESS', 'LOAD_OBJECTS_LIST_FAILURE', 'DUPLICATE_ITEMS_REQUEST', 'DUPLICATE_ITEMS_SUCCESS', 'DUPLICATE_ITEMS_FAILURE', 'DUPLICATE_COURSE_REQUEST', 'DUPLICATE_COURSE_SUCCESS', 'DUPLICATE_COURSE_FAILURE', 'SHOW_DUPLICATE_ITEMS_CONFIRMATION', 'HIDE_DUPLICATE_ITEMS_CONFIRMATION', 'SET_ITEM_SELECTED_BOOLEAN', 'SET_TARGET_COURSE_ID', 'SET_DUPLICATION_MODE', 'SET_ITEM_SELECTOR_PANEL', ]); export default actionTypes;
import mirrorCreator from 'mirror-creator'; export const duplicationModes = mirrorCreator([ 'OBJECT', 'COURSE', ]); // These are mirrored in app/helpers/course/object_duplications_helper.rb export const duplicableItemTypes = mirrorCreator([ 'ASSESSMENT', 'TAB', 'CATEGORY', 'SURVEY', 'ACHIEVEMENT', 'FOLDER', 'MATERIAL', 'VIDEO', 'VIDEO_TAB', ]); // These are mirrored in app/helpers/course/object_duplications_helper.rb export const itemSelectorPanels = mirrorCreator([ 'TARGET_COURSE', 'ASSESSMENTS', 'SURVEYS', 'ACHIEVEMENTS', 'MATERIALS', 'VIDEOS', ]); export const formNames = mirrorCreator([ 'NEW_COURSE', ]); const actionTypes = mirrorCreator([ 'LOAD_OBJECTS_LIST_REQUEST', 'LOAD_OBJECTS_LIST_SUCCESS', 'LOAD_OBJECTS_LIST_FAILURE', 'DUPLICATE_ITEMS_REQUEST', 'DUPLICATE_ITEMS_SUCCESS', 'DUPLICATE_ITEMS_FAILURE', 'DUPLICATE_COURSE_REQUEST', 'DUPLICATE_COURSE_SUCCESS', 'DUPLICATE_COURSE_FAILURE', 'SHOW_DUPLICATE_ITEMS_CONFIRMATION', 'HIDE_DUPLICATE_ITEMS_CONFIRMATION', 'SET_ITEM_SELECTED_BOOLEAN', 'SET_TARGET_COURSE_ID', 'SET_DUPLICATION_MODE', 'SET_ITEM_SELECTOR_PANEL', ]); export default actionTypes;
Fix appRoot for catchall resource.
package com.hubspot.singularity.resources; import javax.inject.Singleton; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.google.inject.Inject; import com.google.inject.name.Named; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.views.IndexView; import static com.hubspot.singularity.SingularityMainModule.SINGULARITY_URI_BASE; @Singleton @Path("/{uiPath:.*}") public class StaticCatchallResource { private final SingularityConfiguration configuration; private final String singularityUriBase; @Inject public StaticCatchallResource(@Named(SINGULARITY_URI_BASE) String singularityUriBase, SingularityConfiguration configuration) { this.configuration = configuration; this.singularityUriBase = singularityUriBase; } @GET @Produces(MediaType.TEXT_HTML) public IndexView getIndex() { return new IndexView(singularityUriBase, "", configuration); } }
package com.hubspot.singularity.resources; import javax.inject.Singleton; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.google.inject.Inject; import com.google.inject.name.Named; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.views.IndexView; import static com.hubspot.singularity.SingularityMainModule.SINGULARITY_URI_BASE; @Singleton @Path("/{uiPath:.*}") public class StaticCatchallResource { private final SingularityConfiguration configuration; private final String singularityUriBase; @Inject public StaticCatchallResource(@Named(SINGULARITY_URI_BASE) String singularityUriBase, SingularityConfiguration configuration) { this.configuration = configuration; this.singularityUriBase = singularityUriBase; } @GET @Produces(MediaType.TEXT_HTML) public IndexView getIndex() { return new IndexView(singularityUriBase, "/", configuration); } }
Address review comment: Just pass through fields we aren't changing.
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ This module defines the Eliot log events emitted by the API implementation. """ __all__ = [ "JSON_REQUEST", "REQUEST", ] from eliot import Field, ActionType LOG_SYSTEM = u"api" METHOD = Field(u"method", lambda method: method, u"The HTTP method of the request.") REQUEST_PATH = Field( u"request_path", lambda path: path, u"The absolute path of the resource to which the request was issued.") JSON = Field.forTypes( u"json", [unicode, bytes, dict, list, None, bool, float], u"JSON, either request or response depending on context.") RESPONSE_CODE = Field.forTypes( u"code", [int], u"The response code for the request.") REQUEST = ActionType( LOG_SYSTEM + u":request", [REQUEST_PATH, METHOD], [], u"A request was received on the public HTTP interface.") JSON_REQUEST = ActionType( LOG_SYSTEM + u":json_request", [JSON], [RESPONSE_CODE, JSON], u"A request containing JSON request and response.")
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ This module defines the Eliot log events emitted by the API implementation. """ __all__ = [ "JSON_REQUEST", "REQUEST", ] from eliot import Field, ActionType LOG_SYSTEM = u"api" METHOD = Field.forTypes( u"method", [unicode, bytes], u"The HTTP method of the request.") REQUEST_PATH = Field.forTypes( u"request_path", [unicode, bytes], u"The absolute path of the resource to which the request was issued.") JSON = Field.forTypes( u"json", [unicode, bytes, dict, list, None, bool, float], u"JSON, either request or response depending on context.") RESPONSE_CODE = Field.forTypes( u"code", [int], u"The response code for the request.") REQUEST = ActionType( LOG_SYSTEM + u":request", [REQUEST_PATH, METHOD], [], u"A request was received on the public HTTP interface.") JSON_REQUEST = ActionType( LOG_SYSTEM + u":json_request", [JSON], [RESPONSE_CODE, JSON], u"A request containing JSON request and response.")
Convert to one step util
'use strict'; var ensureDate = require('es5-ext/date/valid-date') , ensureString = require('es5-ext/object/validate-stringifiable-value') , db = require('../db'); // Convert any date to db.Date in specified time zone. module.exports = function (date, timeZone) { ensureDate(date); timeZone = ensureString(timeZone); try { var res = new Date(date).toLocaleDateString('en', { timeZone: timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).match(/^(\d{2})\/(\d{2})\/(\d{4})$/); if (res) { return new db.Date(res[3], res[1] - 1, res[2]); } } catch (ignore) {} return new db.Date(date); };
'use strict'; var ensureDate = require('es5-ext/date/valid-date') , ensureString = require('es5-ext/object/validate-stringifiable-value') , memoize = require('memoizee/plain') , validDb = require('dbjs/valid-dbjs'); // Convert any date to db.Date in specified time zone. module.exports = memoize(function (db) { validDb(db); return function (date, timeZone) { ensureDate(date); timeZone = ensureString(timeZone); try { var res = new Date(date).toLocaleDateString('en', { timeZone: timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).match(/^(\d{2})\/(\d{2})\/(\d{4})$/); if (res) { return new db.Date(res[3], res[1] - 1, res[2]); } } catch (ignore) {} return new db.Date(date); }; }, { normalizer: require('memoizee/normalizers/get-1')() });
Fix missed raw type ArrayList
package me.nallar.javapatcher.mappings; import java.util.*; /** * Maps method/field/class names in patches to allow obfuscated code to be patched. */ public abstract class Mappings { /** * Takes a list of Class/Method/FieldDescriptions and maps them all using the appropriate map(*Description) * * @param list List of Class/Method/FieldDescriptions * @return Mapped List */ @SuppressWarnings("unchecked") public final <T> List<T> map(List<T> list) { List<T> mappedThings = new ArrayList<T>(); for (Object thing : list) { // TODO - cleaner way of doing this? if (thing instanceof MethodDescription) { mappedThings.add((T) map((MethodDescription) thing)); } else if (thing instanceof ClassDescription) { mappedThings.add((T) map((ClassDescription) thing)); } else if (thing instanceof FieldDescription) { mappedThings.add((T) map((FieldDescription) thing)); } else { throw new IllegalArgumentException("Must be mappable: " + thing + "isn't!"); } } return mappedThings; } public abstract MethodDescription map(MethodDescription methodDescription); public abstract ClassDescription map(ClassDescription classDescription); public abstract FieldDescription map(FieldDescription fieldDescription); public abstract MethodDescription unmap(MethodDescription methodDescription); public abstract String obfuscate(String code); }
package me.nallar.javapatcher.mappings; import java.util.*; /** * Maps method/field/class names in patches to allow obfuscated code to be patched. */ public abstract class Mappings { /** * Takes a list of Class/Method/FieldDescriptions and maps them all using the appropriate map(*Description) * * @param list List of Class/Method/FieldDescriptions * @return Mapped List */ @SuppressWarnings("unchecked") public final <T> List<T> map(List<T> list) { List<T> mappedThings = new ArrayList(); for (Object thing : list) { // TODO - cleaner way of doing this? if (thing instanceof MethodDescription) { mappedThings.add((T) map((MethodDescription) thing)); } else if (thing instanceof ClassDescription) { mappedThings.add((T) map((ClassDescription) thing)); } else if (thing instanceof FieldDescription) { mappedThings.add((T) map((FieldDescription) thing)); } else { throw new IllegalArgumentException("Must be mappable: " + thing + "isn't!"); } } return mappedThings; } public abstract MethodDescription map(MethodDescription methodDescription); public abstract ClassDescription map(ClassDescription classDescription); public abstract FieldDescription map(FieldDescription fieldDescription); public abstract MethodDescription unmap(MethodDescription methodDescription); public abstract String obfuscate(String code); }
Add location field in relation between course and period
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCoursePeriodTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('course_period', function (Blueprint $table) { $table->string('course_id'); $table->unsignedInteger('period_id'); $table->string('location'); $table->timestamps(); $table->primary(['course_id', 'period_id']); $table->foreign('course_id')->references('id')->on('courses') ->onUpdate('cascade')->onDelete('cascade'); $table->foreign('period_id')->references('id')->on('periods') ->onUpdate('cascade')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('course_period'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCoursePeriodTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('course_period', function (Blueprint $table) { $table->string('course_id'); $table->unsignedInteger('period_id'); $table->timestamps(); $table->primary(['course_id', 'period_id']); $table->foreign('course_id')->references('id')->on('courses') ->onUpdate('cascade')->onDelete('cascade'); $table->foreign('period_id')->references('id')->on('periods') ->onUpdate('cascade')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('course_period'); } }
Use hash_type param for pem_finger
# -*- coding: utf-8 -*- ''' Functions to view the minion's public key information ''' from __future__ import absolute_import # Import python libs import os # Import Salt libs import salt.utils def finger(): ''' Return the minion's public key fingerprint CLI Example: .. code-block:: bash salt '*' key.finger ''' # MD5 here is temporary. Change to SHA256 when retired. return salt.utils.pem_finger(os.path.join(__opts__['pki_dir'], 'minion.pub'), sum_type=__opts__.get('hash_type', 'md5')) def finger_master(): ''' Return the fingerprint of the master's public key on the minion. CLI Example: .. code-block:: bash salt '*' key.finger_master ''' # MD5 here is temporary. Change to SHA256 when retired. return salt.utils.pem_finger(os.path.join(__opts__['pki_dir'], 'minion_master.pub'), sum_type=__opts__.get('hash_type', 'md5'))
# -*- coding: utf-8 -*- ''' Functions to view the minion's public key information ''' from __future__ import absolute_import # Import python libs import os # Import Salt libs import salt.utils def finger(): ''' Return the minion's public key fingerprint CLI Example: .. code-block:: bash salt '*' key.finger ''' return salt.utils.pem_finger( os.path.join(__opts__['pki_dir'], 'minion.pub'), sum_type=__opts__['hash_type'] ) def finger_master(): ''' Return the fingerprint of the master's public key on the minion. CLI Example: .. code-block:: bash salt '*' key.finger_master ''' return salt.utils.pem_finger( os.path.join(__opts__['pki_dir'], 'minion_master.pub'), sum_type=__opts__['hash_type'] )
Optimize the common case to reduce startup time.
import sys from process import Process from exit import err_exit class Python(object): """A Python interpreter path that can test itself.""" def __init__(self, defaults, process=None): self.process = process or Process() self.python = defaults.python def __str__(self): return self.python def is_valid_python(self, python=None): version = self.get_python_version(python) if version and version >= '2.6': return True return False def check_valid_python(self, python=None): version = self.get_python_version(python) if not version: err_exit('Bad interpreter') if version < '2.6': err_exit('Python >= 2.6 required') def get_python_version(self, python=None): if python is None: python = self.python if python == sys.executable: return sys.version[:3] version = self.process.pipe( '"%(python)s" -c"import sys; print sys.version[:3]"' % locals()) return version
from process import Process from exit import err_exit class Python(object): """A Python interpreter path that can test itself.""" def __init__(self, defaults, process=None): self.process = process or Process() self.python = defaults.python def __str__(self): return self.python def is_valid_python(self, python=None): version = self.get_python_version(python) if version and version >= '2.6': return True return False def check_valid_python(self, python=None): version = self.get_python_version(python) if not version: err_exit('Bad interpreter') if version < '2.6': err_exit('Python >= 2.6 required') def get_python_version(self, python=None): if python is None: python = self.python version = self.process.pipe( '"%(python)s" -c"import sys; print sys.version[:3]"' % locals()) return version
Fix the ggj route setup
const routeRegex = /^\/(global-game-jam-2021|globalgamejam2021|ggj2021|ggj21)(?:\/.*)?$/; const githubUrl = 'https://levilindsey.github.io/global-game-jam-2021'; // Attaches the route handlers for this app. exports.attachRoutes = (server, appPath, config) => { server.get(routeRegex, handleRequest); // --- --- // // Handles a request for this app. function handleRequest(req, res, next) { // Check whether this request was directed to the portfolio. if (config.portfolioDomains.indexOf(req.hostname) < 0) { next(); return; } const dirs = req.path.split('/'); if (dirs[2] === '' || dirs.length === 2) { res.redirect(githubUrl); } else { next(); } } };
const routeRegex = /^\/(global-game-jam-2021|globalgamejam2021|ggj2021|ggj21)(?:\/.*)?$/; const githubUrl = 'https://levilindsey.github.io/global-game-jam-2021'; // Attaches the route handlers for this app. exports.attachRoutes = (server, appPath, config) => { server.get(routeRegex, handleRequest); // --- --- // // Handles a request for this app. function handleRequest(req, res, next) { // Check whether this request was directed to the games subdomain. if (config.gamesDomains.indexOf(req.hostname) < 0) { next(); return; } const dirs = req.path.split('/'); if (dirs[2] === '' || dirs.length === 2) { res.redirect(githubUrl); } else { next(); } } };
Replace Chrome with Firefox for travis
var webpackConf = require('./webpack.config.js'); module.exports = function(config) { config.set({ files: [ // Each file acts as entry point for the webpack configuration './node_modules/phantomjs-polyfill/bind-polyfill.js', 'test/client/**/*.js' ], frameworks: ['mocha', 'sinon-chai'], preprocessors: { 'test/client/**/*.js': ['webpack'] }, webpack: { module: webpackConf.module }, webpackMiddleware: { noInfo: true }, browsers: ['PhantomJS', 'Firefox'], plugins: [ require('karma-webpack'), require('karma-mocha'), require('karma-sinon-chai'), require('karma-phantomjs-launcher'), require('karma-chrome-launcher'), require('karma-spec-reporter') ], }); };
var webpackConf = require('./webpack.config.js'); module.exports = function(config) { config.set({ files: [ // Each file acts as entry point for the webpack configuration './node_modules/phantomjs-polyfill/bind-polyfill.js', 'test/client/**/*.js' ], frameworks: ['mocha', 'sinon-chai'], preprocessors: { 'test/client/**/*.js': ['webpack'] }, webpack: { module: webpackConf.module }, webpackMiddleware: { noInfo: true }, browsers: ['PhantomJS', 'Chrome'], plugins: [ require('karma-webpack'), require('karma-mocha'), require('karma-sinon-chai'), require('karma-phantomjs-launcher'), require('karma-chrome-launcher'), require('karma-spec-reporter') ], }); };
Revert "fix: so that sync will not always be false"
const isString = val => typeof val === 'string'; const isBlob = val => val instanceof Blob; polyfill.call(typeof window === 'object' ? window : this); function polyfill() { if (isSupported.call(this)) return; if (!('navigator' in this)) this.navigator = {}; this.navigator.sendBeacon = sendBeacon.bind(this); }; function sendBeacon(url, data) { const event = this.event && this.event.type; const sync = event === 'unload' || event === 'beforeunload'; const xhr = ('XMLHttpRequest' in this) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); xhr.open('POST', url, !sync); xhr.withCredentials = true; xhr.setRequestHeader('Accept', '*/*'); if (isString(data)) { xhr.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8'); xhr.responseType = 'text/plain'; } else if (isBlob(data) && data.type) { xhr.setRequestHeader('Content-Type', data.type); } try { xhr.send(data); } catch (error) { return false; } return true; } function isSupported() { return ('navigator' in this) && ('sendBeacon' in this.navigator); }
const isString = val => typeof val === 'string'; const isBlob = val => val instanceof Blob; polyfill.call(typeof window === 'object' ? window : this); function polyfill() { if (isSupported.call(this)) return; if (!('navigator' in this)) this.navigator = {}; this.navigator.sendBeacon = sendBeacon.bind(this); }; function sendBeacon(url, data) { const event = this.event && this.event.type ? this.event.type : this.event; const sync = event === 'unload' || event === 'beforeunload'; const xhr = ('XMLHttpRequest' in this) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); xhr.open('POST', url, !sync); xhr.withCredentials = true; xhr.setRequestHeader('Accept', '*/*'); if (isString(data)) { xhr.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8'); xhr.responseType = 'text/plain'; } else if (isBlob(data) && data.type) { xhr.setRequestHeader('Content-Type', data.type); } try { xhr.send(data); } catch (error) { return false; } return true; } function isSupported() { return ('navigator' in this) && ('sendBeacon' in this.navigator); }
Test that deprecation exceptions are working differently, after suggestion by @embray
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) # test helper.run_tests function import warnings from .. import helper from ... import _get_test_runner from .. helper import pytest # run_tests should raise ValueError when asked to run on a module it can't find def test_module_not_found(): with helper.pytest.raises(ValueError): _get_test_runner().run_tests('fake.module') # run_tests should raise ValueError when passed an invalid pastebin= option def test_pastebin_keyword(): with helper.pytest.raises(ValueError): _get_test_runner().run_tests(pastebin='not_an_option') # tests that tests are only run in Python 3 out of the 2to3'd build (otherwise # a syntax error would occur) try: from .run_after_2to3 import test_run_after_2to3 except SyntaxError: def test_run_after_2to3(): helper.pytest.fail("Not running the 2to3'd tests!") def test_deprecation_warning(): with pytest.raises(DeprecationWarning): warnings.warn('test warning', DeprecationWarning)
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) # test helper.run_tests function import sys from .. import helper from ... import _get_test_runner from .. helper import pytest # run_tests should raise ValueError when asked to run on a module it can't find def test_module_not_found(): with helper.pytest.raises(ValueError): _get_test_runner().run_tests('fake.module') # run_tests should raise ValueError when passed an invalid pastebin= option def test_pastebin_keyword(): with helper.pytest.raises(ValueError): _get_test_runner().run_tests(pastebin='not_an_option') # tests that tests are only run in Python 3 out of the 2to3'd build (otherwise # a syntax error would occur) try: from .run_after_2to3 import test_run_after_2to3 except SyntaxError: def test_run_after_2to3(): helper.pytest.fail("Not running the 2to3'd tests!") def test_deprecation_warning(): if sys.version_info[:2] == (3, 3): with pytest.raises(DeprecationWarning): '{0:s}'.format(object())
Fix tests in python 2.6
from datetime import datetime, date, timedelta import unittest from businesstime.holidays.aus import QueenslandPublicHolidays, BrisbanePublicHolidays class QueenslandPublicHolidaysTest(unittest.TestCase): def test_2016_08(self): holidays_gen = QueenslandPublicHolidays() self.assertEqual( list(holidays_gen(date(2016, 8, 1), end=date(2016, 8, 31))), [] ) class BrisbanePublicHolidaysTest(unittest.TestCase): def test_2016_08(self): holidays_gen = BrisbanePublicHolidays() self.assertEqual( list(holidays_gen(date(2016, 8, 1), end=date(2016, 8, 31))), [ date(2016, 8, 10) ] ) def test_out_of_range(self): holidays_gen = BrisbanePublicHolidays() def test(): return list(holidays_gen(date(2017, 1, 1), end=date(2017, 12, 31))) self.assertRaises(NotImplementedError, test)
from datetime import datetime, date, timedelta import unittest from businesstime.holidays.aus import QueenslandPublicHolidays, BrisbanePublicHolidays class QueenslandPublicHolidaysTest(unittest.TestCase): def test_2016_08(self): holidays_gen = QueenslandPublicHolidays() self.assertEqual( list(holidays_gen(date(2016, 8, 1), end=date(2016, 8, 31))), [] ) class BrisbanePublicHolidaysTest(unittest.TestCase): def test_2016_08(self): holidays_gen = BrisbanePublicHolidays() self.assertEqual( list(holidays_gen(date(2016, 8, 1), end=date(2016, 8, 31))), [ date(2016, 8, 10) ] ) def test_out_of_range(self): holidays_gen = BrisbanePublicHolidays() with self.assertRaises(NotImplementedError): list(holidays_gen(date(2017, 1, 1), end=date(2017, 12, 31)))
Set debug to true for template debugging
from .base import * # Disable debug mode DEBUG = True TEMPLATE_DEBUG = True # Compress static files offline # http://django-compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_OFFLINE COMPRESS_OFFLINE = True # Send notification emails as a background task using Celery, # to prevent this from blocking web server threads # (requires the django-celery package): # http://celery.readthedocs.org/en/latest/configuration.html # import djcelery # # djcelery.setup_loader() # # CELERY_SEND_TASK_ERROR_EMAILS = True # BROKER_URL = 'redis://' EMAIL_SUBJECT_PREFIX = '[b-wise] ' WAGTAILADMIN_NOTIFICATION_FROM_EMAIL = 'no-reply@b-wise.mobi' # Use Redis as the cache backend for extra performance # (requires the django-redis-cache package): # http://wagtail.readthedocs.org/en/latest/howto/performance.html#cache # CACHES = { # 'default': { # 'BACKEND': 'redis_cache.cache.RedisCache', # 'LOCATION': '127.0.0.1:6379', # 'KEY_PREFIX': 'base', # 'OPTIONS': { # 'CLIENT_CLASS': 'redis_cache.client.DefaultClient', # } # } # } try: from .local import * except ImportError: pass
from .base import * # Disable debug mode DEBUG = False TEMPLATE_DEBUG = False # Compress static files offline # http://django-compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_OFFLINE COMPRESS_OFFLINE = True # Send notification emails as a background task using Celery, # to prevent this from blocking web server threads # (requires the django-celery package): # http://celery.readthedocs.org/en/latest/configuration.html # import djcelery # # djcelery.setup_loader() # # CELERY_SEND_TASK_ERROR_EMAILS = True # BROKER_URL = 'redis://' EMAIL_SUBJECT_PREFIX = '[b-wise] ' WAGTAILADMIN_NOTIFICATION_FROM_EMAIL = 'no-reply@b-wise.mobi' # Use Redis as the cache backend for extra performance # (requires the django-redis-cache package): # http://wagtail.readthedocs.org/en/latest/howto/performance.html#cache # CACHES = { # 'default': { # 'BACKEND': 'redis_cache.cache.RedisCache', # 'LOCATION': '127.0.0.1:6379', # 'KEY_PREFIX': 'base', # 'OPTIONS': { # 'CLIENT_CLASS': 'redis_cache.client.DefaultClient', # } # } # } try: from .local import * except ImportError: pass
Add properCase. Use 'for-of' statement in path.
/** Wrap DOM selector methods: * document.querySelector, * document.getElementById, * document.getElementsByClassName] */ const dom = { query(arg) { return document.querySelector(arg); }, id(arg) { return document.getElementById(arg); }, class(arg) { return document.getElementsByClassName(arg); }, }; /** * Returns a (nested) propery from an object, or undefined if it doesn't exist * @param {String | Array} props - An array of properties or a single property * @param {Object | Array} obj */ const path = (props, obj) => { let nested = obj; const properties = typeof props === 'string' ? props.split('.') : props; for (const property of properties) { nested = nested[property]; if (nested === undefined) { return nested; } } return nested; }; /** * Converts a string to proper case (e.g. 'camera' => 'Camera') * @param {String} text * @returns {String} */ const properCase = text => `${text[0].toUpperCase()}${text.slice(1)}`; module.exports = { dom, path, properCase, };
/** Wrap DOM selector methods: * document.querySelector, * document.getElementById, * document.getElementsByClassName] */ const dom = { query(arg) { return document.querySelector(arg); }, id(arg) { return document.getElementById(arg); }, class(arg) { return document.getElementsByClassName(arg); }, }; /** * Returns a (nested) propery from an object, or undefined if it doesn't exist * @param {String | Array} props - An array of properties or a single property * @param {Object | Array} obj */ const path = (props, obj) => { let nested = obj; const properties = typeof props === 'string' ? props.split('.') : props; for (let i = 0; i < properties.length; i++) { nested = nested[properties[i]]; if (nested === undefined) { return nested; } } return nested; }; module.exports = { dom, path, };
Fix the VFG path test.
import angr import logging import os l = logging.getLogger("angr_tests") test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) def test_vfg_paths(): p = angr.Project(os.path.join(test_location, "x86_64/track_user_input")) main_addr = p.loader.main_bin.get_symbol("main").addr printf_addr = 0x4005e1 # actually where it returns vfg = p.analyses.VFG(context_sensitivity_level=1, interfunction_level=5) paths = vfg.get_paths(main_addr, printf_addr) if __name__ == '__main__': test_vfg_paths()
import angr import logging import os l = logging.getLogger("angr_tests") test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) def test_vfg_paths(): p = angr.Project(os.path.join(test_location, "x86_64/track_user_input")) main_addr = p.loader.main_bin.get_symbol("main").addr printf_addr = 0x4005e1 # actually where it returns vfg = p.analyses.VFG(context_sensitivity_level=1, interfunction_level=4) paths = vfg.get_paths(main_addr, printf_addr) if __name__ == '__main__': test_vfg_paths()
Fix GCI Task URL Pattern.
#!/usr/bin/env python2.5 # # Copyright 2011 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module for constructing GCI related URL patterns """ __authors__ = [ '"Lennard de Rijk" <ljvderijk@gmail.com>', '"Selwyn Jacob" <selwynjacob90@gmail.com>', ] from django.conf.urls.defaults import url as django_url from soc.views.helper import url_patterns def url(regex, view, kwargs=None, name=None): """Constructs an url pattern prefixed with ^gci/. Args: see django.conf.urls.defaults.url """ return django_url('^gci/%s' % regex, view, kwargs=kwargs, name=name) TASK = url_patterns.namedIdBasedPattern(['sponsor', 'program'])
#!/usr/bin/env python2.5 # # Copyright 2011 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module for constructing GCI related URL patterns """ __authors__ = [ '"Lennard de Rijk" <ljvderijk@gmail.com>', '"Selwyn Jacob" <selwynjacob90@gmail.com>', ] from django.conf.urls.defaults import url as django_url from soc.views.helper import url_patterns def url(regex, view, kwargs=None, name=None): """Constructs an url pattern prefixed with ^gci/. Args: see django.conf.urls.defaults.url """ return django_url('^gci/%s' % regex, view, kwargs=kwargs, name=name) TASK = url_patterns.namedIdBasedPattern(['sponsor', 'program', 'task'])
Use more specific session cookie name
""" Config parameters for the Flask app itself. Nothing here is user-configurable; all config variables you can set yourself are in config.py. Generally speaking, don't touch this file unless you know what you're doing. """ import config import constants # Flask-SQLAlchemy SQLALCHEMY_DATABASE_URI = 'mysql://{database_user}:{database_password}@{database_host}/{database_name}'.format( database_user=config.DATABASE_USER, database_password=config.DATABASE_PASSWORD, database_host=config.DATABASE_HOST, database_name=config.DATABASE_NAME if config.BUILD_ENVIRONMENT == constants.build_environment.PROD else config.DATABASE_NAME + '_dev', ) SQLALCHEMY_TEST_DATABASE_URI = 'mysql://{database_user}:{database_password}@{database_host}/{database_name}'.format( database_user=config.DATABASE_USER, database_password=config.DATABASE_PASSWORD, database_host=config.DATABASE_HOST, database_name=config.DATABASE_NAME + '_test', ) SQLALCHEMY_TRACK_MODIFICATIONS = False # Flask session cookie name SESSION_COOKIE_NAME = 'modern-paste-session' # Flask session secret key SECRET_KEY = config.FLASK_SECRET_KEY
""" Config parameters for the Flask app itself. Nothing here is user-configurable; all config variables you can set yourself are in config.py. Generally speaking, don't touch this file unless you know what you're doing. """ import config import constants # Flask-SQLAlchemy SQLALCHEMY_DATABASE_URI = 'mysql://{database_user}:{database_password}@{database_host}/{database_name}'.format( database_user=config.DATABASE_USER, database_password=config.DATABASE_PASSWORD, database_host=config.DATABASE_HOST, database_name=config.DATABASE_NAME if config.BUILD_ENVIRONMENT == constants.build_environment.PROD else config.DATABASE_NAME + '_dev', ) SQLALCHEMY_TEST_DATABASE_URI = 'mysql://{database_user}:{database_password}@{database_host}/{database_name}'.format( database_user=config.DATABASE_USER, database_password=config.DATABASE_PASSWORD, database_host=config.DATABASE_HOST, database_name=config.DATABASE_NAME + '_test', ) SQLALCHEMY_TRACK_MODIFICATIONS = False # Flask session secret key SECRET_KEY = config.FLASK_SECRET_KEY
Change highest color to orange
/*eslint-env browser*/ /*eslint no-use-before-define:0 */ /*global $*/ (function(){ "use strict"; $(document).ready(function(){ setInterval(updatePage, 100); }); function updatePage(){ $.getJSON("./state.json", updateImage); } function updateLights(data){ $.each(data, function(index, value){ document.getElementById(value.location + "2" + value.direction).style.fill = value.state; document.getElementById(value.location + "2" + value.direction + "-load").innerHTML = value.load; }); } function updateImage(data){ updateLights(data); colorHighest(data); createStatistics(data); } function createStatistics(data){ var totalCars = Array.reduce(data, function(total, current){ return current.load + total;}, 0); document.getElementById("totalCars").innerHTML = totalCars; } function colorHighest(data){ var carCounts = $.map(data, function(d){return d.load}); var highestCarCount = Array.max(carCounts); $.each(data, function(index, value){ var color = value.load === highestCarCount ? "orange": "black"; document.getElementById(value.location + "2" + value.direction + "-load").style.fill = color; }); } Array.max = function( array ){ return Math.max.apply( Math, array ); }; })();
/*eslint-env browser*/ /*eslint no-use-before-define:0 */ /*global $*/ (function(){ "use strict"; $(document).ready(function(){ setInterval(updatePage, 100); }); function updatePage(){ $.getJSON("./state.json", updateImage); } function updateLights(data){ $.each(data, function(index, value){ document.getElementById(value.location + "2" + value.direction).style.fill = value.state; document.getElementById(value.location + "2" + value.direction + "-load").innerHTML = value.load; }); } function updateImage(data){ updateLights(data); colorHighest(data); createStatistics(data); } function createStatistics(data){ var totalCars = Array.reduce(data, function(total, current){ return current.load + total;}, 0); document.getElementById("totalCars").innerHTML = totalCars; } function colorHighest(data){ var carCounts = $.map(data, function(d){return d.load}); var highestCarCount = Array.max(carCounts); $.each(data, function(index, value){ var color = value.load === highestCarCount ? "yellow": "black"; document.getElementById(value.location + "2" + value.direction + "-load").style.fill = color; }); } Array.max = function( array ){ return Math.max.apply( Math, array ); }; })();
fix(Spellchecker): Fix disabling spellchecker after app start
import { autorun, observable } from 'mobx'; import { DEFAULT_FEATURES_CONFIG } from '../../config'; const debug = require('debug')('Franz:feature:spellchecker'); export const config = observable({ isIncludedInCurrentPlan: DEFAULT_FEATURES_CONFIG.isSpellcheckerIncludedInCurrentPlan, }); export default function init(stores) { debug('Initializing `spellchecker` feature'); autorun(() => { const { isSpellcheckerIncludedInCurrentPlan } = stores.features.features; config.isIncludedInCurrentPlan = isSpellcheckerIncludedInCurrentPlan !== undefined ? isSpellcheckerIncludedInCurrentPlan : DEFAULT_FEATURES_CONFIG.isSpellcheckerIncludedInCurrentPlan; if (!stores.user.data.isPremium && !config.isIncludedInCurrentPlan && stores.settings.app.enableSpellchecking) { debug('Override settings.spellcheckerEnabled flag to false'); Object.assign(stores.settings.app, { enableSpellchecking: false, }); } }); }
import { autorun, observable } from 'mobx'; import { DEFAULT_FEATURES_CONFIG } from '../../config'; const debug = require('debug')('Franz:feature:spellchecker'); export const config = observable({ isIncludedInCurrentPlan: DEFAULT_FEATURES_CONFIG.isSpellcheckerIncludedInCurrentPlan, }); export default function init(stores) { debug('Initializing `spellchecker` feature'); autorun(() => { const { isSpellcheckerIncludedInCurrentPlan } = stores.features.features; config.isIncludedInCurrentPlan = isSpellcheckerIncludedInCurrentPlan !== undefined ? isSpellcheckerIncludedInCurrentPlan : DEFAULT_FEATURES_CONFIG.isSpellcheckerIncludedInCurrentPlan; if (!stores.user.data.isPremium && config.isIncludedInCurrentPlan && stores.settings.app.enableSpellchecking) { debug('Override settings.spellcheckerEnabled flag to false'); Object.assign(stores.settings.app, { enableSpellchecking: false, }); } }); }