text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update support for Meteor 1.2
// package metadata file for Meteor.js /* jshint strict:false */ /* global Package:true */ Package.describe({ name: 'twbs:bootstrap', // http://atmospherejs.com/twbs/bootstrap summary: 'The most popular front-end framework for developing responsive, mobile first projects on the web.', version: '3.3.5', git: 'https://github.com/twbs/bootstrap.git' }); Package.onUse(function (api) { api.versionsFrom('METEOR@1.0'); api.use('jquery', 'client'); var assets = [ 'dist/fonts/glyphicons-halflings-regular.eot', 'dist/fonts/glyphicons-halflings-regular.svg', 'dist/fonts/glyphicons-halflings-regular.ttf', 'dist/fonts/glyphicons-halflings-regular.woff', 'dist/fonts/glyphicons-halflings-regular.woff2' ]; if (api.addAssets) { api.addAssets(assets, 'client'); } else { api.addFiles(assets, 'client', { isAsset: true }); } api.addFiles([ 'dist/css/bootstrap.css', 'dist/js/bootstrap.js' ], 'client'); });
// package metadata file for Meteor.js /* jshint strict:false */ /* global Package:true */ Package.describe({ name: 'twbs:bootstrap', // http://atmospherejs.com/twbs/bootstrap summary: 'The most popular front-end framework for developing responsive, mobile first projects on the web.', version: '3.3.5', git: 'https://github.com/twbs/bootstrap.git' }); Package.onUse(function (api) { api.versionsFrom('METEOR@1.0'); api.use('jquery', 'client'); api.addFiles([ 'dist/fonts/glyphicons-halflings-regular.eot', 'dist/fonts/glyphicons-halflings-regular.svg', 'dist/fonts/glyphicons-halflings-regular.ttf', 'dist/fonts/glyphicons-halflings-regular.woff', 'dist/fonts/glyphicons-halflings-regular.woff2' ], 'client', { isAsset: true }); api.addFiles([ 'dist/css/bootstrap.css', 'dist/js/bootstrap.js' ], 'client'); });
Fix some code idiocies that lambdagrrl found.
module.exports = function(RED) { "use strict"; function Fifo(config) { RED.nodes.createNode(this,config); this.queue = []; this.depth = config.depth; this.status({fill:"red",shape:"ring",text:"no value"}); this.on('input', function (msg) { // are we full? // if so, boot some out if (this.queue.length >= this.depth) { while (this.queue.length >= this.depth) { var outgoing = this.queue.shift(); this.send(outgoing); } } // clone the message and whack it in the queue this.queue.push(msg); if (this.queue.length == this.depth) { // queue is full this.status({fill: "green", shape: "dot", text: this.queue.length + "/" + this.depth + " msgs"}); } else { // queue is partially full this.status({fill: "green", shape: "ring", text: this.queue.length + "/" + this.depth + " msgs"}); } }); this.on("close", function() { }); } RED.nodes.registerType("fifo",Fifo); }
module.exports = function(RED) { "use strict"; function Fifo(config) { RED.nodes.createNode(this,config); var me = this; this.queue = []; this.depth = config.depth; this.status({fill:"red",shape:"ring",text:"no value"}); this.on('input', function (msg) { // are we full? // if so, boot some out if (this.queue.length >= this.depth) { while (this.queue.length >= this.depth) { var msg = this.queue.shift(); this.send(msg); } } // clone the message and whack it in the queue this.queue.push(msg); if (this.queue.length == this.depth) { // queue is full this.status({fill: "green", shape: "dot", text: this.queue.length + "/" + this.depth + " msgs"}); } else { // queue is partially full this.status({fill: "green", shape: "ring", text: this.queue.length + "/" + this.depth + " msgs"}); } }); this.on("close", function() { }); } RED.nodes.registerType("fifo",Fifo); }
Set cross origin tag for html5 embeds
/* global videojs */ import React from 'react' import { webcastPropType } from '../../utils/webcastUtils' export default class EmbedHtml5 extends React.Component { static propTypes = { webcast: webcastPropType.isRequired, } componentDidMount() { videojs(this.props.webcast.id, { width: '100%', height: '100%', autoplay: true, }) } render() { return ( <video controls crossorigin="anonymous" id={this.props.webcast.id} className="video-js vjs-default-skin" > <source src={this.props.webcast.channel} type="application/x-mpegurl" /> </video> ) } }
/* global videojs */ import React from 'react' import { webcastPropType } from '../../utils/webcastUtils' export default class EmbedHtml5 extends React.Component { static propTypes = { webcast: webcastPropType.isRequired, } componentDidMount() { videojs(this.props.webcast.id, { width: '100%', height: '100%', autoplay: true, }) } render() { return ( <video controls id={this.props.webcast.id} className="video-js vjs-default-skin" > <source src={this.props.webcast.channel} type="application/x-mpegurl" /> </video> ) } }
Fix search index regeneration initializing Sonic client incorrectly
<?php /** * This file is covered by the AGPLv3 license, which can be found at the LICENSE file in the root of this project. * @copyright 2020 subtitulamos.tv */ namespace App\Commands; use App\Services\Sonic; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class RegenerateSearchIndex extends Command { protected function configure() { $this->setName('app:search:regenerate-index') ->setDescription('Renegerate the search index for all shows') ->setHelp('Renegerate the search index for all shows'); } protected function execute(InputInterface $input, OutputInterface $output) { global $entityManager; $shows = $entityManager->getRepository('App:Show')->findAll(); $ingest = Sonic::getIngestClient(); foreach ($shows as $show) { $ingest->push(Sonic::SHOW_NAME_COLLECTION, 'default', $show->getId(), $show->getName()); } $ingest->disconnect(); $output->writeln(count($shows)." shows sync'd to search engine"); } }
<?php /** * This file is covered by the AGPLv3 license, which can be found at the LICENSE file in the root of this project. * @copyright 2020 subtitulamos.tv */ namespace App\Commands; use App\Services\Sonic; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class RegenerateSearchIndex extends Command { protected function configure() { $this->setName('app:search:regenerate-index') ->setDescription('Renegerate the search index for all shows') ->setHelp('Renegerate the search index for all shows'); } protected function execute(InputInterface $input, OutputInterface $output) { global $entityManager; $shows = $entityManager->getRepository('App:Show')->findAll(); foreach ($shows as $show) { $ingest = Sonic::getIngestClient(); $ingest->push(Sonic::SHOW_NAME_COLLECTION, 'default', $show->getId(), $show->getName()); } $ingest->disconnect(); $output->writeln(count($shows)." shows sync'd to search engine"); } }
Remove title attribute from Bootstrap Select buttons.
ManageIQ.angular.app.directive('selectpickerForSelectTag', function() { return { require: 'ngModel', link: function (scope, elem, attr, ctrl) { scope['form_' + ctrl.$name] = elem[0]; scope.$watch(attr.ngModel, function() { if((ctrl.$modelValue != undefined)) { $(scope['form_' + ctrl.$name]).selectpicker({ dropupAuto: false }); $(scope['form_' + ctrl.$name]).selectpicker('show'); $(scope['form_' + ctrl.$name]).selectpicker('refresh'); $(scope['form_' + ctrl.$name]).addClass('span12').selectpicker('setStyle'); } }); scope.$watch('loaded.bs.select', function() { $('.bootstrap-select button').removeAttr('title'); }); } } });
ManageIQ.angular.app.directive('selectpickerForSelectTag', function() { return { require: 'ngModel', link: function (scope, elem, attr, ctrl) { scope['form_' + ctrl.$name] = elem[0]; scope.$watch(attr.ngModel, function() { if((ctrl.$modelValue != undefined)) { $(scope['form_' + ctrl.$name]).selectpicker({ dropupAuto: false }); $(scope['form_' + ctrl.$name]).selectpicker('show'); $(scope['form_' + ctrl.$name]).selectpicker('refresh'); $(scope['form_' + ctrl.$name]).addClass('span12').selectpicker('setStyle'); } }); } } });
Add object-assign plugin to karma
var webpack = require('webpack'); module.exports = function (config) { config.set({ browserNoActivityTimeout: 30000, browsers: [ process.env.CONTINUOUS_INTEGRATION ? 'Firefox' : 'Chrome' ], singleRun: process.env.CONTINUOUS_INTEGRATION === 'true', frameworks: [ 'mocha' ], files: [ 'tests.webpack.js' ], preprocessors: { 'tests.webpack.js': [ 'webpack', 'sourcemap' ] }, reporters: [ 'dots' ], webpack: { devtool: 'inline-source-map', module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel?optional=es7.classProperties&plugins=object-assign' } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('test') }) ] }, webpackServer: { noInfo: true } }); };
var webpack = require('webpack'); module.exports = function (config) { config.set({ browserNoActivityTimeout: 30000, browsers: [ process.env.CONTINUOUS_INTEGRATION ? 'Firefox' : 'Chrome' ], singleRun: process.env.CONTINUOUS_INTEGRATION === 'true', frameworks: [ 'mocha' ], files: [ 'tests.webpack.js' ], preprocessors: { 'tests.webpack.js': [ 'webpack', 'sourcemap' ] }, reporters: [ 'dots' ], webpack: { devtool: 'inline-source-map', module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?optional=es7.classProperties' } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('test') }) ] }, webpackServer: { noInfo: true } }); };
Increase initial scrollback to 40 messages.
Hummingbird.ChatRoute = Ember.Route.extend({ pingInterval: null, model: function() { return []; }, afterModel: function() { Hummingbird.TitleManager.setTitle("Chat"); }, ping: function() { var self = this; return ic.ajax({ url: "/chat/ping", type: 'POST' }).then(function(pingResponse) { self.set('controller.onlineUsers', pingResponse.online_users); return pingResponse; }); }, activate: function() { //Notification.requestPermission(); var self = this; self.ping().then(function(pingResponse) { var lastId = pingResponse.last_message_id - 40; if (lastId < 0) lastId = 0; MessageBus.subscribe("/chat/lobby", function(message) { self.get('controller').send("recvMessage", message); }, lastId); }); self.set('pingInterval', setInterval(self.ping.bind(self), 20000)); }, deactivate: function() { MessageBus.unsubscribe("/chat"); if (this.get('pingInterval')) { clearInterval(this.get('pingInterval')); this.set('pingInterval', null); } } });
Hummingbird.ChatRoute = Ember.Route.extend({ pingInterval: null, model: function() { return []; }, afterModel: function() { Hummingbird.TitleManager.setTitle("Chat"); }, ping: function() { var self = this; return ic.ajax({ url: "/chat/ping", type: 'POST' }).then(function(pingResponse) { self.set('controller.onlineUsers', pingResponse.online_users); return pingResponse; }); }, activate: function() { //Notification.requestPermission(); var self = this; self.ping().then(function(pingResponse) { var lastId = pingResponse.last_message_id - 20; if (lastId < 0) lastId = 0; MessageBus.subscribe("/chat/lobby", function(message) { self.get('controller').send("recvMessage", message); }, lastId); }); self.set('pingInterval', setInterval(self.ping.bind(self), 20000)); }, deactivate: function() { MessageBus.unsubscribe("/chat"); if (this.get('pingInterval')) { clearInterval(this.get('pingInterval')); this.set('pingInterval', null); } } });
Tweak email address pattern and define the string as a constant.
/* * Copyright (C) 2011 Archie L. Cobbs. All rights reserved. * * $Id$ */ package org.dellroad.stuff.validation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; import javax.validation.ReportAsSingleViolation; import javax.validation.constraints.Pattern; /** * Validation constraint requiring a {@link String} to be a valid email address. */ @Documented @Constraint(validatedBy = {}) @Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Pattern(regexp = EmailAddress.PATTERN) @ReportAsSingleViolation public @interface EmailAddress { /** * The regular expression string used by this constraint to validate email addresses: {@value} */ String PATTERN = "^[-+%._\\p{Alnum}]+@([-\\p{Alnum}]+\\.)+[-\\p{Alnum}]+$"; String message() default "Invalid email address"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
/* * Copyright (C) 2011 Archie L. Cobbs. All rights reserved. * * $Id$ */ package org.dellroad.stuff.validation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; import javax.validation.ReportAsSingleViolation; import javax.validation.constraints.Pattern; /** * Validation constraint requiring a {@link String} to be a valid email address. */ @Documented @Constraint(validatedBy = {}) @Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Pattern(regexp = "^[-+._\\p{Alnum}]+@[-\\p{Alnum}]+(\\.[-.\\p{Alnum}]+)+$") @ReportAsSingleViolation public @interface EmailAddress { String message() default "Invalid email address"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
Correct the expected number of tests
const test = require('tape') const BorrowState = require('borrow-state') const sleep50ms = (something) => new Promise(function (resolve, reject) { setTimeout(function () { resolve(something) }, 50) }) ;[true, false].forEach((unsafe) => { test(`read-only-parallel (${unsafe ? 'un' : ''}safe)`, (t) => { t.plan(3) t.timeoutAfter(100) let myState = new BorrowState() ;[1, 2, 3].forEach(() => { myState.block('r') .then(sleep50ms) .then((state) => { t.ok(true) state.unblock() }) }) }) })
const test = require('tape') const BorrowState = require('borrow-state') const sleep50ms = (something) => new Promise(function (resolve, reject) { setTimeout(function () { resolve(something) }, 50) }) ;[true, false].forEach((unsafe) => { test(`read-only-parallel (${unsafe ? 'un' : ''}safe)`, (t) => { t.plan(6) t.timeoutAfter(100) let myState = new BorrowState() ;[1, 2, 3].forEach(() => { myState.block('r') .then(sleep50ms) .then((state) => { t.ok(true) state.unblock() }) }) }) })
Use pandoc to convert the markdown readme to rst.
from distutils.core import setup from sh import pandoc setup( name='cardscript', version='0.6', description="A scriptable card game processing engine.", author="Charles Nelson", author_email="cnelsonsic@gmail.com", url="https://github.com/cnelsonsic/cardscript", packages=['cardscript', 'cardscript.cards'], license='AGPLv3+', long_description='\n'.join(pandoc('README.md', t='rst')), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Games/Entertainment :: Board Games', ], )
from distutils.core import setup setup( name='cardscript', version='0.6', description="A scriptable card game processing engine.", author="Charles Nelson", author_email="cnelsonsic@gmail.com", url="https://github.com/cnelsonsic/cardscript", packages=['cardscript', 'cardscript.cards'], license='AGPLv3+', long_description=open('README.md').read(), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Games/Entertainment :: Board Games', ], )
Check for empty string insertion as well - Fixes #21
/* * Copyright (c) 2014 Snowplow Analytics Ltd. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package com.snowplowanalytics.snowplow.tracker; public class LinkedHashMap<K,V> extends java.util.LinkedHashMap<K, V> { @Override public V put(K key, V value) { if(value != null && value != "") return super.put(key, value); else return null; } }
/* * Copyright (c) 2014 Snowplow Analytics Ltd. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package com.snowplowanalytics.snowplow.tracker; public class LinkedHashMap<K,V> extends java.util.LinkedHashMap<K, V> { @Override public V put(K key, V value) { if(value != null) return super.put(key, value); else return null; } }
Change Scatter Plot to Scatterplot in default title
Settings = { chart: { padding: { right: 40, bottom: 100 }, margins: { top: 30, bottom: 0, right: 35 }, dots: { size: 5, color: '#378E00', opacity: 0.7 } }, defaultData: { title: 'Scatterplot', byYear: false, chosenYear: '', x: { indicator: 'ipr', // Percentage of individuals using the Internet log: false, jitter: 0.0 }, y: { indicator: 'downloadkbps', // Average download speed (kbps) log: false, jitter: 0.0 } } }; IMonScatterWidget = function(doc) { Widget.call(this, doc); _.defaults(this.data, Settings.defaultData); }; IMonScatterWidget.prototype = Object.create(Widget.prototype); IMonScatterWidget.prototype.constructor = IMonScatterWidget; IMonScatter = { widget: { name: 'Scatterplot', description: 'Shows a scatterplot of two chosen metrics from the Internet Monitor dataset across all countries', url: 'https://thenetmonitor.org/sources', dimensions: { width: 3, height: 2 }, resize: { mode: 'cover' }, constructor: IMonScatterWidget, typeIcon: 'line-chart' }, org: { name: 'Internet Monitor', shortName: 'IM', url: 'http://thenetmonitor.org' } };
Settings = { chart: { padding: { right: 40, bottom: 100 }, margins: { top: 30, bottom: 0, right: 35 }, dots: { size: 5, color: '#378E00', opacity: 0.7 } }, defaultData: { title: 'Scatter Plot', byYear: false, chosenYear: '', x: { indicator: 'ipr', // Percentage of individuals using the Internet log: false, jitter: 0.0 }, y: { indicator: 'downloadkbps', // Average download speed (kbps) log: false, jitter: 0.0 } } }; IMonScatterWidget = function(doc) { Widget.call(this, doc); _.defaults(this.data, Settings.defaultData); }; IMonScatterWidget.prototype = Object.create(Widget.prototype); IMonScatterWidget.prototype.constructor = IMonScatterWidget; IMonScatter = { widget: { name: 'Scatterplot', description: 'Shows a scatterplot of two chosen metrics from the Internet Monitor dataset across all countries', url: 'https://thenetmonitor.org/sources', dimensions: { width: 3, height: 2 }, resize: { mode: 'cover' }, constructor: IMonScatterWidget, typeIcon: 'line-chart' }, org: { name: 'Internet Monitor', shortName: 'IM', url: 'http://thenetmonitor.org' } };
Update webpack copy plugin configuration
const path = require('path'); const webpack = require('webpack'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: { app: './src/app/app.js' }, module: { rules: [ { test: /\.html$/, use: 'raw-loader' } ] }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: './src/index.html', inject: 'head' }), new CopyWebpackPlugin({patterns: [ { from: './src/assets/', to: 'assets/' }, { from: './src/styles/', to: 'styles/' }, { from: './src/app/lib/stockfish.js', to: 'lib/stockfish.js' } ]}) ], output: { filename: 'app.js', path: path.resolve(__dirname, 'dist') }, };
const path = require('path'); const webpack = require('webpack'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: { app: './src/app/app.js' }, module: { rules: [ { test: /\.html$/, use: 'raw-loader' } ] }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: './src/index.html', inject: 'head' }), new CopyWebpackPlugin([ { from: './src/assets/', to: 'assets/' }, { from: './src/styles/', to: 'styles/' }, { from: './src/app/lib/stockfish.js', to: 'lib/stockfish.js' } ]) ], output: { filename: 'app.js', path: path.resolve(__dirname, 'dist') }, };
Remove attributes instead of setting a false value like [].
from eduid_am.exceptions import UserDoesNotExist WHITELIST_SET_ATTRS = ( 'givenName', 'sn', 'displayName', 'photo', 'preferredLanguage', 'mail', 'date', # last modification # TODO: Arrays must use put or pop, not set, but need more deep refacts 'norEduPersonNIN', 'eduPersonEntitlement', 'mobile', 'mailAliases', 'postalAddress', 'passwords', ) def attribute_fetcher(db, user_id): attributes = {} user = db.profiles.find_one({'_id': user_id}) if user is None: raise UserDoesNotExist("No user matching _id='%s'" % user_id) # white list of valid attributes for security reasons attributes_set = {} attributes_unset = {} for attr in WHITELIST_SET_ATTRS: value = user.get(attr, None) if value: attributes_set[attr] = value else: attributes_unset[attr] = value attributes['$set'] = attributes_set attributes['$unset'] = attributes_unset return attributes
from eduid_am.exceptions import UserDoesNotExist WHITELIST_SET_ATTRS = ( 'givenName', 'sn', 'displayName', 'photo', 'preferredLanguage', 'mail', 'date', # last modification # TODO: Arrays must use put or pop, not set, but need more deep refacts 'norEduPersonNIN', 'eduPersonEntitlement', 'mobile', 'mailAliases', 'postalAddress', 'passwords', ) def attribute_fetcher(db, user_id): attributes = {} user = db.profiles.find_one({'_id': user_id}) if user is None: raise UserDoesNotExist("No user matching _id='%s'" % user_id) # white list of valid attributes for security reasons attributes_set = {} for attr in WHITELIST_SET_ATTRS: value = user.get(attr, None) if value is not None: attributes_set[attr] = value attributes['$set'] = attributes_set return attributes
Add test to get device with non-existant key
from pml.exceptions import PvException import pml.device import pytest import mock @pytest.fixture def create_device(readback, setpoint): _rb = readback _sp = setpoint device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock()) return device def test_set_device_value(): rb_pv = 'SR01A-PC-SQUAD-01:I' sp_pv = 'SR01A-PC-SQUAD-01:SETI' device1 = create_device(rb_pv, sp_pv) device1.put_value(40) device1._cs.put.assert_called_with(sp_pv, 40) device2 = create_device(rb_pv, None) with pytest.raises(PvException): device2.put_value(40) def test_get_device_value(): sp_pv = 'SR01A-PC-SQUAD-01:SETI' device = create_device(None, sp_pv) with pytest.raises(PvException): device.get_value('non_existant') with pytest.raises(PvException): create_device(None, None)
from pml.exceptions import PvException import pml.device import pytest import mock @pytest.fixture def create_device(readback, setpoint): _rb = readback _sp = setpoint device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock()) return device def test_set_device_value(): rb_pv = 'SR01A-PC-SQUAD-01:I' sp_pv = 'SR01A-PC-SQUAD-01:SETI' device1 = create_device(rb_pv, sp_pv) device1.put_value(40) device1._cs.put.assert_called_with(sp_pv, 40) device2 = create_device(rb_pv, None) with pytest.raises(PvException): device2.put_value(40) def test_get_device_value(): sp_pv = 'SR01A-PC-SQUAD-01:SETI' device = create_device(None, sp_pv) with pytest.raises(PvException): device.get_value('non_existant') with pytest.raises(PvException): create_device(None, None)
Add export to use as module
// https://www.codewars.com/kata/death-by-coffee/javascript const coffeeLimits = function(y,m,d) { let healthNumber = y * 10000 + m * 100 + d; let currentHex; let current; let i; let result = [0,0]; for(i=1;i<=5000;i++){ current = healthNumber + i * 0xcafe; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[0]=i; break; } } for(i=1;i<=5000;i++){ current = healthNumber + i * 0xdecaf; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[1]=i; break; } } return result; } export { coffeeLimits };
// https://www.codewars.com/kata/death-by-coffee/javascript const coffeeLimits = function(y,m,d) { let healthNumber = y * 10000 + m * 100 + d; let currentHex; let current; let i; let result = [0,0]; for(i=1;i<=5000;i++){ current = healthNumber + i * 0xcafe; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[0]=i; break; } } for(i=1;i<=5000;i++){ current = healthNumber + i * 0xdecaf; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[1]=i; break; } } return result; }
Fix rhybcpStatuses in the get response
package com.servinglynk.hmis.warehouse.core.model; import java.util.ArrayList; import java.util.List; import com.servinglynk.hmis.warehouse.PaginatedModel; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("rhybcpStatuses") public class Rhybcpstatuses extends PaginatedModel{ @JsonProperty("rhybcpStatuses") List<Rhybcpstatus>rhybcpstatuses = new ArrayList<Rhybcpstatus>(); public List<Rhybcpstatus> getRhybcpstatuses() { return rhybcpstatuses; } public void setRhybcpstatuses(List<Rhybcpstatus> rhybcpstatuses) { this.rhybcpstatuses = rhybcpstatuses; } public void addRhybcpstatus(Rhybcpstatus rhybcpstatus) { this.rhybcpstatuses.add(rhybcpstatus); } }
package com.servinglynk.hmis.warehouse.core.model; import java.util.ArrayList; import java.util.List; import com.servinglynk.hmis.warehouse.PaginatedModel; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("rhybcpStatuses") public class Rhybcpstatuses extends PaginatedModel{ @JsonProperty("rhybcpstatuses") List<Rhybcpstatus>rhybcpstatuses = new ArrayList<Rhybcpstatus>(); public List<Rhybcpstatus> getRhybcpstatuses() { return rhybcpstatuses; } public void setRhybcpstatuses(List<Rhybcpstatus> rhybcpstatuses) { this.rhybcpstatuses = rhybcpstatuses; } public void addRhybcpstatus(Rhybcpstatus rhybcpstatus) { this.rhybcpstatuses.add(rhybcpstatus); } }
Fix setting of StepPhase in the Retry action Change-Id: I92b5f1d6892dab5659eccdc15ab46aaa60986da7
package com.sap.cloud.lm.sl.cf.process.actions; import javax.inject.Inject; import org.springframework.stereotype.Component; import com.sap.cloud.lm.sl.cf.core.flowable.AdditionalProcessAction; import com.sap.cloud.lm.sl.cf.core.flowable.FlowableFacade; import com.sap.cloud.lm.sl.cf.core.flowable.RetryProcessAction; import com.sap.cloud.lm.sl.cf.process.Constants; import com.sap.cloud.lm.sl.cf.process.steps.StepPhase; @Component public class SetRetryPhaseAdditionalProcessAction implements AdditionalProcessAction { private FlowableFacade flowableFacade; @Inject public SetRetryPhaseAdditionalProcessAction(FlowableFacade flowableFacade) { this.flowableFacade = flowableFacade; } @Override public void executeAdditionalProcessAction(String processInstanceId) { flowableFacade.getActiveProcessExecutions(processInstanceId) .stream() .map(execution -> execution.getProcessInstanceId()) .forEach(executionProcessId -> flowableFacade.getProcessEngine() .getRuntimeService() .setVariable(executionProcessId, Constants.VAR_STEP_PHASE, StepPhase.RETRY.toString())); } @Override public String getApplicableActionId() { return RetryProcessAction.ACTION_ID_RETRY; } }
package com.sap.cloud.lm.sl.cf.process.actions; import javax.inject.Inject; import org.springframework.stereotype.Component; import com.sap.cloud.lm.sl.cf.core.flowable.AdditionalProcessAction; import com.sap.cloud.lm.sl.cf.core.flowable.FlowableFacade; import com.sap.cloud.lm.sl.cf.core.flowable.RetryProcessAction; import com.sap.cloud.lm.sl.cf.process.Constants; import com.sap.cloud.lm.sl.cf.process.steps.StepPhase; @Component public class SetRetryPhaseAdditionalProcessAction implements AdditionalProcessAction { private FlowableFacade flowableFacade; @Inject public SetRetryPhaseAdditionalProcessAction(FlowableFacade flowableFacade) { this.flowableFacade = flowableFacade; } @Override public void executeAdditionalProcessAction(String processInstanceId) { flowableFacade.getActiveProcessExecutions(processInstanceId) .stream() .map(execution -> execution.getProcessInstanceId()) .forEach(executionProcessId -> flowableFacade.getProcessEngine() .getRuntimeService() .setVariable(executionProcessId, Constants.VAR_STEP_PHASE, StepPhase.RETRY)); } @Override public String getApplicableActionId() { return RetryProcessAction.ACTION_ID_RETRY; } }
Call sum endpoint with inqueue§
import { takeLatest } from 'redux-saga' import { call, put, fork } from 'redux-saga/effects' import * as actions from './actions' import 'isomorphic-fetch' export default function* root(){ yield fork(sagas) } export function* sagas() { console.log('setup saga') yield [ takeLatest(actions.FETCH_TOTAL_AMOUNT, fetchTotalAmount), takeLatest(actions.FETCH_QUEUE, fetchQueue) ] } export function fetchApi(url) { return fetch(url) .then(response => response.json()) } export function* fetchQueue() { console.log('saga') try { const queue = yield call(fetchApi, 'donation/queue') console.log('quuee', queue) yield put(actions.fetchQueueDone(queue)) } catch(err) { console.log(err) // Error handling } } export function* fetchTotalAmount() { console.log('saga') try { const response = yield call(fetchApi, 'donation/sum?state=in_queue') yield put(actions.fetchTotalAmountDone(response.sum)) } catch(err) { console.log(err) // Error handling } }
import { takeLatest } from 'redux-saga' import { call, put, fork } from 'redux-saga/effects' import * as actions from './actions' import 'isomorphic-fetch' export default function* root(){ yield fork(sagas) } export function* sagas() { console.log('setup saga') yield [ takeLatest(actions.FETCH_TOTAL_AMOUNT, fetchTotalAmount), takeLatest(actions.FETCH_QUEUE, fetchQueue) ] } export function fetchApi(url) { return fetch(url) .then(response => response.json()) } export function* fetchQueue() { console.log('saga') try { const queue = yield call(fetchApi, 'donation/queue') console.log('quuee', queue) yield put(actions.fetchQueueDone(queue)) } catch(err) { console.log(err) // Error handling } } export function* fetchTotalAmount() { console.log('saga') try { const response = yield call(fetchApi, 'donation/sum') yield put(actions.fetchTotalAmountDone(response.sum)) } catch(err) { console.log(err) // Error handling } }
Correct AEP resource for person signup helper Signed-off-by: shaisachs <47bd79f9420edf5d0991d1e2710179d4e040d480@ngpvan.com>
var contentType = require('../middleware/contentType'), config = require('../config'); function apiRoot(req, res) { var root = config.get('apiEndpoint'); var answer = { motd: 'Welcome to the NGP VAN OSDI Service!', max_pagesize: 200, vendor_name: 'NGP VAN, Inc.', product_name: 'VAN', osdi_version: '1.0', _links: { self: { href: root, title: 'NGP VAN OSDI Service Entry Point' }, 'osdi:tags': { 'href': root + 'tags', 'title': 'The collection of tags in the system' }, 'osdi:questions': { 'href': root + 'questions', 'title': 'The collection of questions in the system' }, "osdi:person_signup_helper": { "href": root + 'people/person_signup', "title": "The person signup helper for the system" } } }; return res.status(200).send(answer); } module.exports = function (app) { app.get('/api/v1/', contentType, apiRoot); };
var contentType = require('../middleware/contentType'), config = require('../config'); function apiRoot(req, res) { var root = config.get('apiEndpoint'); var answer = { motd: 'Welcome to the NGP VAN OSDI Service!', max_pagesize: 200, vendor_name: 'NGP VAN, Inc.', product_name: 'VAN', osdi_version: '1.0', _links: { self: { href: root, title: 'NGP VAN OSDI Service Entry Point' }, 'osdi:tags': { 'href': root + 'tags', 'title': 'The collection of tags in the system' }, 'osdi:questions': { 'href': root + 'questions', 'title': 'The collection of questions in the system' }, 'osdi:people': { 'href': root + 'people', 'title': 'The collection of people in the system' } } }; return res.status(200).send(answer); } module.exports = function (app) { app.get('/api/v1/', contentType, apiRoot); };
Update regex used to check for codegenNativeComponent Summary: Updates regex to allow for type casts Reviewed By: TheSavior Differential Revision: D16717249 fbshipit-source-id: f22561d5cd33ab129fc0af4490692344726d7d71
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ 'use strict'; import type {SchemaType} from '../../CodegenSchema.js'; const FlowParser = require('../../parsers/flow'); const fs = require('fs'); function combineSchemas(files: Array<string>): SchemaType { return files.reduce( (merged, filename) => { const contents = fs.readFileSync(filename, 'utf8'); if ( contents && (/export\s+default\s+\(?codegenNativeComponent</.test(contents) || /extends TurboModule/.test(contents)) ) { const schema = FlowParser.parseFile(filename); if (schema && schema.modules) { merged.modules = {...merged.modules, ...schema.modules}; } } return merged; }, {modules: {}}, ); } module.exports = combineSchemas;
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ 'use strict'; import type {SchemaType} from '../../CodegenSchema.js'; const FlowParser = require('../../parsers/flow'); const fs = require('fs'); function combineSchemas(files: Array<string>): SchemaType { return files.reduce( (merged, filename) => { const contents = fs.readFileSync(filename, 'utf8'); if ( contents && (/export\s+default\s+codegenNativeComponent</.test(contents) || /extends TurboModule/.test(contents)) ) { const schema = FlowParser.parseFile(filename); if (schema && schema.modules) { merged.modules = {...merged.modules, ...schema.modules}; } } return merged; }, {modules: {}}, ); } module.exports = combineSchemas;
Fix for assertIs method not being present in Python 2.6.
from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message assert type(time) is datetime if sys.version_info[0] == 2: # python2.x assert type(msgId) in (str, unicode) assert type(user) in (str, unicode) assert type(text) in (str, unicode) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main()
from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message self.assertIs(type(time), datetime) if sys.version_info[0] == 2: # python2.x assert type(msgId) in (str, unicode) assert type(user) in (str, unicode) assert type(text) in (str, unicode) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main()
Add some chronopost codes to recognize
<?php namespace LWI\DeliveryTracking\Behavior; use LWI\DeliveryTracking\DeliveryStatus; trait ChronopostCodesTransformer { /** * @param string $code * * @return null | DeliveryStatus */ protected function getStateFromCode($code) { switch ($code) { case 'D': case 'D1': case 'D2': case 'RG': case 'DD': case 'B': case 'U': case 'VC': case 'RI': case 'RR': $state = DeliveryStatus::stateDelivered(); break; default: $state = DeliveryStatus::stateInProgress(); break; } return $state; } }
<?php namespace LWI\DeliveryTracking\Behavior; use LWI\DeliveryTracking\DeliveryStatus; trait ChronopostCodesTransformer { /** * @param string $code * * @return null | DeliveryStatus */ protected function getStateFromCode($code) { switch ($code) { case 'D': case 'D1': case 'D2': $state = DeliveryStatus::stateDelivered(); break; default: $state = DeliveryStatus::stateInProgress(); break; } return $state; } }
Add Method to Context interface
package chuper import ( "net/url" "github.com/PuerkitoBio/fetchbot" "github.com/Sirupsen/logrus" ) type Context interface { Cache() Cache Queue() Enqueuer Log(fields map[string]interface{}) *logrus.Entry URL() *url.URL Method() string SourceURL() *url.URL } type Ctx struct { *fetchbot.Context C Cache L *logrus.Logger } func (c *Ctx) Cache() Cache { return c.C } func (c *Ctx) Queue() Enqueuer { return &Queue{c.Q} } func (c *Ctx) Log(fields map[string]interface{}) *logrus.Entry { data := logrus.Fields{} for k, v := range fields { data[k] = v } return c.L.WithFields(data) } func (c *Ctx) URL() *url.URL { return c.Cmd.URL() } func (c *Ctx) Method() string { return c.Cmd.Method() } func (c *Ctx) SourceURL() *url.URL { switch cmd := c.Cmd.(type) { case *Cmd: return cmd.SourceURL() case *CmdBasicAuth: return cmd.SourceURL() default: return nil } }
package chuper import ( "net/url" "github.com/PuerkitoBio/fetchbot" "github.com/Sirupsen/logrus" ) type Context interface { Cache() Cache Queue() Enqueuer Log(fields map[string]interface{}) *logrus.Entry URL() *url.URL SourceURL() *url.URL } type Ctx struct { *fetchbot.Context C Cache L *logrus.Logger } func (c *Ctx) Cache() Cache { return c.C } func (c *Ctx) Queue() Enqueuer { return &Queue{c.Q} } func (c *Ctx) Log(fields map[string]interface{}) *logrus.Entry { data := logrus.Fields{} for k, v := range fields { data[k] = v } return c.L.WithFields(data) } func (c *Ctx) URL() *url.URL { return c.Cmd.URL() } func (c *Ctx) SourceURL() *url.URL { switch cmd := c.Cmd.(type) { case *Cmd: return cmd.SourceURL() case *CmdBasicAuth: return cmd.SourceURL() default: return nil } }
Fix some var names and ES6 syntax
import 'babel-polyfill'; const window = (typeof window !== 'undefined') ? window : {}; // Default config values. const defaultConfig = { loggingFunction: () => true, loadInWorker: true, // FIXME cambia il nome }; // Config used by the module. const config = {}; // ***** Private functions ***** const formatError = (error = {}) => error; // Public function. const funcExecutor = (funcToCall, args = [], scope = undefined) => { try { funcToCall.apply(scope, ...args); } catch (e) { // TODO trova modo per fare la compose nativa config.loggingFunction(formatError(e)); throw e; } }; // FIXME capire se è permesso avere la window come default const attachGlobalHandler = (scope = window) => { scope.onerror = () => { // TODO trova modo per fare la compose nativa config.loggingFunction(formatError({ ...arguments })); return false; }; }; export default function LogIt(userConfig = defaultConfig) { Object.assign(config, userConfig); return { funcExecutor, attachGlobalHandler, }; }
import 'babel-polyfill'; // Default config values. const defaultConfig = { loggingFunction: () => true, }; // Config used by the module. const config = {}; // Private function. const formatError = (error = {}) => { return error; }; const formatAndLogError = (error) => { }; // Public function. const funcExecutor = (funcToCall, args = [], scope = undefined) => { try { funcToCall.apply(scope, ...args); } catch (e) { config.loggingFunction(); throw e; } }; const attachGlobalHandler = (scope = window) => { scope.onerror = function myErrorHandler() { const formattedError = formatError({ ...arguments }); const return false; }; }; export default function LogIt(userConfig = defaultConfig) { Object.assign(config, userConfig); return { funcExecutor, attachGlobalHandler, }; }
Change onMessage signature to match MessageHandler
// Program gcm-logger logs and echoes as a GCM "server". package main import ( "github.com/alecthomas/kingpin" "github.com/aliafshar/toylog" "github.com/google/go-gcm" ) var ( serverKey = kingpin.Flag("server_key", "The server key to use for GCM.").Short('k').Required().String() senderId = kingpin.Flag("sender_id", "The sender ID to use for GCM.").Short('s').Required().String() ) // onMessage receives messages, logs them, and echoes a response. func onMessage(cm gcm.CcsMessage) error { toylog.Infoln("Message, from:", cm.From, "with:", cm.Data) // Echo the message with a tag. cm.Data["echoed"] = true m := gcm.HttpMessage{To: cm.From, Data: cm.Data} r, err := gcm.SendHttp(*serverKey, m) if err != nil { toylog.Errorln("Error sending message.", err) return err } toylog.Infof("Sent message. %+v -> %+v", m, r) return nil } func main() { toylog.Infoln("GCM Logger, starting.") kingpin.Parse() gcm.Listen(*senderId, *serverKey, onMessage, nil) }
// Program gcm-logger logs and echoes as a GCM "server". package main import ( "github.com/alecthomas/kingpin" "github.com/aliafshar/toylog" "github.com/google/go-gcm" ) var ( serverKey = kingpin.Flag("server_key", "The server key to use for GCM.").Short('k').Required().String() senderId = kingpin.Flag("sender_id", "The sender ID to use for GCM.").Short('s').Required().String() ) // onMessage receives messages, logs them, and echoes a response. func onMessage(from string, d gcm.Data) error { toylog.Infoln("Message, from:", from, "with:", d) // Echo the message with a tag. d["echoed"] = true m := gcm.HttpMessage{To: from, Data: d} r, err := gcm.SendHttp(*serverKey, m) if err != nil { toylog.Errorln("Error sending message.", err) return err } toylog.Infof("Sent message. %+v -> %+v", m, r) return nil } func main() { toylog.Infoln("GCM Logger, starting.") kingpin.Parse() gcm.Listen(*senderId, *serverKey, onMessage, nil) }
Include deleted count into report * updated tests
package com.nhl.link.move; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.Collections; import java.util.Map; import org.junit.Test; import com.nhl.link.move.Execution; public class ExecutionTest { @Test public void testCreateReport() { Execution execution = new Execution("xsync", Collections.singletonMap("a", 5)); Map<String, Object> r1 = execution.createReport(); assertEquals("xsync", r1.get("Task")); assertEquals(5, r1.get("Parameter[a]")); assertEquals(r1.toString(), 8, r1.size()); assertEquals("in progress", r1.get("Status")); execution.close(); Map<String, Object> r2 = execution.createReport(); assertEquals(r2.toString(), 8, r2.size()); assertEquals("finished", r2.get("Status")); } @Test public void testAttribute() { try (Execution execution = new Execution("xsync", Collections.<String, Object> emptyMap())) { assertNull(execution.getAttribute("a")); execution.setAttribute("a", "MMM"); assertEquals("MMM", execution.getAttribute("a")); execution.setAttribute("a", null); assertNull(execution.getAttribute("a")); } } }
package com.nhl.link.move; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.Collections; import java.util.Map; import org.junit.Test; import com.nhl.link.move.Execution; public class ExecutionTest { @Test public void testCreateReport() { Execution execution = new Execution("xsync", Collections.singletonMap("a", 5)); Map<String, Object> r1 = execution.createReport(); assertEquals("xsync", r1.get("Task")); assertEquals(5, r1.get("Parameter[a]")); assertEquals(r1.toString(), 7, r1.size()); assertEquals("in progress", r1.get("Status")); execution.close(); Map<String, Object> r2 = execution.createReport(); assertEquals(r2.toString(), 7, r2.size()); assertEquals("finished", r2.get("Status")); } @Test public void testAttribute() { try (Execution execution = new Execution("xsync", Collections.<String, Object> emptyMap())) { assertNull(execution.getAttribute("a")); execution.setAttribute("a", "MMM"); assertEquals("MMM", execution.getAttribute("a")); execution.setAttribute("a", null); assertNull(execution.getAttribute("a")); } } }
Add find and delete functions to ang review model
(function(){ 'use strict'; angular .module('secondLead') .factory('ReviewModel',['$http', 'Restangular', 'store', function($http, Restangular, store) { var currentUser = store.get('user'); function extract(result) { return result.data; }; return { getAll: function(dramaID){ return Restangular.one('dramas', dramaID).getList('reviews').$object }, getOne: function(dramaID, reviewID) { return Restangular.one('dramas', dramaID).one('reviews', reviewID).get() }, create: function(dramaID, userID, review) { return Restangular.one('dramas', dramaID).all('reviews').post({drama_id: dramaID, body: review, reviewer_id: userID}) }, find: function(dramaID, userID){ return $http.get('/reviews/find', {params: {drama_id: dramaID, reviewer_id: userID}}).then(extract); }, update: function(dramaID, reviewID,review){ return Restangular.one('dramas', dramaID).one('reviews', reviewID).put({body: review}) }, delete: function(dramaID, reviewID){ return Restangular.one('dramas', dramaID).one('reviews', reviewID).remove() } }; }]) })();
(function(){ 'use strict'; angular .module('secondLead') .factory('ReviewModel',['Restangular', 'store', function(Restangular, store) { var currentUser = store.get('user'); return { getAll: function(dramaID){ return Restangular.one('dramas', dramaID).getList('reviews').$object }, getOne: function(dramaID, reviewID) { return Restangular.one('dramas', dramaID).one('reviews', reviewID).get() }, create: function(dramaID, userID, review) { return Restangular.one('dramas', dramaID).getList('reviews').post({drama_id: dramaID, body: review, reviewer_id: userID}) }, update: function(dramaID, reviewID,review){ return Restangular.one('dramas', dramaID).one('reviews', reviewID).put({body: review}) } }; }]) })();
Replace direct reference to user in the recipe list api
var express = require('express'); var router = express.Router(); var JsonDB = require('node-json-db'); var _ = require('lodash'); // Recipes listing router.get('/', function (req, res, next) { var db = new JsonDB('db', false, false); var recipes = db.getData('/recipes'); // Expand requested resources if they exist // The resource to expand is singular, e.g. // to expand 'users' we provide _expand=user var expand = req.query._expand; if (expand) { try { var relation = db.getData('/' + expand + 's'); _(recipes) .forEach(function (recipe) { recipe[expand] = _(relation).find({ id: recipe[expand + 'Id'] }); delete recipe[expand + 'Id']; }) .value(); } catch(err) { console.log(err); } } res.json(recipes); }); module.exports = router;
var express = require('express'); var router = express.Router(); var JsonDB = require('node-json-db'); var _ = require('lodash'); // Recipes listing router.get('/', function (req, res, next) { var db = new JsonDB('db', false, false); var recipes = db.getData('/recipes'); // Expand requested resources if they exist // The resource to expand is singular, e.g. // to expand 'users' we provide _expand=user var expand = req.query._expand; if (expand) { try { var relation = db.getData('/' + expand + 's'); _(recipes) .forEach(function (recipe) { recipe.user = _(relation).findWhere({ id: recipe[expand + 'Id'] }); delete recipe[expand + 'Id']; }) .value(); } catch(err) { console.log(err); } } res.json(recipes); }); module.exports = router;
Fix unit test to temporarily pass Travis
import documentFormatter from 'src/logic/documentPackager/documentFormatter'; describe('DocumentFormatter', () => { describe('format', () => { it('should returns the same data for \'html viewMode\'', () => { const viewMode = 'html'; const inputData = '<div>This is a HTML content</div>'; const outputData = documentFormatter.format(inputData, viewMode); expect(outputData).to.equal('<div>This is a HTML content</div>'); }); }); describe('getPdfBase64', () => { it('should returns a pdfBase64 for \'pages viewMode\'', (done) => { const inputData = '<div>This is a HTML content</div>'; documentFormatter.getPdfBase64(inputData) .then((outputData) => { // jsPDF does not give deterministic outputData // around 5 characters will always be different in the output // therefore, an approximation method to use content length for // testing is used. expect(outputData.length).to.equal(3333); done(); }) .catch((error) => { done(error); }); }); }); });
import documentFormatter from 'src/logic/documentPackager/documentFormatter'; import base64OfSimplePdf from './reference/base64OfSimplePdf'; describe('DocumentFormatter', () => { describe('format', () => { it('should returns the same data for \'html viewMode\'', () => { const viewMode = 'html'; const inputData = '<div>This is a HTML content</div>'; const outputData = documentFormatter.format(inputData, viewMode); expect(outputData).to.equal('<div>This is a HTML content</div>'); }); }); describe('getPdfBase64', () => { it('should returns a pdfBase64 for \'pages viewMode\'', (done) => { const expectedOutput = base64OfSimplePdf; const inputData = '<div>This is a HTML content</div>'; documentFormatter.getPdfBase64(inputData) .then((outputData) => { // jsPDF does not give deterministic outputData // around 5 characters will always be different in the output // therefore, an approximation method to use content length for // testing is used. expect(outputData.length).to.equal(expectedOutput.length); done(); }) .catch((error) => { done(error); }); }); }); });
Remove no-op event handlers in playground.
/*global Playground*/ (function() { "use strict"; Playground.VideoService = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.videoPort = port; } }); Playground.SurveyService = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.surveyPort = port; } }); Playground.SlotMachine = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.slotMachinePort = port; } }); Playground.AdPlaylistService = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.adPlaylistPort = port; }, events: { surveyTaken: function (data) { this.sandbox.slotMachinePort.send('addCoin'); } } }); $.extend(Playground, { initializeServices: function () { Conductor.services.video = Playground.VideoService; Conductor.services.survey = Playground.SurveyService; Conductor.services.slotMachine = Playground.SlotMachine; } }); })();
/*global Playground*/ (function() { "use strict"; Playground.VideoService = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.videoPort = port; }, events: { videoWatched: function () { } } }); Playground.SurveyService = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.surveyPort = port; }, events: { surveyTaken: function () { } } }); Playground.SlotMachine = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.slotMachinePort = port; }, events: { getCoins: function () { } } }); Playground.AdPlaylistService = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.adPlaylistPort = port; }, events: { surveyTaken: function (data) { this.sandbox.slotMachinePort.send('addCoin'); } } }); $.extend(Playground, { initializeServices: function () { Conductor.services.video = Playground.VideoService; Conductor.services.survey = Playground.SurveyService; Conductor.services.slotMachine = Playground.SlotMachine; } }); })();
Raise invalid page on paging error
from django.core.paginator import Paginator, InvalidPage class ElasticsearchPaginator(Paginator): """ Paginator that prevents two queries to ES (for count and objects) as ES gives count with objects """ MAX_ES_OFFSET = 10000 def page(self, number): """ Returns a Page object for the given 1-based page number. """ bottom = (number - 1) * self.per_page if bottom >= self.MAX_ES_OFFSET: # Only validate if bigger than offset number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page try: self.object_list = self.object_list[bottom:top] except ValueError: raise InvalidPage() # ignore top boundary # if top + self.orphans >= self.count: # top = self.count # Validate number after limit/offset has been set number = self.validate_number(number) return self._get_page(self.object_list, number, self)
from django.core.paginator import Paginator class ElasticsearchPaginator(Paginator): """ Paginator that prevents two queries to ES (for count and objects) as ES gives count with objects """ MAX_ES_OFFSET = 10000 def page(self, number): """ Returns a Page object for the given 1-based page number. """ bottom = (number - 1) * self.per_page if bottom >= self.MAX_ES_OFFSET: # Only validate if bigger than offset number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page self.object_list = self.object_list[bottom:top] # ignore top boundary # if top + self.orphans >= self.count: # top = self.count # Validate number after limit/offset has been set number = self.validate_number(number) return self._get_page(self.object_list, number, self)
examples/fortune: Use the roaming and not the generic runtime factory In this particular case, it means fortuned transparently remounts itself as it moves across networks (if running on a laptop that moves around for example) and it also turns on the debugging services. In general though, I suspect we can simply do away with the use of the 'generic' profile. Will look into that separately. Change-Id: Icca633576a498277351bea4ca6e1c4420076add2
// Copyright 2015 The Vanadium Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Command fortuned runs a daemon that implements the Fortune interface. package main import ( "flag" "log" "v.io/v23" "v.io/v23/security" "v.io/x/ref/examples/fortune" "v.io/x/ref/lib/signals" // The v23.Init call below will use the roaming runtime factory. _ "v.io/x/ref/runtime/factories/roaming" ) var ( name = flag.String("name", "", "Name for fortuned in default mount table") ) func main() { ctx, shutdown := v23.Init() defer shutdown() authorizer := security.DefaultAuthorizer() impl := newImpl() service := fortune.FortuneServer(impl) ctx, server, err := v23.WithNewServer(ctx, *name, service, authorizer) if err != nil { log.Panic("Failure creating server: ", err) } log.Printf("Listening at: %v\n", server.Status().Endpoints[0]) <-signals.ShutdownOnSignals(ctx) }
// Copyright 2015 The Vanadium Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Command fortuned runs a daemon that implements the Fortune interface. package main import ( "flag" "log" "v.io/v23" "v.io/v23/security" "v.io/x/ref/examples/fortune" "v.io/x/ref/lib/signals" // The v23.Init call below will use the generic runtime factory. _ "v.io/x/ref/runtime/factories/generic" ) var ( name = flag.String("name", "", "Name for fortuned in default mount table") ) func main() { ctx, shutdown := v23.Init() defer shutdown() authorizer := security.DefaultAuthorizer() impl := newImpl() service := fortune.FortuneServer(impl) ctx, server, err := v23.WithNewServer(ctx, *name, service, authorizer) if err != nil { log.Panic("Failure creating server: ", err) } log.Printf("Listening at: %v\n", server.Status().Endpoints[0]) <-signals.ShutdownOnSignals(ctx) }
Use local memory as cache so ratelimit tests don't fail
from __future__ import absolute_import import os os.environ['INBOX_TESTING'] = '1' from settings import * CACHES = { "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache" } } db = os.environ.get('DB') SECRET_KEY = "This is a test, you don't need secrets" if db == "sqlite": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } elif db == "postgres": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'inboxen', 'USER': 'postgres', }, } else: raise NotImplementedError("Please check tests/settings.py for valid DB values")
from __future__ import absolute_import import os os.environ['INBOX_TESTING'] = '1' from settings import * CACHES = { "default": { "BACKEND": "django.core.cache.backends.dummy.DummyCache" } } db = os.environ.get('DB') SECRET_KEY = "This is a test, you don't need secrets" if db == "sqlite": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } elif db == "postgres": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'inboxen', 'USER': 'postgres', }, } else: raise NotImplementedError("Please check tests/settings.py for valid DB values")
Improve the migration for unique data source name
from redash.models import db import peewee from playhouse.migrate import PostgresqlMigrator, migrate if __name__ == '__main__': migrator = PostgresqlMigrator(db.database) with db.database.transaction(): # Change the uniqueness constraint on data source name to be (org, name): # In some cases it's a constraint: db.database.execute_sql('ALTER TABLE data_sources DROP CONSTRAINT IF EXISTS unique_name') # In others only an index: db.database.execute_sql('DROP INDEX IF EXISTS data_sources_name') migrate( migrator.add_index('data_sources', ('org_id', 'name'), unique=True) ) db.close_db(None)
from redash.models import db import peewee from playhouse.migrate import PostgresqlMigrator, migrate if __name__ == '__main__': migrator = PostgresqlMigrator(db.database) with db.database.transaction(): # Change the uniqueness constraint on data source name to be (org, name): success = False for index_name in ['unique_name', 'data_sources_name']: try: print "Trying to remove data source name uniqueness index with the name: {}".format(index_name) migrate(migrator.drop_index("data_sources", index_name)) print "Success!" success = True break except peewee.ProgrammingError: db.close_db(None) if not success: print "Failed removing uniqueness constraint on data source name." print "Please verify its name in the schema, update the migration and run again." exit(1) migrate( migrator.add_index('data_sources', ('org_id', 'name'), unique=True) ) db.close_db(None)
Support ConnectedTechnologies and EnabledTechnologies Properties
//var dbus = module.exports = require('node-dbus'); var dbus = require('node-dbus'); module.exports = function() { var self = this; this.init = function(callback) { dbus.start(function() { self.systemBus = dbus.system_bus(); self.manager = dbus.get_interface(self.systemBus, 'net.connman', '/', 'net.connman.Manager'); self.properties = self.manager.GetProperties(); console.log(self.manager.GetProperties()); // console.log(self.manager); callback(); }); }; this.__defineGetter__('AvailableTechnologies', function() { return self.manager.GetProperties().AvailableTechnologies; }); this.__defineGetter__('EnabledTechnologies', function() { return self.manager.GetProperties().EnabledTechnologies; }); this.__defineGetter__('ConnectedTechnologies', function() { return self.manager.GetProperties().ConnectedTechnologies; }); this.__defineGetter__('GetState', function() { return self.manager.GetState(); }); this.__defineGetter__('OfflineMode', function() { return self.manager.GetProperties().OfflineMode; }); this.__defineSetter__('OfflineMode', function(value) { return self.manager.SetProperty('OfflineMode', false); }); };
//var dbus = module.exports = require('node-dbus'); var dbus = require('node-dbus'); module.exports = function() { var self = this; this.init = function(callback) { dbus.start(function() { self.systemBus = dbus.system_bus(); self.manager = dbus.get_interface(self.systemBus, 'net.connman', '/', 'net.connman.Manager'); self.properties = self.manager.GetProperties(); console.log(self.manager); callback(); }); }; this.__defineGetter__('AvailableTechnologies', function() { return self.properties.AvailableTechnologies; }); this.__defineGetter__('GetState', function() { return self.manager.GetState(); }); this.__defineGetter__('OfflineMode', function() { return self.manager.GetProperties().OfflineMode; }); this.__defineSetter__('OfflineMode', function(value) { return self.manager.SetProperty('OfflineMode', false); }); };
Test double call to DisposableSubscription.unsubscribe()
package com.artemzin.qualitymatters.other; import org.junit.Before; import org.junit.Test; import rx.functions.Action0; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; public class DisposableSubscriptionTest { private Action0 disposeAction; private DisposableSubscription disposableSubscription; @Before public void beforeEachTest() { disposeAction = mock(Action0.class); disposableSubscription = new DisposableSubscription(disposeAction); } @Test public void unsubscribed_shouldReturnFalseByDefault() { assertThat(disposableSubscription.isUnsubscribed()).isFalse(); verifyZeroInteractions(disposeAction); } @Test public void unsubscribe_shouldChangeValueOfIsUsubscribed() { disposableSubscription.unsubscribe(); assertThat(disposableSubscription.isUnsubscribed()).isTrue(); } @Test public void unsubscribe_shouldCallDisposableAction() { disposableSubscription.unsubscribe(); verify(disposeAction).call(); } @Test public void unsubscribeTwice_shouldCallDisposableActionOnce() { disposableSubscription.unsubscribe(); disposableSubscription.unsubscribe(); verify(disposeAction).call(); } }
package com.artemzin.qualitymatters.other; import org.junit.Before; import org.junit.Test; import rx.functions.Action0; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; public class DisposableSubscriptionTest { private Action0 disposeAction; private DisposableSubscription disposableSubscription; @Before public void beforeEachTest() { disposeAction = mock(Action0.class); disposableSubscription = new DisposableSubscription(disposeAction); } @Test public void unsubscribed_shouldReturnFalseByDefault() { assertThat(disposableSubscription.isUnsubscribed()).isFalse(); verifyZeroInteractions(disposeAction); } @Test public void unsubscribe_shouldChangeValueOfIsUsubscribed() { disposableSubscription.unsubscribe(); assertThat(disposableSubscription.isUnsubscribed()).isTrue(); } @Test public void unsubscribe_shouldCallDisposableAction() { disposableSubscription.unsubscribe(); verify(disposeAction).call(); } }
Edit model associations using new syntax
module.exports = (sequelize, DataTypes) => { const User = sequelize.define('User', { username: { type: DataTypes.STRING, allowNull: false, unique: true, }, password: { type: DataTypes.STRING, allowNull: false, }, email: { type: DataTypes.STRING, allowNull: false, unique: true }, salt: DataTypes.STRING }); User.associate = (models) => { User.hasMany(models.Message, { foreignKey: 'userId' }); User.belongsToMany(models.Group, { as: 'Members', foreignKey: 'groupId', through: 'UserGroup', }); }; return User; };
module.exports = (sequelize, DataTypes) => { const User = sequelize.define('User', { username: { type: DataTypes.STRING, allowNull: false, unique: true, }, password: { type: DataTypes.STRING, allowNull: false, }, email: { type: DataTypes.STRING, allowNull: false, unique: true }, salt: DataTypes.STRING }, { classMethods: { associate(models) { User.hasMany(models.Message, { foreignKey: 'userId', as: 'userMessages' }); User.belongsToMany(models.Group, { as: 'Members', foreignKey: 'groupId', through: 'UserGroup', }); } } }); return User; };
Fix issues found by jshint
var express = require('express'); var http = require('http'); // var url = require('url'); var restify = require('express-restify-mongoose'); var mongoose = require('mongoose'); var Artist = require('./api/models/artist'); var Faq = require('./api/models/faq'); var News = require('./api/models/news'); var Program = require('./api/models/program'); var Stage = require('./api/models/stage'); var mongourl = process.env.MONGOLAB_URI || 'mongodb://localhost/festapp-dev'; mongoose.connect(mongourl); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { console.log('Yay'); }); var app = express(); app.use('/public', express.static(__dirname + '/public')); restify.serve(app, Artist); restify.serve(app, Faq); restify.serve(app, News); restify.serve(app, Program); restify.serve(app, Stage); var port = Number(process.env.PORT || 8080); http.createServer(app).listen(port); console.log('Running at port '+port);
var express = require('express'); var http = require('http'); var url = require('url'); var restify = require('express-restify-mongoose'); var mongoose = require('mongoose'); var Artist = require('./api/models/artist'); var Faq = require('./api/models/faq'); var News = require('./api/models/news'); var Program = require('./api/models/program'); var Stage = require('./api/models/stage'); var mongourl = process.env.MONGOLAB_URI || 'mongodb://localhost/festapp-dev'; mongoose.connect(mongourl); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { console.log("Yay"); }); var app = express(); app.use('/public', express.static(__dirname + '/public')); restify.serve(app, Artist); restify.serve(app, Faq); restify.serve(app, News); restify.serve(app, Program); restify.serve(app, Stage); var port = Number(process.env.PORT || 8080); http.createServer(app).listen(port); console.log('Running at port '+port);
Use item_type, and also register a block helper for each template
/** * Class - a registry of templates. Duh. */ cronenberg.TemplateRegistry = function() { this.registry = {}; /** * Compile a template and register the compiled render function by * item type. Each template must specify what kind of API entity * it renders using the data-item-type HTML attribute. * * An expression helper will also be registered, so each template * can be called easily from other templates. */ this.register = function(elementId) { var element = $('#' + elementId); var itemType = element.attr('data-item-type'); var compiled = Handlebars.compile(element.html()); this.registry[itemType] = compiled; Handlebars.registerHelper(itemType, function(item) { return new Handlebars.SafeString( cronenberg.templates.registry[itemType]({ item: item }) ); }); return this; }; /** * Render an item (either presentation or layout) received from * the API. */ this.render = function(item) { var template = this.registry[item.item_type]; return template({item: item}); }; }; cronenberg.templates = new cronenberg.TemplateRegistry();
/** * Class - a registry of templates. Duh. */ cronenberg.TemplateRegistry = function() { this.registry = {}; /** * Compile a template and register the compiled render function by * item type. Each template must specify what kind of API entity * it renders using the data-item-type HTML attribute. */ this.register = function(elementId) { element = $('#' + elementId); this.registry[element.attr('data-item-type')] = Handlebars.compile(element.html()); return this; }; /** * Render an item (either presentation or layout) received from * the API. * * TODO: should this append to the parent, or leave that to the * caller? Leaning towards the latter. */ this.render = function(item, parent) { var template = this.registry[item.type]; $(parent).append(template({item: item})); }; }; cronenberg.templates = new cronenberg.TemplateRegistry();
Move ok response creation to pytest fixture
import os import pytest import requests from cisco_olt_http import operations from cisco_olt_http.client import Client @pytest.fixture def data_dir(): return os.path.abspath( os.path.join(os.path.dirname(__file__), 'data')) @pytest.fixture def ok_response(data_dir, mocker): response = mocker.Mock(autospec=requests.Response) with open(os.path.join(data_dir, 'ok_response.xml')) as of: response.content = of.read() return response def test_get_data(): client = Client('http://base-url') show_equipment_op = operations.ShowEquipmentOp(client) op_data = show_equipment_op.get_data() assert op_data class TestOperationResult: def test_ok_response(self, ok_response): operation_result = operations.OperationResult(ok_response) assert not operation_result.error assert operation_result.error_str == 'OK'
import os import pytest import requests from cisco_olt_http import operations from cisco_olt_http.client import Client @pytest.fixture def data_dir(): return os.path.abspath( os.path.join(os.path.dirname(__file__), 'data')) def test_get_data(): client = Client('http://base-url') show_equipment_op = operations.ShowEquipmentOp(client) op_data = show_equipment_op.get_data() assert op_data class TestOperationResult: def test_ok_response(self, data_dir, mocker): response = mocker.Mock(autospec=requests.Response) with open(os.path.join(data_dir, 'ok_response.xml')) as of: response.content = of.read() operation_result = operations.OperationResult(response) assert not operation_result.error assert operation_result.error_str == 'OK'
Set expectations for the project disclaimer
import React from 'react'; import { mount, shallow } from 'enzyme'; import { expect } from 'chai'; import { project, workflow } from '../dev-classifier/mock-data'; import ProjectPage from './project-navbar'; describe('ProjectPage', () => { const background = { src: 'the project background image url' }; it('should render without crashing', () => { shallow(<ProjectPage />); }); it('should render the project nav bar', () => { const wrapper = shallow(<ProjectPage />); const navElement = wrapper.find('ProjectNavbar').first(); expect(navElement).to.have.lengthOf(1); }); it('should receive a background, project and workflow props', () => { const wrapper = mount(<ProjectPage background={background} project={project} workflow={workflow} />); expect(wrapper.props().background).to.equal(background); expect(wrapper.props().project).to.equal(project); expect(wrapper.props().workflow).to.equal(workflow); }); describe('with a launch-approved project', () => { it('should not render the Zooniverse disclaimer.'); }); describe('without approval', () => { it('should render the Zooniverse disclaimer.'); it('should render the disclaimer immediately after its children.') }); });
import React from 'react'; import { mount, shallow } from 'enzyme'; import { expect } from 'chai'; import { project, workflow } from '../dev-classifier/mock-data'; import ProjectPage from './project-navbar'; describe('ProjectPage', () => { const background = { src: 'the project background image url' }; it('should render without crashing', () => { shallow(<ProjectPage />); }); it('should render the project nav bar', () => { const wrapper = shallow(<ProjectPage />); const navElement = wrapper.find('ProjectNavbar').first(); expect(navElement).to.have.lengthOf(1); }); it('should receive a background, project and workflow props', () => { const wrapper = mount(<ProjectPage background={background} project={project} workflow={workflow} />); expect(wrapper.props().background).to.equal(background); expect(wrapper.props().project).to.equal(project); expect(wrapper.props().workflow).to.equal(workflow); }); });
Remove some lingering citext stuff from nickname query
import { db, Rat } from '../db' import Query from './index' /** * A class representing a rat query */ class NicknameQuery extends Query { /** * Create a sequelize rat query from a set of parameters * @constructor * @param params * @param connection */ constructor (params, connection) { super(params, connection) if (params.nickname) { let formattedNickname = params.nickname.replace(/\[(.*?)]$/g, '') this._query.where.nicknames = { $overlap: [params.nickname, formattedNickname] } delete this._query.where.nickname } this._query.attributes = [ 'id', 'createdAt', 'updatedAt', 'email', 'displayRatId', 'nicknames' ] this._query.include = [{ model: Rat, as: 'rats', required: false, attributes: { exclude: [ 'deletedAt' ] } }] } } module.exports = NicknameQuery
import { db, Rat } from '../db' import Query from './index' /** * A class representing a rat query */ class NicknameQuery extends Query { /** * Create a sequelize rat query from a set of parameters * @constructor * @param params * @param connection */ constructor (params, connection) { super(params, connection) if (params.nickname) { let formattedNickname = params.nickname.replace(/\[(.*?)]$/g, '') this._query.where.nicknames = { $overlap: db.literal(`ARRAY[${db.escape(params.nickname)}, ${db.escape(formattedNickname)}]::citext[]`) } delete this._query.where.nickname } this._query.attributes = [ 'id', 'createdAt', 'updatedAt', 'email', 'displayRatId', [db.cast(db.col('nicknames'), 'text[]'), 'nicknames'] ] this._query.include = [{ model: Rat, as: 'rats', required: false, attributes: { exclude: [ 'deletedAt' ] } }] } } module.exports = NicknameQuery
Remove Edge launcher from Karma Conf
module.exports = function(config) { config.set({ frameworks: [ 'jasmine', 'karma-typescript', ], plugins: [ 'karma-typescript', 'karma-jasmine', 'karma-firefox-launcher', 'karma-chrome-launcher', ], files: [ "./src/**/*.ts", "./test/**/*.ts" ], exclude: [ "./**/*.d.ts", "./**/IAsyncGrouping.ts", "./node_modules" ], preprocessors: { "./**/*.ts": "karma-typescript", }, karmaTypescriptConfig: { tsconfig: "./test/tsconfig.json" }, reporters: [ 'progress', 'karma-typescript' ], browsers: [ 'Firefox', 'Chrome', ], port: 9876, singleRun: true, logLevel: config.LOG_INFO, }) }
module.exports = function(config) { config.set({ frameworks: [ 'jasmine', 'karma-typescript', ], plugins: [ 'karma-typescript', 'karma-jasmine', 'karma-firefox-launcher', 'karma-chrome-launcher', 'karma-edge-launcher' ], files: [ "./src/**/*.ts", "./test/**/*.ts" ], exclude: [ "./**/*.d.ts", "./**/IAsyncGrouping.ts", "./node_modules" ], preprocessors: { "./**/*.ts": "karma-typescript", }, karmaTypescriptConfig: { tsconfig: "./test/tsconfig.json" }, reporters: [ 'progress', 'karma-typescript' ], browsers: [ // 'Edge', 'Firefox', 'Chrome', ], port: 9876, singleRun: true, logLevel: config.LOG_INFO, }) }
Use $UserID instead of $User->id git-svn-id: 3b6cb4556d214d66df54bca2662d7ef408f367bf@2610 46e82423-29d8-e211-989e-002590a4cdd4
<?php # # $Id: login.php,v 1.1.2.8 2003-12-01 18:17:47 dan Exp $ # # Copyright (c) 1998-2003 DVL Software Limited # if (IsSet($_GET['origin'])) $origin = $_GET["origin"]; ?> <form action="<?php echo $_SERVER["PHP_SELF"] . "?origin=$origin" ?>" method="POST" name="l"> <input type="hidden" name="custom_settings" value="1"><input type="hidden" name="LOGIN" value="1"> <p>User ID:<br> <input SIZE="15" NAME="UserID" value="<?php if (IsSet($UserID)) echo $UserID ?>"></p> <p>Password:<br> <input TYPE="PASSWORD" NAME="Password" VALUE = "<?php if (IsSet($Password)) echo $Password ?>" size="20"></p> <p><input TYPE="submit" VALUE="Login" name=submit> &nbsp;&nbsp;&nbsp;&nbsp; <input TYPE="reset" VALUE="reset form"> </form>
<?php # # $Id: login.php,v 1.1.2.7 2003-07-04 14:59:19 dan Exp $ # # Copyright (c) 1998-2003 DVL Software Limited # if (IsSet($_GET['origin'])) $origin = $_GET["origin"]; ?> <form action="<?php echo $_SERVER["PHP_SELF"] . "?origin=$origin" ?>" method="POST" name="l"> <input type="hidden" name="custom_settings" value="1"><input type="hidden" name="LOGIN" value="1"> <p>User ID:<br> <input SIZE="15" NAME="UserID" value="<?php if (IsSet($User->id)) echo $User->id ?>"></p> <p>Password:<br> <input TYPE="PASSWORD" NAME="Password" VALUE = "<?php if (IsSet($Password)) echo $Password ?>" size="20"></p> <p><input TYPE="submit" VALUE="Login" name=submit> &nbsp;&nbsp;&nbsp;&nbsp; <input TYPE="reset" VALUE="reset form"> </form>
PhpDoc: Fix type inconsistencies, put |null last for better readability
<?php /* * This file is part of the Elcodi package. * * Copyright (c) 2014 Elcodi.com * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Feel free to edit as you please, and have fun. * * @author Marc Morera <yuhu@mmoreram.com> * @author Aldo Chiecchia <zimage@tiscali.it> * @author Elcodi Team <tech@elcodi.com> */ namespace Elcodi\Component\Rule\Repository; use Doctrine\ORM\EntityRepository; use Elcodi\Component\Rule\Entity\Interfaces\RuleInterface; /** * Class RuleRepository */ class RuleRepository extends EntityRepository { /** * Return a rule by name * * @param string $name * * @return RuleInterface|null */ public function findOneByName($name) { return parent::findOneBy(['name' => $name]); } }
<?php /* * This file is part of the Elcodi package. * * Copyright (c) 2014 Elcodi.com * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Feel free to edit as you please, and have fun. * * @author Marc Morera <yuhu@mmoreram.com> * @author Aldo Chiecchia <zimage@tiscali.it> * @author Elcodi Team <tech@elcodi.com> */ namespace Elcodi\Component\Rule\Repository; use Doctrine\ORM\EntityRepository; use Elcodi\Component\Rule\Entity\Interfaces\RuleInterface; /** * Class RuleRepository */ class RuleRepository extends EntityRepository { /** * Return a rule by name * * @param string $name * * @return null|RuleInterface */ public function findOneByName($name) { return parent::findOneBy(['name' => $name]); } }
Remove reference to postgis template. Django now installs postgis when database is created.
import os import inspect import subprocess from django.template import Template from django.template import Context from django.conf import settings from arches.management.commands import utils def create_sqlfile(database_settings, path_to_file): context = Context(database_settings) postgres_version = subprocess.check_output(["psql", "--version"]) if int(postgres_version.split('.')[1]) >= 2: context['PID'] = "pid" else: context['PID'] = "procpid" t = Template( "SELECT pg_terminate_backend({{ PID }}) from pg_stat_activity where datname='{{ NAME }}';\n" "\n" "DROP DATABASE IF EXISTS {{ NAME }};\n" "\n" "CREATE DATABASE {{ NAME }}\n" " WITH ENCODING='UTF8'\n" " OWNER={{ USER }}\n" " CONNECTION LIMIT=-1;\n" "\n" ) utils.write_to_file(path_to_file, t.render(context));
import os import inspect import subprocess from django.template import Template from django.template import Context from django.conf import settings from arches.management.commands import utils def create_sqlfile(database_settings, path_to_file): context = Context(database_settings) postgres_version = subprocess.check_output(["psql", "--version"]) if int(postgres_version.split('.')[1]) >= 2: context['PID'] = "pid" else: context['PID'] = "procpid" t = Template( "SELECT pg_terminate_backend({{ PID }}) from pg_stat_activity where datname='{{ NAME }}';\n" "SELECT pg_terminate_backend({{ PID }}) from pg_stat_activity where datname='{{ POSTGIS_TEMPLATE }}';\n" "\n" "DROP DATABASE IF EXISTS {{ NAME }};\n" "\n" "CREATE DATABASE {{ NAME }}\n" " WITH ENCODING='UTF8'\n" " OWNER={{ USER }}\n" " TEMPLATE={{POSTGIS_TEMPLATE}}\n" " CONNECTION LIMIT=-1;\n" "\n" ) utils.write_to_file(path_to_file, t.render(context));
Update pysaml2 dependency to resolve bugs related to attribute filtering.
#!/usr/bin/env python """ setup.py """ from setuptools import setup, find_packages setup( name='SATOSA', version='0.4.1', description='Protocol proxy (SAML/OIDC).', author='DIRG', author_email='dirg@its.umu.se', license='Apache 2.0', url='https://github.com/its-dirg/SATOSA', packages=find_packages('src/'), package_dir={'': 'src'}, scripts=["tools/make_satosa_saml_metadata.py"], install_requires=[ "pluginbase", "future", "oic", "pyjwkest", "pysaml2 >= 4.0.2", "requests", "PyYAML", "pycrypto", "gunicorn", "Werkzeug" ], zip_safe=False, classifiers=[ "Programming Language :: Python :: 3 :: Only" "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", ] )
#!/usr/bin/env python """ setup.py """ from setuptools import setup, find_packages setup( name='SATOSA', version='0.4.1', description='Protocol proxy (SAML/OIDC).', author='DIRG', author_email='dirg@its.umu.se', license='Apache 2.0', url='https://github.com/its-dirg/SATOSA', packages=find_packages('src/'), package_dir={'': 'src'}, scripts=["tools/make_satosa_saml_metadata.py"], install_requires=[ "pluginbase", "future", "oic", "pyjwkest", "pysaml2 >= 4.0.0", "requests", "PyYAML", "pycrypto", "gunicorn", "Werkzeug" ], zip_safe=False, classifiers=[ "Programming Language :: Python :: 3 :: Only" "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", ] )
tests: Check bench mode==run with fixed block shape
from subprocess import check_call def run_cmd(command, problem, so, shape, nbpml, *extra): args = ["python", "../benchmarks/user/benchmark.py", command] args.extend(["-P", str(problem)]) args.extend(["-so", str(so)]) args.extend(["-d"] + [str(i) for i in shape]) args.extend(["--nbpml", str(nbpml)]) args.extend(extra) check_call(args) def test_test_tti(): run_cmd('test', 'tti', 4, [20, 20, 20], 5) def test_test_acoustic(): run_cmd('test', 'acoustic', 4, [20, 20, 20], 5) def test_run_acoustic_fixed_bs(): run_cmd('run', 'acoustic', 4, [20, 20, 20], 5, '-bs', '5', '5', '4')
import os from subprocess import check_call import pytest def run(command, problem, so, shape, nbpml, *extra): args = ["python", "../benchmarks/user/benchmark.py", command] args.extend(["-P", str(problem)]) args.extend(["-so", str(so)]) args.extend(["-d"] + [str(i) for i in shape]) args.extend(["--nbpml", str(nbpml)]) args.extend(extra) check_call(args) def test_test_tti(): run('test', 'tti', 4, [20, 20, 20], 5) def test_test_acoustic(): run('test', 'acoustic', 4, [20, 20, 20], 5) def test_run_acoustic_fixed_bs(): run('run', 'acoustic', 4, [20, 20, 20], 5, '-bs', '5', '5', '4')
Fix warning about transitionTo being deprecated
import EditorControllerMixin from 'ghost/mixins/editor-base-controller'; var EditorNewController = Ember.ObjectController.extend(EditorControllerMixin, { actions: { /** * Redirect to editor after the first save */ save: function () { var self = this; this._super().then(function (model) { if (model.get('id')) { self.transitionToRoute('editor.edit', model); } return model; }); } } }); export default EditorNewController;
import EditorControllerMixin from 'ghost/mixins/editor-base-controller'; var EditorNewController = Ember.ObjectController.extend(EditorControllerMixin, { actions: { /** * Redirect to editor after the first save */ save: function () { var self = this; this._super().then(function (model) { if (model.get('id')) { self.transitionTo('editor.edit', model); } return model; }); } } }); export default EditorNewController;
Add unique constraint on Meal name field
from __future__ import unicode_literals from django.db import models class Weekday(models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) def clean(self): """ Capitalize the first letter of the first word to avoid case insensitive duplicates for name field. """ self.name = self.name.capitalize() def save(self, *args, **kwargs): self.clean() return super(Weekday, self).save(*args, **kwargs) class Meal(models.Model): name = models.CharField(max_length=60, unique=True) start_time = models.TimeField() end_time = models.TimeField() def __str__(self): return self.name
from __future__ import unicode_literals from django.db import models class Weekday(models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) def clean(self): """ Capitalize the first letter of the first word to avoid case insensitive duplicates for name field. """ self.name = self.name.capitalize() def save(self, *args, **kwargs): self.clean() return super(Weekday, self).save(*args, **kwargs) class Meal(models.Model): name = models.CharField(max_length=60) start_time = models.TimeField() end_time = models.TimeField() def __str__(self): return self.name
Add google+ as alias for googleplus
var qs = require('querystring') module.exports = function (network, url, opts) { opts = opts || {} if (!linkfor[network]) throw new Error('Unsupported network ' + network) return linkfor[network](url, opts) } var linkfor = { facebook: function (url, opts) { var share = { u: url } if (opts.t) share.t = opts.t return 'https://www.facebook.com/sharer/sharer.php?' + qs.stringify(share) }, googleplus: function (url, opts) { var share = { url: url } return 'https://plus.google.com/share?' + qs.stringify(share) }, pinterest: function (url, opts) { var share = { url: url } if (opts.media) share.media = opts.media if (opts.description) share.description = opts.description return 'http://pinterest.com/pin/create/button/?' + qs.stringify(share) }, twitter: function (url, opts) { var share = { source: url } if (opts.text) share.text = opts.text if (opts.via) share.via = opts.via return 'https://twitter.com/intent/tweet?' + qs.stringify(share) } } linkfor['google+'] = linkfor.googleplus
var qs = require('querystring') module.exports = function (network, url, opts) { opts = opts || {} if (!linkfor[network]) throw new Error('Unsupported network ' + network) return linkfor[network](url, opts) } var linkfor = { facebook: function (url, opts) { var share = { u: url } if (opts.t) share.t = opts.t return 'https://www.facebook.com/sharer/sharer.php?' + qs.stringify(share) }, googleplus: function (url, opts) { var share = { url: url } return 'https://plus.google.com/share?' + qs.stringify(share) }, pinterest: function (url, opts) { var share = { url: url } if (opts.media) share.media = opts.media if (opts.description) share.description = opts.description return 'http://pinterest.com/pin/create/button/?' + qs.stringify(share) }, twitter: function (url, opts) { var share = { source: url } if (opts.text) share.text = opts.text if (opts.via) share.via = opts.via return 'https://twitter.com/intent/tweet?' + qs.stringify(share) } }
Update default image for borked images
/** * Wait until the DOM is ready. * * @param {Function} fn */ import { flatMap, keyBy } from 'lodash'; export function ready(fn) { if (document.readyState !== 'loading'){ fn(); } else { document.addEventListener('DOMContentLoaded', fn); } } export function calculateAge(date) { const birthdate = new Date(date); const today = Date.now(); const age = Math.floor((today - birthdate) / 31536000000); return age; }; export function getImageUrlFromProp(photoProp) { const photo_url = photoProp['url']; if (photo_url == "default") { return "https://www.dosomething.org/sites/default/files/JenBugError.png"; } else { return photo_url; } }; export function extractPostsFromSignups(signups) { const posts = keyBy(flatMap(signups, signup => { return signup.posts; }), 'id'); return posts; }
/** * Wait until the DOM is ready. * * @param {Function} fn */ import { flatMap, keyBy } from 'lodash'; export function ready(fn) { if (document.readyState !== 'loading'){ fn(); } else { document.addEventListener('DOMContentLoaded', fn); } } export function calculateAge(date) { const birthdate = new Date(date); const today = Date.now(); const age = Math.floor((today - birthdate) / 31536000000); return age; }; export function getImageUrlFromProp(photoProp) { const photo_url = photoProp['url']; if (photo_url == "default") { return "https://pics.onsizzle.com/bork-2411135.png"; } else { return photo_url; } }; export function extractPostsFromSignups(signups) { const posts = keyBy(flatMap(signups, signup => { return signup.posts; }), 'id'); return posts; }
Fix busted subcommand shortcut for runserver
package main import ( "github.com/cloudtools/ssh-cert-authority/util" "github.com/codegangsta/cli" "os" ) func main() { app := cli.NewApp() app.Name = "ssh-cert-authority" app.EnableBashCompletion = true app.Version = ssh_ca_util.BuildVersion app.Commands = []cli.Command{ { Name: "request", Aliases: []string{"r"}, Flags: requestCertFlags(), Usage: "Request a new certificate", Action: requestCert, }, { Name: "sign", Aliases: []string{"s"}, Flags: signCertFlags(), Usage: "Sign a certificate", Action: signCert, }, { Name: "get", Aliases: []string{"g"}, Flags: getCertFlags(), Usage: "Get a certificate", Action: getCert, }, { Name: "runserver", Flags: signdFlags(), Usage: "Get a certificate", Action: signCertd, }, } app.Run(os.Args) }
package main import ( "github.com/cloudtools/ssh-cert-authority/util" "github.com/codegangsta/cli" "os" ) func main() { app := cli.NewApp() app.Name = "ssh-cert-authority" app.EnableBashCompletion = true app.Version = ssh_ca_util.BuildVersion app.Commands = []cli.Command{ { Name: "request", Aliases: []string{"r"}, Flags: requestCertFlags(), Usage: "Request a new certificate", Action: requestCert, }, { Name: "sign", Aliases: []string{"s"}, Flags: signCertFlags(), Usage: "Sign a certificate", Action: signCert, }, { Name: "get", Aliases: []string{"g"}, Flags: getCertFlags(), Usage: "Get a certificate", Action: getCert, }, { Name: "runserver", Aliases: []string{"g"}, Flags: signdFlags(), Usage: "Get a certificate", Action: signCertd, }, } app.Run(os.Args) }
Add missing tx context for user verify tx store.
package userverify import ( "github.com/sirupsen/logrus" "github.com/skygeario/skygear-server/pkg/core/db" ) type safeStoreImpl struct { impl *storeImpl txContext db.SafeTxContext } func NewSafeStore( builder db.SQLBuilder, executor db.SQLExecutor, logger *logrus.Entry, txContext db.SafeTxContext, ) Store { return &safeStoreImpl{ impl: newStore(builder, executor, logger), txContext: txContext, } } func (s *safeStoreImpl) CreateVerifyCode(code *VerifyCode) error { s.txContext.EnsureTx() return s.impl.CreateVerifyCode(code) } func (s *safeStoreImpl) UpdateVerifyCode(code *VerifyCode) error { s.txContext.EnsureTx() return s.impl.UpdateVerifyCode(code) } func (s *safeStoreImpl) GetVerifyCodeByCode(code string, vCode *VerifyCode) error { s.txContext.EnsureTx() return s.impl.GetVerifyCodeByCode(code, vCode) }
package userverify import ( "github.com/sirupsen/logrus" "github.com/skygeario/skygear-server/pkg/core/db" ) type safeStoreImpl struct { impl *storeImpl txContext db.SafeTxContext } func NewSafeStore( builder db.SQLBuilder, executor db.SQLExecutor, logger *logrus.Entry, txContext db.SafeTxContext, ) Store { return &safeStoreImpl{ impl: newStore(builder, executor, logger), } } func (s *safeStoreImpl) CreateVerifyCode(code *VerifyCode) error { s.txContext.EnsureTx() return s.impl.CreateVerifyCode(code) } func (s *safeStoreImpl) UpdateVerifyCode(code *VerifyCode) error { s.txContext.EnsureTx() return s.impl.UpdateVerifyCode(code) } func (s *safeStoreImpl) GetVerifyCodeByCode(code string, vCode *VerifyCode) error { s.txContext.EnsureTx() return s.impl.GetVerifyCodeByCode(code, vCode) }
Set the cookie path properly. This is needed so that the cookies are valid for (only) us, and so that they're easier to track.
<?php require_once("tokenstrategy.php"); class CookieStrategy extends TokenStrategy { /** * the name for the cookie */ const COOKIENAME = "token"; public function getAuthToken() { return $_COOKIE[self::COOKIENAME]; } public function setNextAuthToken($token) { $expiry = Configuration::getInstance()->getConfig("cookie_expiry_time"); if ($expiry == null) { throw new Exception("no cookie expiry time found in config file", E_NO_EXPIRY_TIME); } setcookie( self::COOKIENAME, $token, time() + (int)$expiry, $_SERVER['SCRIPT_NAME'] ); } public function removeAuthToken() { setcookie (self::COOKIENAME, "", time() - 3600); } }
<?php require_once("tokenstrategy.php"); class CookieStrategy extends TokenStrategy { /** * the name for the cookie */ const COOKIENAME = "token"; public function getAuthToken() { return $_COOKIE[self::COOKIENAME]; } public function setNextAuthToken($token) { $expiry = Configuration::getInstance()->getConfig("cookie_expiry_time"); if ($expiry == null) { throw new Exception("no cookie expiry time found in config file", E_NO_EXPIRY_TIME); } setcookie( self::COOKIENAME, $token, time() + (int)$expiry ); } public function removeAuthToken() { setcookie (self::COOKIENAME, "", time() - 3600); } }
Update master version to 0.3-dev
#from distutils.core import setup from setuptools import setup descr = """cellom2tif: Convert Cellomics .C01 images to TIFF. This package uses the python-bioformats library to traverse directories and convert files in the Cellomics format (.C01) to TIFF files. """ DISTNAME = 'cellom2tif' DESCRIPTION = 'Convert Cellomics images to TIFF.' LONG_DESCRIPTION = descr MAINTAINER = 'Juan Nunez-Iglesias' MAINTAINER_EMAIL = 'juan.n@unimelb.edu.au' URL = 'https://github.com/jni/cellom2tif' LICENSE = 'BSD 3-clause' DOWNLOAD_URL = 'https://github.com/jni/cellom2tif' VERSION = '0.3-dev' PYTHON_VERSION = (2, 7) INST_DEPENDENCIES = {} if __name__ == '__main__': setup(name=DISTNAME, version=VERSION, url=URL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=MAINTAINER, author_email=MAINTAINER_EMAIL, license=LICENSE, packages=['cellom2tif'], install_requires=INST_DEPENDENCIES, scripts=["bin/cellom2tif"] )
#from distutils.core import setup from setuptools import setup descr = """cellom2tif: Convert Cellomics .C01 images to TIFF. This package uses the python-bioformats library to traverse directories and convert files in the Cellomics format (.C01) to TIFF files. """ DISTNAME = 'cellom2tif' DESCRIPTION = 'Convert Cellomics images to TIFF.' LONG_DESCRIPTION = descr MAINTAINER = 'Juan Nunez-Iglesias' MAINTAINER_EMAIL = 'juan.n@unimelb.edu.au' URL = 'https://github.com/jni/cellom2tif' LICENSE = 'BSD 3-clause' DOWNLOAD_URL = 'https://github.com/jni/cellom2tif' VERSION = '0.2-dev' PYTHON_VERSION = (2, 7) INST_DEPENDENCIES = {} if __name__ == '__main__': setup(name=DISTNAME, version=VERSION, url=URL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=MAINTAINER, author_email=MAINTAINER_EMAIL, license=LICENSE, packages=['cellom2tif'], install_requires=INST_DEPENDENCIES, scripts=["bin/cellom2tif"] )
Use extended shallow instead of mount from enzyme
import React from 'react' import ReactDOM from 'react-dom' import CircularProgressButton from './CircularProgressButton' import Button from 'material-ui/Button' import { createShallow } from 'material-ui/test-utils' let shallow; beforeAll(() => { shallow = createShallow({ dive: true }); }); it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<CircularProgressButton />, div); }); it('calls onClick method when loading is off and onClick is passed to the component', () => { const onClick = jest.fn() const wrapper = shallow(<CircularProgressButton onClick={onClick}/>) const button = wrapper.find(Button) expect(button.length).toBe(1) button.simulate('click') expect(onClick.mock.calls.length).toBe(1); }); it('does not call onClick method when loading is on', () => { const onClick = jest.fn() const wrapper = shallow(<CircularProgressButton status='loading' onClick={onClick}/>) const button = wrapper.find(Button) expect(button.length).toBe(1) button.simulate('click') expect(onClick.mock.calls.length).toBe(0); }); it('does not call onClick method when onClick is undefined', () => { const onClick = jest.fn() const wrapper = shallow(<CircularProgressButton status='loading'/>) const button = wrapper.find(Button) expect(button.length).toBe(1) button.simulate('click') expect(onClick.mock.calls.length).toBe(0); });
import React from 'react' import ReactDOM from 'react-dom' import CircularProgressButton from './CircularProgressButton' import Button from 'material-ui/Button' import { mount, shallow, render } from 'enzyme' it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<CircularProgressButton />, div); }); it('calls onClick method when loading is off and onClick is passed to the component', () => { const onClick = jest.fn() const wrapper = mount(<CircularProgressButton onClick={onClick}/>) const button = wrapper.find(Button) expect(button.length).toBe(1) button.simulate('click') expect(onClick.mock.calls.length).toBe(1); }); it('does not call onClick method when loading is on', () => { const onClick = jest.fn() const wrapper = mount(<CircularProgressButton status='loading' onClick={onClick}/>) const button = wrapper.find(Button) expect(button.length).toBe(1) button.simulate('click') expect(onClick.mock.calls.length).toBe(0); }); it('does not call onClick method when onClick is undefined', () => { const onClick = jest.fn() const wrapper = mount(<CircularProgressButton status='loading'/>) const button = wrapper.find(Button) expect(button.length).toBe(1) button.simulate('click') expect(onClick.mock.calls.length).toBe(0); });
Call hasNext in next to make sure we have an element available
package uk.co.jezuk.mango.iterators; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.NoSuchElementException; public class ChainIterator<T> implements Iterator<T> { private final Iterator<Iterator<T>> chain_; private Iterator<T> current_; public ChainIterator(final Object... iterables) { final List<Iterator<T>> list = Helpers.toIterators(iterables); chain_ = list.iterator(); current_ = chain_.hasNext() ? chain_.next() : null; } // ChainIterator public boolean hasNext() { if(current_ == null) return false; if(current_.hasNext()) return true; current_ = chain_.hasNext() ? chain_.next() : null; return hasNext(); } // hasNext public T next() { if (hasNext()) return current_.next(); throw new NoSuchElementException("ChainIterator is exhausted"); } // next public void remove() { throw new UnsupportedOperationException("uk.co.jezuk.mango.ChainIterator does not support the remove method"); } // remove } // ChainIterator
package uk.co.jezuk.mango.iterators; import java.util.Iterator; import java.util.List; import java.util.ArrayList; public class ChainIterator<T> implements Iterator<T> { private final Iterator<Iterator<T>> chain_; private Iterator<T> current_; public ChainIterator(final Object... iterables) { final List<Iterator<T>> list = Helpers.toIterators(iterables); chain_ = list.iterator(); current_ = chain_.hasNext() ? chain_.next() : null; } // ChainIterator public boolean hasNext() { if(current_ == null) return false; if(current_.hasNext()) return true; current_ = chain_.hasNext() ? chain_.next() : null; return hasNext(); } // hasNext public T next() { return current_.next(); } // next public void remove() { throw new UnsupportedOperationException("uk.co.jezuk.mango.ChainIterator does not support the remove method"); } // remove } // ChainIterator
Replace the double arrow on collection with circle
<div class="col-md-12"> <div class="a-note"> <div class="layout"> <div class="layout-center" style="width: 100px"> <div> <a href="/notes/{{$notes->id}}" class="note-title"> <i class="fa fa-circle-o"></i> </a> </div> </div> <div class="layout-center"> <div class="text-capitalize text-left"> <a href="" class="note-title"> {{ $notes->notes_title }} </a> </div> </div> </div> </div> </div>
<div class="col-md-12"> <div class="a-note"> <div class="layout"> <div class="layout-center"> <div class="text-capitalize text-left"> <a href="/notes/{{$notes->id}}" class="note-title"> {{ $notes->notes_title }} </a> </div> </div> <div class="layout-center" style="width: 100px"> <div class="text-capitalize text-right"> <a href="/notes/{{$notes->id}}" class="note-title direction"> <i class="fa fa-angle-double-right" aria-hidden="true"></i> </a> </div> </div> </div> </div> </div>
Clean up the AuthComplete API a little
import logging from django.contrib import messages from django.http import HttpResponseRedirect, HttpResponse from django.utils.encoding import force_text from django.views.generic.base import View from social_auth.exceptions import AuthFailed from social_auth.views import complete logger = logging.getLogger(__name__) class AuthComplete(View): def get(self, request, *args, **kwargs): backend = kwargs.pop('backend') try: return complete(request, backend, *args, **kwargs) except AuthFailed as e: logger.error(e) messages.error(request, self.get_error_message()) return HttpResponseRedirect(self.get_faiure_url()) def get_error_message(self): if self.error_message: return self.error_message return "Your Google Apps domain isn't authorized for this app" def get_failure_url(self): if self.failure_url: return force_text(self.failure_url) return '/' class LoginError(View): def get(self, request, *args, **kwargs): return HttpResponse(status=401)
import logging from django.contrib import messages from django.http import HttpResponseRedirect, HttpResponse from django.views.generic.base import View from social_auth.exceptions import AuthFailed from social_auth.views import complete logger = logging.getLogger(__name__) class AuthComplete(View): def get(self, request, *args, **kwargs): backend = kwargs.pop('backend') try: return complete(request, backend, *args, **kwargs) except AuthFailed as e: logger.error(e) messages.error(request, "Your Google Apps domain isn't authorized for this app") return HttpResponseRedirect('/') class LoginError(View): def get(self, request, *args, **kwargs): return HttpResponse(status=401)
chore(gulp): Fix build behavior by returning streams.
'use strict'; var gulp = require('gulp'); var jscs = require('gulp-jscs'); var jshint = require('gulp-jshint'); var gulpMocha = require('gulp-mocha'); var javascriptGlobs = ['*.js', 'src/**/*.js', 'test/**/*.js']; gulp.task('style', function () { return gulp.src(javascriptGlobs) .pipe(jscs()) .pipe(jscs.reporter()) .pipe(jscs.reporter('fail')); }); gulp.task('lint', function () { return gulp.src(javascriptGlobs) .pipe(jshint('.jshintrc')) .pipe(jshint.reporter()) .pipe(jshint.reporter('fail')); }); gulp.task('test:unit', function () { return gulp.src('test/unit/**/*.js') .pipe(gulpMocha()); }); gulp.task('test:integration', function () { return gulp.src('test/integration/**/*.js') .pipe(gulpMocha()); }); gulp.task('test', ['test:unit', 'test:integration']); gulp.task('build', ['lint', 'style', 'test']); gulp.task('default', ['build']);
'use strict'; var gulp = require('gulp'); var jscs = require('gulp-jscs'); var jshint = require('gulp-jshint'); var gulpMocha = require('gulp-mocha'); var javascriptGlobs = ['*.js', 'src/**/*.js', 'test/**/*.js']; gulp.task('style', function () { gulp.src(javascriptGlobs) .pipe(jscs()) .pipe(jscs.reporter()) .pipe(jscs.reporter('fail')); }); gulp.task('lint', function () { gulp.src(javascriptGlobs) .pipe(jshint('.jshintrc')) .pipe(jshint.reporter()) .pipe(jshint.reporter('fail')); }); gulp.task('test:unit', function () { gulp.src('test/unit/**/*.js') .pipe(gulpMocha()); }); gulp.task('test:integration', function () { gulp.src('test/integration/**/*.js') .pipe(gulpMocha()); }); gulp.task('test', ['test:unit', 'test:integration']); gulp.task('build', ['lint', 'style', 'test'], function () { gulp.src('/'); }); gulp.task('default', ['build']);
Remove sources from source maps.
const path = require('path'); const webpack = require('webpack'); const glob = require('glob'); const pkg = require('./package.json'); function newConfig() { return { resolve: { extensions: ['.coffee'] }, module: { rules: [ {test: /\.coffee$/, loader: 'coffee-loader'} ] }, devtool: 'nosources-source-map', output: { filename: '[name].js', chunkFilename: '[id][name].js', path: path.resolve(__dirname, 'dist') }, plugins: [ new webpack.DefinePlugin({ VERSION: JSON.stringify(pkg.version) }), new webpack.optimize.UglifyJsPlugin({ include: /\.min\.js$/, sourceMap: true }) ] } }; var client = newConfig(); client.entry = { 'client': './src/client.coffee', 'client.min': './src/client.coffee' }; client.output.library = ['airbrakeJs', 'Client']; var jquery = newConfig(); jquery.entry = { 'instrumentation/jquery': './src/instrumentation/jquery.coffee', 'instrumentation/jquery.min': './src/instrumentation/jquery.coffee', } jquery.output.library = ['airbrakeJs', 'instrumentation', 'jquery']; module.exports = [client, jquery];
const path = require('path'); const webpack = require('webpack'); const glob = require('glob'); const pkg = require('./package.json'); function newConfig() { return { resolve: { extensions: ['.coffee'] }, module: { rules: [ {test: /\.coffee$/, loader: 'coffee-loader'} ] }, devtool: 'source-map', output: { filename: '[name].js', chunkFilename: '[id][name].js', path: path.resolve(__dirname, 'dist') }, plugins: [ new webpack.DefinePlugin({ VERSION: JSON.stringify(pkg.version) }), new webpack.optimize.UglifyJsPlugin({ include: /\.min\.js$/, sourceMap: true }) ] } }; var client = newConfig(); client.entry = { 'client': './src/client.coffee', 'client.min': './src/client.coffee' }; client.output.library = ['airbrakeJs', 'Client']; var jquery = newConfig(); jquery.entry = { 'instrumentation/jquery': './src/instrumentation/jquery.coffee', 'instrumentation/jquery.min': './src/instrumentation/jquery.coffee', } jquery.output.library = ['airbrakeJs', 'instrumentation', 'jquery']; module.exports = [client, jquery];
Remove --profile tag from debugging
//https://nvbn.github.io/2015/06/19/jekyll-browsersync/ var gulp = require('gulp'); var shell = require('gulp-shell'); var browserSync = require('browser-sync').create(); // Task for building blog when something changed: gulp.task('build', shell.task(['bundle exec jekyll build --watch'])); // Task for serving blog with Browsersync gulp.task('serve', function () { browserSync.init({ server: {baseDir: '_site/'}, "notify": false, }); // Reloads page when some of the already built files changed: //Because I'm not using incremental, I can have it watch a single file. //This prevents a plethora of reloads being sent. gulp.watch('./_site/sitemap.xml').on('change', browserSync.reload); }); gulp.task('default', ['build', 'serve']);
//https://nvbn.github.io/2015/06/19/jekyll-browsersync/ var gulp = require('gulp'); var shell = require('gulp-shell'); var browserSync = require('browser-sync').create(); // Task for building blog when something changed: gulp.task('build', shell.task(['bundle exec jekyll build --watch --profile'])); // Task for serving blog with Browsersync gulp.task('serve', function () { browserSync.init({ server: {baseDir: '_site/'}, "notify": false, }); // Reloads page when some of the already built files changed: //Because I'm not using incremental, I can have it watch a single file. //This prevents a plethora of reloads being sent. gulp.watch('./_site/sitemap.xml').on('change', browserSync.reload); }); gulp.task('default', ['build', 'serve']);
Deal with commodity display for contracts
var path = require('path'); var rootPath = path.normalize(__dirname + '/../../'); module.exports = { local: { baseUrl: 'http://localhost:3030', db: 'mongodb://localhost/rp_local', rootPath: rootPath, port: process.env.PORT || 3030 }, staging : { baseUrl: 'http://dev.resourceprojects.org', //db: '@aws-us-east-1-portal.14.dblayer.com:10669/rp_dev?ssl=true', db: '@aws-us-east-1-portal.14.dblayer.com:10669,aws-us-east-1-portal.13.dblayer.com:10499/rp_dev?ssl=true', rootPath: rootPath, port: process.env.PORT || 80 } };
var path = require('path'); var rootPath = path.normalize(__dirname + '/../../'); module.exports = { local: { baseUrl: 'http://localhost:3008', db: 'mongodb://localhost/rp_local', rootPath: rootPath, port: process.env.PORT || 3008 }, staging : { baseUrl: 'http://dev.resourceprojects.org', //db: '@aws-us-east-1-portal.14.dblayer.com:10669/rp_dev?ssl=true', db: '@aws-us-east-1-portal.14.dblayer.com:10669,aws-us-east-1-portal.13.dblayer.com:10499/rp_dev?ssl=true', rootPath: rootPath, port: process.env.PORT || 80 } };
Rewrite test to use ThrowableCaptor
package com.codeaffine.extras.jdt.internal.prefs; import static com.codeaffine.test.util.lang.ThrowableCaptor.thrownBy; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.services.IEvaluationService; import org.junit.Before; import org.junit.Test; public class ExpressionEvaluatorTest { private IWorkbench workbench; @Before public void setUp() { workbench = mock( IWorkbench.class ); } @Test public void testEvaluate() { IEvaluationService evaluationService = mock( IEvaluationService.class ); when( workbench.getService( IEvaluationService.class ) ).thenReturn( evaluationService ); new ExpressionEvaluator( workbench ).evaluate(); verify( evaluationService ).requestEvaluation( PreferencePropertyTester.PROP_IS_TRUE ); } @Test public void testEvaluateWithNullWorkbench() { Throwable throwable = thrownBy( () -> new ExpressionEvaluator( null ).evaluate() ); assertThat( throwable ).isNull(); } @Test public void testEvaluateWithoutEvaluationService() { new ExpressionEvaluator( workbench ).evaluate(); verify( workbench ).getService( IEvaluationService.class ); } }
package com.codeaffine.extras.jdt.internal.prefs; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.services.IEvaluationService; import org.junit.Before; import org.junit.Test; public class ExpressionEvaluatorTest { private IWorkbench workbench; @Before public void setUp() { workbench = mock( IWorkbench.class ); } @Test public void testEvaluate() { IEvaluationService evaluationService = mock( IEvaluationService.class ); when( workbench.getService( IEvaluationService.class ) ).thenReturn( evaluationService ); new ExpressionEvaluator( workbench ).evaluate(); verify( evaluationService ).requestEvaluation( PreferencePropertyTester.PROP_IS_TRUE ); } @Test public void testEvaluateWithNullworkbench() { try { new ExpressionEvaluator( null ).evaluate(); } catch( RuntimeException notExpected ) { fail(); } } @Test public void testEvaluateWithoutEvaluationService() { new ExpressionEvaluator( workbench ).evaluate(); verify( workbench ).getService( IEvaluationService.class ); } }
Fix style error at command map imports.
package fi.helsinki.cs.tmc.cli.command; import fi.helsinki.cs.tmc.cli.Application; import java.util.HashMap; import java.util.Map; /** * Class creates a map for commands. */ public class CommandMap { private Map<String, Command> commands; /** * Constructor. */ public CommandMap(Application app) { this.commands = new HashMap<>(); createCommand(new TestCommand(app)); createCommand(new HelpCommand(app)); } private void createCommand(Command command) { this.commands.put(command.getName(), command); } /** * Get command by default name. * @param name * @return Command */ public Command getCommand(String name) { return commands.get(name); } public Map<String, Command> getCommands() { return this.commands; } }
package fi.helsinki.cs.tmc.cli.command; import fi.helsinki.cs.tmc.cli.Application; import java.util.HashMap; import java.util.Map; /** * Class creates a map for commands. */ public class CommandMap { private Map<String, Command> commands; /** * Constructor. */ public CommandMap(Application app) { this.commands = new HashMap<>(); createCommand(new TestCommand(app)); createCommand(new HelpCommand(app)); } private void createCommand(Command command) { this.commands.put(command.getName(), command); } /** * Get command by default name. * @param name * @return Command */ public Command getCommand(String name) { return commands.get(name); } public Map<String, Command> getCommands() { return this.commands; } }
Implement method to start service.
package com.github.aureliano.achmed.os.service; import org.apache.log4j.Logger; import com.github.aureliano.achmed.command.CommandFacade; import com.github.aureliano.achmed.command.CommandResponse; import com.github.aureliano.achmed.helper.StringHelper; public class RedHatService extends LinuxService { private static final Logger logger = Logger.getLogger(RedHatService.class); private static final String SERVICE = "/sbin/service"; public RedHatService() { super(); } @Override public CommandResponse start() { if (this.isRunning()) { logger.debug("Service " + super.properties.getName() + " is already running."); return null; } if (StringHelper.isEmpty(super.properties.getBinary())) { return CommandFacade.executeCommand(SERVICE, super.properties.getName(), "start"); } return super.start(); } @Override public boolean isRunning() { if ((super.properties.getHasStatus() != null) && (super.properties.getHasStatus())) { CommandResponse res = CommandFacade.executeCommand(SERVICE, super.properties.getName(), "status"); return (res.getExitStatusCode() == 0); } return super.isRunning(); } @Override public CommandResponse enableBootstrap() { throw new UnsupportedOperationException("Not implemented yet."); } @Override public CommandResponse disableBootstrap() { throw new UnsupportedOperationException("Not implemented yet."); } @Override public boolean isEnabledInBootstrap() { throw new UnsupportedOperationException("Not implemented yet."); } }
package com.github.aureliano.achmed.os.service; import org.apache.log4j.Logger; import com.github.aureliano.achmed.command.CommandFacade; import com.github.aureliano.achmed.command.CommandResponse; public class RedHatService extends LinuxService { private static final Logger logger = Logger.getLogger(RedHatService.class); private static final String SERVICE = "/sbin/service"; public RedHatService() { super(); } @Override public boolean isRunning() { if ((super.properties.getHasStatus() != null) && (super.properties.getHasStatus())) { CommandResponse res = CommandFacade.executeCommand(SERVICE, super.properties.getName(), "status"); return (res.getExitStatusCode() == 0); } return super.isRunning(); } @Override public CommandResponse enableBootstrap() { throw new UnsupportedOperationException("Not implemented yet."); } @Override public CommandResponse disableBootstrap() { throw new UnsupportedOperationException("Not implemented yet."); } @Override public boolean isEnabledInBootstrap() { throw new UnsupportedOperationException("Not implemented yet."); } }
Implement bluebird instead of Q inside demo userDAO
"use strict"; var loki = require('lokijs'); var _ = require('lodash'); var Promise = require('bluebird'); // variable to hold the singleton instance, if used in that manner var userDAOInstance = undefined; // // User Data Access Object // // Constructor function UserDAO(dbName) { // Define database name dbName = (dbName != '') ? dbName : 'janux.people.db'; // Create db this._db = new loki(dbName); // Add users collection this._users = this._db.addCollection('users'); } // Get User Object by id UserDAO.prototype.findUserById = function (userId, callback) { var users = this._users.findOne( { userId:userId }); return new Promise(function(resolve){ resolve( users ); }).asCallback(callback); }; // Get User Object by username UserDAO.prototype.findUserByName = function (userName, callback) { var users = this._users.findOne( { username:userName } ); return new Promise(function(resolve){ resolve( users ); }).asCallback(callback); }; // Add new User Object UserDAO.prototype.addUser = function (aUserObj) { this._users.insert(aUserObj); }; exports.createInstance = function() { return new UserDAO(); }; exports.singleton = function() { // if the singleton has not yet been instantiated, do so if ( !_.isObject(userDAOInstance) ) { userDAOInstance = new UserDAO(); } return userDAOInstance; };
"use strict"; var loki = require('lokijs'); var _ = require('lodash'); var Q = require('q'); // variable to hold the singleton instance, if used in that manner var userDAOInstance = undefined; // // User Data Access Object // // Constructor function UserDAO(dbName) { // Define database name dbName = (dbName != '') ? dbName : 'janux.people.db'; // Create db this._db = new loki(dbName); // Add users collection this._users = this._db.addCollection('users'); } // Get User Object by id UserDAO.prototype.getUserById = function (userId, callback) { return Q.when( this._users.findOne( { userId:userId } ) ); }; // Get User Object by username UserDAO.prototype.getUserByName = function (userName) { return Q.when( this._users.findOne( { username:userName } ) ); }; // Add new User Object UserDAO.prototype.addUser = function (aUserObj) { this._users.insert(aUserObj); }; exports.createInstance = function() { return new UserDAO(); }; exports.singleton = function() { // if the singleton has not yet been instantiated, do so if ( !_.isObject(userDAOInstance) ) { userDAOInstance = new UserDAO(); } return userDAOInstance; };
Modify created_at and updated_at to millisecond
#!/usr/bin/env python # -*- coding: utf-8 -*- import cgi import sqlite3 import time import config def valid(qs): required_keys = ['title', 'comment', 'posted_by', 'localite', 'latitude', 'longitude'] return all([qs.has_key(k) for k in required_keys]) def post(title, comment, posted_by, localite, latitude, longitude): rate = 0 created_at = int(time.time()*1000) updated_at = created_at sql = u'insert into posts (id, title, comment, posted_by, localite, rate, latitude, longitude, created_at, updated_at) values (null,?,?,?,?,?,?,?,?,?);' con = sqlite3.connect(config.db_path, isolation_level=None) con.execute(sql, (title, comment, posted_by, localite, rate, latitude, longitude, created_at, updated_at)) con.close() if __name__ == '__main__': import utils qs = utils.fs2dict(cgi.FieldStorage()) if valid(qs): keys = ['title', 'comment', 'posted_by', 'localite', 'latitude', 'longitude'] query_string = [qs[k].decode('utf-8') for k in keys] post(*query_string) result = '{"message": "Successfully posted!"}' else: result = '{"message": "Invalid query string"}' utils.cgi_header() print result
#!/usr/bin/env python # -*- coding: utf-8 -*- import cgi import sqlite3 import time import config def valid(qs): required_keys = ['title', 'comment', 'posted_by', 'localite', 'latitude', 'longitude'] return all([qs.has_key(k) for k in required_keys]) def post(title, comment, posted_by, localite, latitude, longitude): rate = 0 created_at = int(time.time()) updated_at = created_at sql = u'insert into posts (id, title, comment, posted_by, localite, rate, latitude, longitude, created_at, updated_at) values (null,?,?,?,?,?,?,?,?,?);' con = sqlite3.connect(config.db_path, isolation_level=None) con.execute(sql, (title, comment, posted_by, localite, rate, latitude, longitude, created_at, updated_at)) con.close() if __name__ == '__main__': import utils qs = utils.fs2dict(cgi.FieldStorage()) if valid(qs): keys = ['title', 'comment', 'posted_by', 'localite', 'latitude', 'longitude'] query_string = [qs[k].decode('utf-8') for k in keys] post(*query_string) result = '{"message": "Successfully posted!"}' else: result = '{"message": "Invalid query string"}' utils.cgi_header() print result
Stop test run if config loading errors
#! /usr/bin/env node 'use strict'; var doctest = require('../lib/doctest'); var fs = require('fs'); var glob = require('glob'); var CONFIG_FILEPATH = process.cwd() + '/.markdown-doctest-setup.js'; var DEFAULT_GLOB = '**/*.+(md|markdown)'; var DEFAULT_IGNORE = ['**/node_modules/**', '**/bower_components/**']; function main () { var userGlob = process.argv[2]; var config = {require: {}}; if (fs.existsSync(CONFIG_FILEPATH)) { try { config = require(CONFIG_FILEPATH); } catch (e) { console.log('Error running .markdown-doctest-setup.js:'); console.error(e); return; } } glob( userGlob || DEFAULT_GLOB, {ignore: DEFAULT_IGNORE}, run ); function run (err, files) { if (err) { console.trace(err); } var results = doctest.runTests(files, config); console.log('\n'); doctest.printResults(results); var failures = results.filter(function (result) { return result.status === 'fail'; }); if (failures.length > 0) { process.exitCode = 127; } } } main();
#! /usr/bin/env node 'use strict'; var doctest = require('../lib/doctest'); var fs = require('fs'); var glob = require('glob'); var CONFIG_FILEPATH = process.cwd() + '/.markdown-doctest-setup.js'; var DEFAULT_GLOB = '**/*.+(md|markdown)'; var DEFAULT_IGNORE = ['**/node_modules/**', '**/bower_components/**']; function main () { var userGlob = process.argv[2]; var config = {require: {}}; if (fs.existsSync(CONFIG_FILEPATH)) { try { config = require(CONFIG_FILEPATH); } catch (e) { console.log('Error running setup:'); console.trace(e); } } glob( userGlob || DEFAULT_GLOB, {ignore: DEFAULT_IGNORE}, run ); function run (err, files) { if (err) { console.trace(err); } var results = doctest.runTests(files, config); console.log('\n'); doctest.printResults(results); var failures = results.filter(function (result) { return result.status === 'fail'; }); if (failures.length > 0) { process.exitCode = 127; } } } main();
Fix error, need to add PressAddStory button
import React, { Component } from 'react'; import { StyleSheet, Text, View, TouchableHighlight, } from 'react-native'; import I18n from 'react-native-i18n' class Profile extends Component{ _onPressAddStory(){ } render() { return ( <View style={styles.container}> <Text style={styles.title}>Smeagles {I18n.t('profile')}</Text> <Text style={styles.body}> {JSON.stringify(this.props.users)}</Text> <Text style={styles.body}> Temporary for styling Skeleton </Text> <TouchableHighlight onPress={this._onPressAddStory.bind(this)} style={styles.button}> <Text style={styles.buttonText}> Add Story </Text> </TouchableHighlight> </View> ) } }; var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, title: { marginTop: 25, fontSize: 20, alignSelf: 'center', margin: 40, }, body: { flex: 0.1, } }); module.exports = Profile;
import React, { Component } from 'react'; import { StyleSheet, Text, View, TouchableHighlight, } from 'react-native'; import I18n from 'react-native-i18n' class Profile extends Component{ async _onPressAddStory(){ try { } } render() { return ( <View style={styles.container}> <Text style={styles.title}>Smeagles {I18n.t('profile')}</Text> <Text style={styles.body}> {JSON.stringify(this.props.users)}</Text> <Text style={styles.body}> Temporary for styling Skeleton </Text> <TouchableHighlight onPress={this._onPressAddStory}.bind(this)} style={styles.button}> <Text style={styles.buttonText}> </Text> </TouchableHighlight> </View> ) } }; var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, title: { marginTop: 25, fontSize: 20, alignSelf: 'center', margin: 40, }, body: { flex: 0.1, } }); module.exports = Profile;
Use omitempty tag for storage & network arrays
// Copyright © 2016 Zlatko Čalušić // // Use of this source code is governed by an MIT-style license that can be found in the LICENSE file. // Package sysinfo is a pure Go library providing Linux OS / kernel / hardware system information. package sysinfo // SysInfo struct encapsulates all other information structs. type SysInfo struct { Meta Meta `json:"sysinfo"` Node Node `json:"node"` OS OS `json:"os"` Kernel Kernel `json:"kernel"` Product Product `json:"product"` Board Board `json:"board"` Chassis Chassis `json:"chassis"` BIOS BIOS `json:"bios"` CPU CPU `json:"cpu"` Memory Memory `json:"memory"` Storage []StorageDevice `json:"storage,omitempty"` Network []NetworkDevice `json:"network,omitempty"` } // GetSysInfo gathers all available system information. func (si *SysInfo) GetSysInfo() { // Meta info si.getMetaInfo() // Software info si.getNodeInfo() si.getOSInfo() si.getKernelInfo() // Hardware info si.getProductInfo() si.getBoardInfo() si.getChassisInfo() si.getBIOSInfo() si.getCPUInfo() si.getMemoryInfo() si.getStorageInfo() si.getNetworkInfo() }
// Copyright © 2016 Zlatko Čalušić // // Use of this source code is governed by an MIT-style license that can be found in the LICENSE file. // Package sysinfo is a pure Go library providing Linux OS / kernel / hardware system information. package sysinfo // SysInfo struct encapsulates all other information structs. type SysInfo struct { Meta Meta `json:"sysinfo"` Node Node `json:"node"` OS OS `json:"os"` Kernel Kernel `json:"kernel"` Product Product `json:"product"` Board Board `json:"board"` Chassis Chassis `json:"chassis"` BIOS BIOS `json:"bios"` CPU CPU `json:"cpu"` Memory Memory `json:"memory"` Storage []StorageDevice `json:"storage"` Network []NetworkDevice `json:"network"` } // GetSysInfo gathers all available system information. func (si *SysInfo) GetSysInfo() { // Meta info si.getMetaInfo() // Software info si.getNodeInfo() si.getOSInfo() si.getKernelInfo() // Hardware info si.getProductInfo() si.getBoardInfo() si.getChassisInfo() si.getBIOSInfo() si.getCPUInfo() si.getMemoryInfo() si.getStorageInfo() si.getNetworkInfo() }
Implement throw error when no function found
import * as PASTEL_FUNC from '../../functions/functions.js'; import CraftyBlock from './CraftyBlock.js'; export default class CraftyBlockSpec { constructor(name, type, parameters = [], library="", docstring="") { this.name = name; this.type = type; this.parameters = parameters; this.docstring = docstring; this.library = library; } static functionWithName(name) { let info = [ ...PASTEL_FUNC.STANDARD, ...PASTEL_FUNC.MATH].find( functionInfo => { return functionInfo.name === name; }); if (!info) { throw new Error("Not able to find function with name: " + name); } return new CraftyBlockSpec(info.name, CraftyBlock.FUNCTION, info.parameters, "", info.docstring); } }
import * as PASTEL_FUNC from '../../functions/functions.js'; import CraftyBlock from './CraftyBlock.js'; export default class CraftyBlockSpec { constructor(name, type, parameters = [], library="", docstring="") { this.name = name; this.type = type; this.parameters = parameters; this.docstring = docstring; this.library = library; } static functionWithName(name) { let info = [ ...PASTEL_FUNC.STANDARD, ...PASTEL_FUNC.MATH].find( functionInfo => { return functionInfo.name === name; }); return new CraftyBlockSpec(info.name, CraftyBlock.FUNCTION, info.parameters, "", info.docstring); } }
Validate that the request body is unchanged by default
package rapi_test import ( "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/waltzofpearls/relay-api/rapi" ) func TestEndpointUnchanged(t *testing.T) { var requestContent string expectedResult := `test` ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { req, _ := ioutil.ReadAll(r.Body) requestContent = string(req) w.Write([]byte(expectedResult)) })) defer ts.Close() conf := rapi.NewConfig() conf.Backend.Address = strings.TrimPrefix(ts.URL, "http://") api := rapi.New(conf) require.NotNil(t, api) ep := rapi.NewEndpoint(api, "POST", "/foo") assert.NotNil(t, ep) fixture := `{"One":"this is the one", "Two":"this is the second"}` req, err := http.NewRequest("POST", "/foo", strings.NewReader(fixture)) require.Nil(t, err) require.NotNil(t, req) resp := httptest.NewRecorder() require.NotNil(t, resp) ep.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) assert.Equal(t, fixture, requestContent, "request body is unchanged") }
package rapi_test import ( "net/http" "net/http/httptest" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/waltzofpearls/relay-api/rapi" ) func TestEndpoint(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) defer ts.Close() conf := rapi.NewConfig() conf.Backend.Address = strings.TrimPrefix(ts.URL, "http://") api := rapi.New(conf) require.NotNil(t, api) ep := rapi.NewEndpoint(api, "GET", "/foo") assert.NotNil(t, ep) req, err := http.NewRequest("GET", "/foo", nil) require.Nil(t, err) require.NotNil(t, req) resp := httptest.NewRecorder() require.NotNil(t, resp) ep.ServeHTTP(resp, req) }
Add paramiko to install_requires since libcloud deploy_node() requires it.
#!/bin/env python # -*- coding: utf8 -*- from setuptools import setup setup( name='fedimg', version='0.0.1', description='Service to automatically upload built Fedora images \ to internal and external cloud providers.', classifiers=[ "Programming Language :: Python :: 2", "License :: OSI Approved :: GNU Affero General Public License \ v3 or later (AGPLv3+)", ], keywords='python Fedora cloud image uploader', author='David Gay', author_email='oddshocks@riseup.net', url='https://github.com/oddshocks/fedimg', license='AGPLv3+', include_package_data=True, zip_safe=False, install_requires=["fedmsg", "apache-libcloud", "paramiko"], packages=[], entry_points=""" [moksha.consumer] kojiconsumer = fedimg.consumers:KojiConsumer """, )
#!/bin/env python # -*- coding: utf8 -*- from setuptools import setup setup( name='fedimg', version='0.0.1', description='Service to automatically upload built Fedora images \ to internal and external cloud providers.', classifiers=[ "Programming Language :: Python :: 2", "License :: OSI Approved :: GNU Affero General Public License \ v3 or later (AGPLv3+)", ], keywords='python Fedora cloud image uploader', author='David Gay', author_email='oddshocks@riseup.net', url='https://github.com/oddshocks/fedimg', license='AGPLv3+', include_package_data=True, zip_safe=False, install_requires=["fedmsg", "apache-libcloud"], packages=[], entry_points=""" [moksha.consumer] kojiconsumer = fedimg.consumers:KojiConsumer """, )
Handle room users case when not in room
Template.roomView.helpers({ room: function () { return Rooms.findOne({_id: Session.get('currentRoom')}); }, roomUsers: function () { var room = Rooms.findOne({_id: Session.get('currentRoom')}); if(room) { return Meteor.users.find({_id: {$in: room.users}}); } else{ return []; } }, currentRooms: function () { return Rooms.find({users: Meteor.userId()}); }, currentRoom: function () { return Session.get('currentRoom'); }, availableRooms: function () { return Rooms.find(); } }); Template.roomView.events({ 'click #loadMore': function (e) { Session.set('messageLimit', Session.get('messageLimit') + 20); e.preventDefault(); } }); Template.roomView.rendered = function () { Meteor.call('setSeen', Session.get('currentRoom')); Meteor.setTimeout(scrollChatToBottom, 100); }; Template.roomView.created = function () { Deps.autorun(function () { Meteor.subscribe('messages', Session.get('currentRoom'), Session.get('messageLimit')); Meteor.subscribe('feedbackMessages', Session.get('currentRoom')); }); };
Template.roomView.helpers({ room: function () { return Rooms.findOne({_id: Session.get('currentRoom')}); }, roomUsers: function () { var room = Rooms.findOne({_id: Session.get('currentRoom')}); return Meteor.users.find({_id: {$in: room.users}}); }, currentRooms: function () { return Rooms.find({users: Meteor.userId()}); }, currentRoom: function () { return Session.get('currentRoom'); }, availableRooms: function () { return Rooms.find(); } }); Template.roomView.events({ 'click #loadMore': function (e) { Session.set('messageLimit', Session.get('messageLimit') + 20); e.preventDefault(); } }); Template.roomView.rendered = function () { Meteor.call('setSeen', Session.get('currentRoom')); Meteor.setTimeout(scrollChatToBottom, 100); }; Template.roomView.created = function () { Deps.autorun(function () { Meteor.subscribe('messages', Session.get('currentRoom'), Session.get('messageLimit')); Meteor.subscribe('feedbackMessages', Session.get('currentRoom')); }); };
[Core] Fix filtering scenarios loaded from jar I am running cucumber tests with features loaded from classpath:, like this: ``` java -cp fatjar.jar cucumber.api.cli.Main "classpath:features/FeatureWithExamples.feature:64" ``` However, when cucumber parses this path and creates a ZipResource from it, it adds an extra slash. This becomes a problem down the line, when LinePredicate tries to filter out the pickles. Instead of filtering the pickles out, it just lets all of the though the filter. Changed the ZipResource to preserve the original path of the zipped entity.
package cucumber.runtime.io; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import static io.cucumber.core.model.Classpath.CLASSPATH_SCHEME_PREFIX; class ZipResource implements Resource { private final ZipFile jarFile; private final ZipEntry jarEntry; ZipResource(ZipFile jarFile, ZipEntry jarEntry) { this.jarFile = jarFile; this.jarEntry = jarEntry; } @Override public URI getPath() { return URI.create(CLASSPATH_SCHEME_PREFIX + jarEntry.getName()); } @Override public InputStream getInputStream() throws IOException { return jarFile.getInputStream(jarEntry); } }
package cucumber.runtime.io; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import static io.cucumber.core.model.Classpath.CLASSPATH_SCHEME_PREFIX; class ZipResource implements Resource { private final ZipFile jarFile; private final ZipEntry jarEntry; ZipResource(ZipFile jarFile, ZipEntry jarEntry) { this.jarFile = jarFile; this.jarEntry = jarEntry; } @Override public URI getPath() { return URI.create(CLASSPATH_SCHEME_PREFIX + "/" + jarEntry.getName()); } @Override public InputStream getInputStream() throws IOException { return jarFile.getInputStream(jarEntry); } }
Fix wrong URL for success login
from django.views.generic import FormView, RedirectView from django.contrib.auth.forms import AuthenticationForm from django.core.urlresolvers import reverse from django.contrib.auth import login, logout class LoginView(FormView): template_name = 'homepage/login.html' form_class = AuthenticationForm def form_valid(self, form): user = form.get_user() login(self.request, user) return super().form_valid(form) def get_success_url(self): return reverse('tasks-project-detail', args=['general']) class LogoutView(RedirectView): permanent = False pattern_name = 'homepage-login' def get_redirect_url(self, *args, **kwargs): self._logout_user() return super().get_redirect_url(*args, **kwargs) def _logout_user(self): if self.request.user.is_authenticated(): logout(self.request)
from django.views.generic import FormView, RedirectView from django.contrib.auth.forms import AuthenticationForm from django.core.urlresolvers import reverse from django.contrib.auth import login, logout class LoginView(FormView): template_name = 'homepage/login.html' form_class = AuthenticationForm def form_valid(self, form): user = form.get_user() login(self.request, user) return super().form_valid(form) def get_success_url(self): return reverse('tasks-project-detail', args=['none']) class LogoutView(RedirectView): permanent = False pattern_name = 'homepage-login' def get_redirect_url(self, *args, **kwargs): self._logout_user() return super().get_redirect_url(*args, **kwargs) def _logout_user(self): if self.request.user.is_authenticated(): logout(self.request)
Disable ContextLost.WebGLContextLostFromSelectElement on Windows Release. BUG=528139 TBR=kbr@chromium.org Review URL: https://codereview.chromium.org/1319463006 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#347374}
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from gpu_test_expectations import GpuTestExpectations # See the GpuTestExpectations class for documentation. class ContextLostExpectations(GpuTestExpectations): def SetExpectations(self): # Sample Usage: # self.Fail('ContextLost.WebGLContextLostFromGPUProcessExit', # ['mac', 'amd', ('nvidia', 0x1234)], bug=123) # AMD Radeon 6450 self.Fail('ContextLost.WebGLContextLostFromGPUProcessExit', ['linux', ('amd', 0x6779)], bug=479975) # Win8 Release NVIDIA bot. self.Skip('ContextLost.WebGLContextLostFromSelectElement', ['win', 'release', 'nvidia'], bug=528139) # Flaky on Mac 10.7 and 10.8 resulting in crashes during browser # startup, so skip this test in those configurations. self.Skip('ContextLost.WebGLContextLostFromSelectElement', ['mountainlion', 'debug'], bug=497411) self.Skip('ContextLost.WebGLContextLostFromSelectElement', ['lion', 'debug'], bug=498149)
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from gpu_test_expectations import GpuTestExpectations # See the GpuTestExpectations class for documentation. class ContextLostExpectations(GpuTestExpectations): def SetExpectations(self): # Sample Usage: # self.Fail('ContextLost.WebGLContextLostFromGPUProcessExit', # ['mac', 'amd', ('nvidia', 0x1234)], bug=123) # AMD Radeon 6450 self.Fail('ContextLost.WebGLContextLostFromGPUProcessExit', ['linux', ('amd', 0x6779)], bug=479975) # Flaky on Mac 10.7 and 10.8 resulting in crashes during browser # startup, so skip this test in those configurations. self.Skip('ContextLost.WebGLContextLostFromSelectElement', ['mountainlion', 'debug'], bug=497411) self.Skip('ContextLost.WebGLContextLostFromSelectElement', ['lion', 'debug'], bug=498149)
Fix DeviceIdentity on RN for Android Reviewed By: Hypuk Differential Revision: D5963912 fbshipit-source-id: 3959e5ab6af66512f0035efea7919572554e10b4
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.bridge; public class JSCJavaScriptExecutorFactory implements JavaScriptExecutorFactory { private final String mAppName; private final String mDeviceName; public JSCJavaScriptExecutorFactory(String appName, String deviceName) { this.mAppName = appName; this.mDeviceName = deviceName; } @Override public JavaScriptExecutor create() throws Exception { WritableNativeMap jscConfig = new WritableNativeMap(); jscConfig.putString("OwnerIdentity", "ReactNative"); jscConfig.putString("AppIdentity", mAppName); jscConfig.putString("DeviceIdentity", mDeviceName); return new JSCJavaScriptExecutor(jscConfig); } }
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.bridge; public class JSCJavaScriptExecutorFactory implements JavaScriptExecutorFactory { private final String mAppName; private final String mDeviceName; public JSCJavaScriptExecutorFactory(String appName, String deviceName) { this.mAppName = appName; this.mDeviceName = deviceName; } @Override public JavaScriptExecutor create() throws Exception { WritableNativeMap jscConfig = new WritableNativeMap(); jscConfig.putString("OwnerIdentity", "ReactNative"); jscConfig.putString("AppIdentity", mAppName); jscConfig.putString("OwnerIdentity", mDeviceName); return new JSCJavaScriptExecutor(jscConfig); } }
Allow mjmlEngine to be null It looks better when we want to pass options but no mjmlEngine ``` mjml(null, {}) // :) mjml(undefined, {}) // :( ```
var through = require ('through2') var mjmlDefaultEngine = require ('mjml') var gutil = require ('gulp-util') var GulpError = gutil.PluginError var NAME = 'MJML' module.exports = function mjml (mjmlEngine, options) { if(!mjmlEngine) { mjmlEngine = mjmlDefaultEngine } if (options === undefined) { options = {} } return through.obj(function (file, enc, callback) { // Not a big fan of this deep copy methods // But it will work regardless of Node version var localOptions = JSON.parse(JSON.stringify(options)) if (localOptions.filePath === undefined) { localOptions.filePath = file.path.toString() } if (file.isStream()) { this.emit('error', new GulpError(NAME, 'Streams are not supported!')) return callback() } if (file.isBuffer()) { var output = file.clone() var render try { render = mjmlEngine.mjml2html(file.contents.toString(), options) } catch (e) { this.emit('error', new GulpError(NAME, e)) return callback() } output.contents = new Buffer(render.html) output.path = gutil.replaceExtension(file.path.toString(), '.html') this.push(output) } return callback() }) }
var through = require ('through2') var mjmlDefaultEngine = require ('mjml') var gutil = require ('gulp-util') var GulpError = gutil.PluginError var NAME = 'MJML' module.exports = function mjml (mjmlEngine, options) { if(mjmlEngine === undefined) { mjmlEngine = mjmlDefaultEngine } if (options === undefined) { options = {} } return through.obj(function (file, enc, callback) { // Not a big fan of this deep copy methods // But it will work regardless of Node version var localOptions = JSON.parse(JSON.stringify(options)) if (localOptions.filePath === undefined) { localOptions.filePath = file.path.toString() } if (file.isStream()) { this.emit('error', new GulpError(NAME, 'Streams are not supported!')) return callback() } if (file.isBuffer()) { var output = file.clone() var render try { render = mjmlEngine.mjml2html(file.contents.toString(), options) } catch (e) { this.emit('error', new GulpError(NAME, e)) return callback() } output.contents = new Buffer(render.html) output.path = gutil.replaceExtension(file.path.toString(), '.html') this.push(output) } return callback() }) }
Fix sdgs feach coming from ndcs
import { createAction } from 'redux-actions'; import { createThunkAction } from 'utils/redux'; import isEmpty from 'lodash/isEmpty'; const fetchSdgGoalsInit = createAction('fetchSdgGoalsInit'); const fetchSdgGoalsReady = createAction('fetchSdgGoalsReady'); const fetchSdgGoalsFail = createAction('fetchSdgGoalsFail'); const fetchSdgGoals = createThunkAction( 'fetchSdgGoals', () => (dispatch, state) => { const { ndcSdg } = state(); if (ndcSdg && isEmpty(ndcSdg.data)) { dispatch(fetchSdgGoalsInit()); fetch('/api/v1/ndcs/sdgs_overview') .then(response => { if (response.ok) return response.json(); throw Error(response.statusText); }) .then(data => { dispatch(fetchSdgGoalsReady(data)); }) .catch(error => { console.warn(error); dispatch(fetchSdgGoalsFail()); }); } } ); export default { fetchSdgGoals, fetchSdgGoalsInit, fetchSdgGoalsReady, fetchSdgGoalsFail };
import { createAction } from 'redux-actions'; import { createThunkAction } from 'utils/redux'; import isEmpty from 'lodash/isEmpty'; const fetchSdgGoalsInit = createAction('fetchSdgGoalsInit'); const fetchSdgGoalsReady = createAction('fetchSdgGoalsReady'); const fetchSdgGoalsFail = createAction('fetchSdgGoalsFail'); const fetchSdgGoals = createThunkAction( 'fetchSdgGoals', () => (dispatch, state) => { const { ndcs } = state(); if (ndcs && isEmpty(ndcs.data)) { dispatch(fetchSdgGoalsInit()); fetch('/api/v1/ndcs/sdgs_overview') .then(response => { if (response.ok) return response.json(); throw Error(response.statusText); }) .then(data => { dispatch(fetchSdgGoalsReady(data)); }) .catch(error => { console.warn(error); dispatch(fetchSdgGoalsFail()); }); } } ); export default { fetchSdgGoals, fetchSdgGoalsInit, fetchSdgGoalsReady, fetchSdgGoalsFail };
Add StoqPluginException to default imports
#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .core import Stoq from .data_classes import ( ArchiverResponse, ExtractedPayload, Payload, PayloadMeta, PayloadResults, RequestMeta, StoqResponse, WorkerResponse, DispatcherResponse, DeepDispatcherResponse, DecoratorResponse, ) from .exceptions import StoqException, StoqPluginException __version__ = '2.0.0'
#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .core import Stoq from .data_classes import ( ArchiverResponse, ExtractedPayload, Payload, PayloadMeta, PayloadResults, RequestMeta, StoqResponse, WorkerResponse, DispatcherResponse, DeepDispatcherResponse, DecoratorResponse, ) from .exceptions import StoqException __version__ = '2.0.0'
Print LICENSE on top of the amalgamation
#!/usr/bin/env python import sys from os.path import basename, dirname, join import re INCLUDE_PATTERN = re.compile(r'^\s*#include "([\w.]+)"') WREN_DIR = dirname(dirname(realpath(__file__))) seen_files = set() out = sys.stdout # Prints a plain text file, adding comment markers. def add_comment_file(filename): with open(filename, 'r') as f: for line in f: out.write('// ') out.write(line) # Prints the given C source file, recursively resolving local #includes. def add_file(filename): bname = basename(filename) # Only include each file at most once. if bname in seen_files: return seen_files.add(bname) path = dirname(filename) out.write('// Begin file "{0}"\n'.format(filename)) with open(filename, 'r') as f: for line in f: m = INCLUDE_PATTERN.match(line) if m: add_file(join(path, m.group(1))) else: out.write(line) out.write('// End file "{0}"\n'.format(filename)) # Print license on top. add_comment_file(join(WREN_DIR, 'LICENSE')) out.write('\n') # Source files. for f in sys.argv[1:]: add_file(f)
#!/usr/bin/env python import sys from os.path import basename, dirname, join import re INCLUDE_PATTERN = re.compile(r'^\s*#include "([\w.]+)"') seen_files = set() out = sys.stdout def add_file(filename): bname = basename(filename) # Only include each file at most once. if bname in seen_files: return seen_files.add(bname) path = dirname(filename) out.write('// Begin file "{0}"\n'.format(filename)) with open(filename, 'r') as f: for line in f: m = INCLUDE_PATTERN.match(line) if m: add_file(join(path, m.group(1))) else: out.write(line) out.write('// End file "{0}"\n'.format(filename)) for f in sys.argv[1:]: add_file(f)
Add tests to check missions_completed attribute in random drone generator
const { generateRandom } = require('../../server/simulation/drone'); describe('generateRandom()', () => { const sampleArguments = {coords: {lat: 1, long: 1}, distance: 1000 }; test('returns an object', () => { expect( typeof generateRandom(sampleArguments) ).toBe('object'); }); test('returns an object with an id', () => { expect( generateRandom(sampleArguments) ).toHaveProperty('id'); }); test('returns an object with a model', () => { expect( generateRandom(sampleArguments) ).toHaveProperty('model'); }); test('returns an object with an icon property', () => { expect( generateRandom(sampleArguments) ).toHaveProperty('icon'); }); test('returns an object with coords', () => { expect( generateRandom(sampleArguments) ).toHaveProperty('coords'); }); test('returns an object with a rating attribute', () => { expect( generateRandom(sampleArguments) ).toHaveProperty('rating'); }); test('returns an object with a missions_completed attribute', () => { expect( generateRandom(sampleArguments) ).toHaveProperty('missions_completed'); }); test('returns an object with a missions_completed_7_days attribute', () => { expect( generateRandom(sampleArguments) ).toHaveProperty('missions_completed_7_days'); }); });
const { generateRandom } = require('../../server/simulation/drone'); describe('generateRandom()', () => { const sampleArguments = {coords: {lat: 1, long: 1}, distance: 1000 }; test('returns an object', () => { expect( typeof generateRandom(sampleArguments) ).toBe('object'); }); test('returns an object with an id', () => { expect( generateRandom(sampleArguments) ).toHaveProperty('id'); }); test('returns an object with a model', () => { expect( generateRandom(sampleArguments) ).toHaveProperty('model'); }); test('returns an object with an icon property', () => { expect( generateRandom(sampleArguments) ).toHaveProperty('icon'); }); test('returns an object with coords', () => { expect( generateRandom(sampleArguments) ).toHaveProperty('coords'); }); test('returns an object with a rating attribute', () => { expect( generateRandom(sampleArguments) ).toHaveProperty('rating'); }); test('returns an object with a missions_completed_7_days attribute', () => { expect( generateRandom(sampleArguments) ).toHaveProperty('missions_completed_7_days'); }); });
Change indentation style to use tabs
#!/usr/bin/env node "use strict"; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; const fatal = err => { console.error(`fatal: ${err}`); process.exit(1); }; process.argv.splice(0, 2); if (process.argv.length === 0) { fatal("No date string given"); }; let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (/Invalid Date/.test(parsedDate)) { fatal(`Could not parse ${date} into a valid date`); }; let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); let command = `GIT_COMMITTER_DATE="${dateString}" git commit --amend --date="${dateString}" --no-edit`; exec(command, (err, stdout, stderr) => { if (err) fatal("Could not modify the date of the previous commit"); console.log("\nModified previous commit:\n AUTHOR_DATE " + chalk.grey(dateString) + "\n COMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n " + chalk.bgWhite.black(command) + "\n"); });
#!/usr/bin/env node "use strict"; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; const fatal = err => { console.error(`fatal: ${err}`); process.exit(1); }; process.argv.splice(0, 2); if (process.argv.length === 0) { fatal("No date string given"); }; let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (/Invalid Date/.test(parsedDate)) { fatal(`Could not parse ${date} into a valid date`); }; let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); let command = `GIT_COMMITTER_DATE="${dateString}" git commit --amend --date="${dateString}" --no-edit`; exec(command, (err, stdout, stderr) => { if (err) fatal("Could not modify the date of the previous commit"); console.log("\nModified previous commit:\n AUTHOR_DATE " + chalk.grey(dateString) + "\n COMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n " + chalk.bgWhite.black(command) + "\n"); });
Remove 'meta' in favour of 'params'
<?php echo '<?php' ?> use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateIndices extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('indices', function(Blueprint $table) { $table->increments('id'); $table->text('params'); $table->integer('order')->unsigned()->default(0); $table->string('title', 255); $table->string('slug', 255)->unique(); $table->string('namespace', 255); $table->text('href'); $table->integer('disabled')->default(0); $table->integer('navigation')->default(0); $table->integer('published')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('indices'); } }
<?php echo '<?php' ?> use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateIndices extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('indices', function(Blueprint $table) { $table->increments('id'); $table->text('params'); $table->integer('order')->unsigned()->default(0); $table->string('title', 255); $table->string('slug', 255)->unique(); $table->string('meta', 255); $table->string('namespace', 255); $table->text('href'); $table->integer('disabled')->default(0); $table->integer('navigation')->default(0); $table->integer('published')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('indices'); } }
Remove forgotten comment quotation marks
def check_argv(argv): """Check if arguments are ok. When executing, there must be argument switch for test/live. There also must be filename. Method returns set(is_correct, filename, is_test) """ python_file_name = argv[0] usage_msg = "Usage: python %s [-test | -live] filename.txt" % python_file_name is_test = True if len(argv) > 1: if '-test' in argv: is_test = True elif '-live' in argv: is_test = False else: print usage_msg return (False, None, is_test) if len(argv) < 3: print usage_msg return (False, None, is_test) else: filename = argv[2] return (True, filename, is_test) else: print usage_msg return (False, None, is_test)
def check_argv(argv): """Check if arguments are ok. When executing, there must be argument switch for test/live. There also must be filename. Method returns set(is_correct, filename, is_test) """`` python_file_name = argv[0] usage_msg = "Usage: python %s [-test | -live] filename.txt" % python_file_name is_test = True if len(argv) > 1: if '-test' in argv: is_test = True elif '-live' in argv: is_test = False else: print usage_msg return (False, None, is_test) if len(argv) < 3: print usage_msg return (False, None, is_test) else: filename = argv[2] return (True, filename, is_test) else: print usage_msg return (False, None, is_test)
Update Worker API - ADD type hints - Remove unused imports
# stdlib from typing import Callable # syft relative from ...messages.infra_messages import CreateWorkerMessage from ...messages.infra_messages import DeleteWorkerMessage from ...messages.infra_messages import GetWorkerMessage from ...messages.infra_messages import GetWorkersMessage from ...messages.infra_messages import UpdateWorkerMessage from .request_api import GridRequestAPI class WorkerRequestAPI(GridRequestAPI): response_key = "worker" def __init__(self, send: Callable): super().__init__( create_msg=CreateWorkerMessage, get_msg=GetWorkerMessage, get_all_msg=GetWorkersMessage, update_msg=UpdateWorkerMessage, delete_msg=DeleteWorkerMessage, send=send, response_key=WorkerRequestAPI.response_key, ) def __getitem__(self, key: int) -> object: return self.get(worker_id=key) def __delitem__(self, key: int) -> None: self.delete(worker_id=key)
# stdlib from typing import Any from typing import Dict # third party from pandas import DataFrame # syft relative from ...messages.infra_messages import CreateWorkerMessage from ...messages.infra_messages import DeleteWorkerMessage from ...messages.infra_messages import GetWorkerMessage from ...messages.infra_messages import GetWorkersMessage from ...messages.infra_messages import UpdateWorkerMessage from .request_api import GridRequestAPI class WorkerRequestAPI(GridRequestAPI): response_key = "worker" def __init__(self, send): super().__init__( create_msg=CreateWorkerMessage, get_msg=GetWorkerMessage, get_all_msg=GetWorkersMessage, update_msg=UpdateWorkerMessage, delete_msg=DeleteWorkerMessage, send=send, response_key=WorkerRequestAPI.response_key, ) def __getitem__(self, key): return self.get(worker_id=key) def __delitem__(self, key): self.delete(worker_id=key)
Use new lrp convergence method * GatherDesiredLRPs -> GatherAndPruneDesiredLRPs Signed-off-by: James Myers <44cbd4b2784f900a6fede6279d0b7fdcbfaa89f5@pivotal.io>
package benchmark_bbs_test import ( "github.com/cloudfoundry-incubator/bbs/db/etcd" "github.com/cloudfoundry-incubator/benchmark-bbs/reporter" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) const ( ConvergenceGathering = "ConvergenceGathering" ) var BenchmarkConvergenceGathering = func(numTrials int) { Describe("Gathering", func() { Measure("data for convergence", func(b Benchmarker) { guids := map[string]struct{}{} b.Time("BBS' internal gathering of LRPs", func() { actuals, err := etcdDB.GatherActualLRPs(logger, guids, &etcd.LRPMetricCounter{}) Expect(err).NotTo(HaveOccurred()) Expect(len(actuals)).To(BeNumerically("~", expectedLRPCount, expectedLRPTolerance)) desireds, err := etcdDB.GatherAndPruneDesiredLRPs(logger, guids, &etcd.LRPMetricCounter{}) Expect(err).NotTo(HaveOccurred()) Expect(len(desireds)).To(BeNumerically("~", expectedLRPCount, expectedLRPTolerance)) }, reporter.ReporterInfo{ MetricName: ConvergenceGathering, }) }, numTrials) }) }
package benchmark_bbs_test import ( "github.com/cloudfoundry-incubator/bbs/db/etcd" "github.com/cloudfoundry-incubator/benchmark-bbs/reporter" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) const ( ConvergenceGathering = "ConvergenceGathering" ) var BenchmarkConvergenceGathering = func(numTrials int) { Describe("Gathering", func() { Measure("data for convergence", func(b Benchmarker) { guids := map[string]struct{}{} b.Time("BBS' internal gathering of LRPs", func() { actuals, err := etcdDB.GatherActualLRPs(logger, guids, &etcd.LRPMetricCounter{}) Expect(err).NotTo(HaveOccurred()) Expect(len(actuals)).To(BeNumerically("~", expectedLRPCount, expectedLRPTolerance)) desireds, err := etcdDB.GatherDesiredLRPs(logger, guids, &etcd.LRPMetricCounter{}) Expect(err).NotTo(HaveOccurred()) Expect(len(desireds)).To(BeNumerically("~", expectedLRPCount, expectedLRPTolerance)) }, reporter.ReporterInfo{ MetricName: ConvergenceGathering, }) }, numTrials) }) }
Use a filesystem db and add the sites app to fix a test failure.
# -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/tmp/django-formtools-tests.db', } } INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'formtools', 'tests.wizard.wizardtests', ] SECRET_KEY = 'spam-spam-spam-spam' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'spam-and-eggs' } } MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', )
# -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'formtools', 'tests.wizard.wizardtests', ] SECRET_KEY = 'spam-spam-spam-spam' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'spam-and-eggs' } } MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', )
Fix individual message button in Slack Closes #1120.
'use strict'; togglbutton.render('#channel_name:not(.toggl)', { observe: true }, function() { var link, placeholder = $('.channel_title_info'), project = $('#team_name').textContent, description = $('#channel_name') .textContent.trim() .replace(/^#/, ''); link = togglbutton.createTimerLink({ className: 'slack', description: description, projectName: project, buttonType: 'minimal' }); placeholder.parentNode.insertBefore(link, placeholder); }); togglbutton.render('.c-message--hover:not(.toggl)', { observe: true }, function( elem ) { var link, placeholder = $('.c-message_actions__button:last-child'), description = $('.c-message__body', elem).textContent, project = $('#team_name').textContent, button = document.createElement('button'); link = togglbutton.createTimerLink({ className: 'slack-message', projectName: project, description: description, buttonType: 'minimal' }); button.className = 'c-button-unstyled c-message_actions__button'; button.setAttribute('type', 'button'); button.appendChild(link); placeholder.parentNode.insertBefore(button, placeholder); });
'use strict'; togglbutton.render('#channel_name:not(.toggl)', { observe: true }, function() { var link, placeholder = $('.channel_title_info'), project = $('#team_name').textContent, description = $('#channel_name') .textContent.trim() .replace(/^#/, ''); link = togglbutton.createTimerLink({ className: 'slack', description: description, projectName: project, buttonType: 'minimal' }); placeholder.parentNode.insertBefore(link, placeholder); }); togglbutton.render('.c-message--hover:not(.toggl)', { observe: true }, function( elem ) { var link, placeholder = $('.c-message_actions__button--last-child'), description = $('.c-message__body', elem).textContent, project = $('#team_name').textContent, button = document.createElement('button'); link = togglbutton.createTimerLink({ className: 'slack-message', projectName: project, description: description, buttonType: 'minimal' }); button.className = 'c-button-unstyled c-message_actions__button'; button.setAttribute('type', 'button'); button.appendChild(link); placeholder.parentNode.insertBefore(button, placeholder); });
Implement UpperCamelCase name check for enums
from tailor.swift.swiftlistener import SwiftListener from tailor.utils.charformat import isUpperCamelCase class MainListener(SwiftListener): def enterClassName(self, ctx): self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase') def enterEnumName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase') def enterEnumCaseName(self, ctx): pass def enterStructName(self, ctx): pass @staticmethod def __verify_upper_camel_case(ctx, err_msg): construct_name = ctx.getText() if not isUpperCamelCase(construct_name): print('Line', str(ctx.start.line) + ':', err_msg)
from tailor.swift.swiftlistener import SwiftListener from tailor.utils.charformat import isUpperCamelCase class MainListener(SwiftListener): def enterClassName(self, ctx): self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase') def enterEnumName(self, ctx): pass def enterEnumCaseName(self, ctx): pass def enterStructName(self, ctx): pass @staticmethod def __verify_upper_camel_case(ctx, err_msg): construct_name = ctx.getText() if not isUpperCamelCase(construct_name): print('Line', str(ctx.start.line) + ':', err_msg)
Fix latest migration's down() function
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddActiveFieldToUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table("users", function(Blueprint $table) { $table->char("active", 1)->default("Y"); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table("users", function($table) { $table->dropColumn('active'); }); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddActiveFieldToUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table("users", function(Blueprint $table) { $table->char("active", 1)->default("Y"); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table("users", function($table) { $table->dropColumn('logged_in_at'); }); } }
Add visual.ons to external link formatter (will enable event tracking for outbound clicks)
// Using regex instead of simply using 'host' because it causes error with security on Government browsers (IE9 so far) function getHostname(url) { var m = url.match(/^http(s?):\/\/[^/]+/); return m ? m[0] : null; } function eachAnchor(anchors) { $(anchors).each(function() { var href = $(this).attr("href"); var hostname = getHostname(href); if (hostname) { if ((hostname !== document.domain && hostname.indexOf('ons.gov.uk') == -1) || (hostname.indexOf('visual.ons.gov.uk') != -1 )){ $(this).attr('target', '_blank'); } } }); } $(function() { eachAnchor('a[href^="http://"]:not([href*="loop11.com"]):not([href*="ons.gov.uk"])'); eachAnchor('a[href^="https://"]:not([href*="loop11.com"]):not([href*="ons.gov.uk"])'); eachAnchor('a[href*="nationalarchives.gov.uk"]'); eachAnchor('a[href*="visual.ons.gov.uk"]'); });
// Using regex instead of simply using 'host' because it causes error with security on Government browsers (IE9 so far) function getHostname(url) { var m = url.match(/^http(s?):\/\/[^/]+/); return m ? m[0] : null; } function eachAnchor(anchors) { $(anchors).each(function() { var href = $(this).attr("href"); var hostname = getHostname(href); if (hostname) { if (hostname !== document.domain && hostname.indexOf('ons.gov.uk') == -1) { $(this).attr('target', '_blank'); } } }); } $(function() { eachAnchor('a[href^="http://"]:not([href*="loop11.com"]):not([href*="ons.gov.uk"])'); eachAnchor('a[href^="https://"]:not([href*="loop11.com"]):not([href*="ons.gov.uk"])'); eachAnchor('a[href*="nationalarchives.gov.uk"]'); });
Add method for ensuring that no null values are contained in a collection. passed as an argument.
/* * Copyright 2015 Martijn van der Woud - The Crimson Cricket Internet Services * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.crimsoncricket.asserts; import java.util.Collection; public class Assert { public static void assertStateNotNull(Object anObject, String message) { if (anObject == null) throw new IllegalStateException(message); } public static void assertArgumentNotNull(Object anArgument, String message) { if (anArgument == null) throw new IllegalArgumentException(message); } public static void assertStringArgumentNotEmpty(String anArgument, String message) { if (anArgument.isEmpty()) throw new IllegalArgumentException(message); } public static void assertArgumentCollectionNotContainsNull(Collection<?> anArgument, String message) { if (anArgument.stream().anyMatch(element -> element == null)) throw new IllegalArgumentException(message); } }
/* * Copyright 2015 Martijn van der Woud - The Crimson Cricket Internet Services * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.crimsoncricket.asserts; public class Assert { public static void assertStateNotNull(Object anObject, String message) { if (anObject == null) throw new IllegalStateException(message); } public static void assertArgumentNotNull(Object anArgument, String message) { if (anArgument == null) throw new IllegalArgumentException(message); } public static void assertStringArgumentNotEmpty(String anArgument, String message) { if (anArgument.isEmpty()) throw new IllegalArgumentException(message); } }
Remove test for cell name and availability zone.
package vizzini_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Cells", func() { It("should return all cells", func() { cells, err := bbsClient.Cells(logger) Expect(err).NotTo(HaveOccurred()) Expect(len(cells)).To(BeNumerically(">=", 1)) cell0 := cells[0] Expect(cell0).NotTo(BeNil()) Expect(cell0.Capacity.MemoryMb).To(BeNumerically(">", 0)) Expect(cell0.Capacity.DiskMb).To(BeNumerically(">", 0)) Expect(cell0.Capacity.Containers).To(BeNumerically(">", 0)) Expect(len(cell0.RootfsProviders)).To(BeNumerically(">", 0)) }) })
package vizzini_test import ( "strings" "code.cloudfoundry.org/bbs/models" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Cells", func() { It("should return all cells", func() { cells, err := bbsClient.Cells(logger) Expect(err).NotTo(HaveOccurred()) Expect(len(cells)).To(BeNumerically(">=", 1)) var cell_z1_0 *models.CellPresence for _, cell := range cells { if strings.HasPrefix(cell.CellId, "cell_z1-0") { cell_z1_0 = cell break } } Expect(cell_z1_0).NotTo(BeNil()) Expect(cell_z1_0.CellId).To(HavePrefix("cell_z1-0")) Expect(cell_z1_0.Zone).To(Equal("z1")) Expect(cell_z1_0.Capacity.MemoryMb).To(BeNumerically(">", 0)) Expect(cell_z1_0.Capacity.DiskMb).To(BeNumerically(">", 0)) Expect(cell_z1_0.Capacity.Containers).To(BeNumerically(">", 0)) Expect(len(cell_z1_0.RootfsProviders)).To(BeNumerically(">", 0)) }) })
Remove non-working debug output to console
/* Author: mythern Copyright (C) 2014, MIT License http://www.opensource.org/licenses/mit-license.php Adressaway is provided free of charge, to any person obtaining a copy of this software and associated documentation files, 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 todo so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial parts of the software, including credits to the original author. */ var debug = true; chrome.webRequest.onBeforeSendHeaders.addListener( function (details) { details.requestHeaders.push( { name: "Referer", value: "https://www.google.com/" } ) return { requestHeaders: details.requestHeaders } }, { urls: ["*://*.adressa.no/*"] }, ["blocking", "requestHeaders"] )
/* Author: mythern Copyright (C) 2014, MIT License http://www.opensource.org/licenses/mit-license.php Adressaway is provided free of charge, to any person obtaining a copy of this software and associated documentation files, 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 todo so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial parts of the software, including credits to the original author. */ var debug = true; chrome.webRequest.onBeforeSendHeaders.addListener( function (details) { if (debug) { console.log("Intercepting request headers, adding google referrer.") } details.requestHeaders.push( { name: "Referer", value: "https://www.google.com/" } ) return { requestHeaders: details.requestHeaders } }, { urls: ["*://*.adressa.no/*"] }, ["blocking", "requestHeaders"] )
Add in message remover for memedog
import BaseWatcher from './BaseWatcher'; import config from '../config'; /** * This checks for people spamming cool dog crap. */ class CoolDogSpamWatcher extends BaseWatcher { constructor(bot) { super(bot); } usesBypassRules = true; /** * The method this watcher should listen on. * * @type {string} */ method = [ 'message', 'messageUpdate' ]; async action(method, message, updatedMessage) { if (method === 'messageUpdate') { message = updatedMessage; } const rulesChannel = this.bot.channels.find((channel) => (channel.name === config.rules_channel)); if ( message.cleanContent.toLowerCase().indexOf('this is cooldog') !== -1 || message.cleanContent.toLowerCase().indexOf('this is memedog') !== -1 ) { const warningMessage = await message.reply(`Please read the ${rulesChannel} channel. Spamming or encouraging spamming is not allowed.`); this.addWarningToUser(message); message.delete(); warningMessage.delete(60000); } } } export default CoolDogSpamWatcher;
import BaseWatcher from './BaseWatcher'; import config from '../config'; /** * This checks for people spamming cool dog crap. */ class CoolDogSpamWatcher extends BaseWatcher { constructor(bot) { super(bot); } usesBypassRules = true; /** * The method this watcher should listen on. * * @type {string} */ method = [ 'message', 'messageUpdate' ]; async action(method, message, updatedMessage) { if (method === 'messageUpdate') { message = updatedMessage; } const rulesChannel = this.bot.channels.find((channel) => (channel.name === config.rules_channel)); if (message.cleanContent.toLowerCase().indexOf('this is cooldog') !== -1) { const warningMessage = await message.reply(`Please read the ${rulesChannel} channel. Spamming or encouraging spamming is not allowed.`); this.addWarningToUser(message); message.delete(); warningMessage.delete(60000); } } } export default CoolDogSpamWatcher;