text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add new functions to the network data trait
<?php namespace App\Modules\Networkdata\Traits; trait NetworkDataAccount { /** * Fetch all ATC Sessions. * * @return \Illuminate\Database\Eloquent\Relations\hasMany */ public function networkDataAtc() { return $this->hasMany(\App\Modules\NetworkData\Models\Atc::class, 'account_id', 'id'); } /** * Get the member's current ATC session, if connected. * * @return \App\Modules\NetworkData\Models\Atc */ public function networkDataAtcCurrent() { return $this->hasOne(\App\Modules\NetworkData\Models\Atc::class, 'account_id', 'id') ->whereNull('disconnected_at') ->limit(1); } /** * Determine if the user is on the network. * * @return bool */ public function getIsOnNetworkAttribute() { return $this->networkDataAtcCurrent->exists; } /* * Fetch all Pilot Sessions * * @return \Illuminate\Database\Eloquent\Relations\hasMany */ // public function networkDataPilot() // { // return $this->hasMany(\App\Modules\NetworkData\Models\Pilot::class, "account_id", "id"); // } }
<?php namespace App\Modules\Networkdata\Traits; trait NetworkDataAccount { /** * Fetch all ATC Sessions. * * @return \Illuminate\Database\Eloquent\Relations\hasMany */ public function networkDataAtc() { return $this->hasMany(\App\Modules\NetworkData\Models\Atc::class, 'account_id', 'id'); } /* * Fetch all Pilot Sessions * * @return \Illuminate\Database\Eloquent\Relations\hasMany */ // public function networkDataPilot() // { // return $this->hasMany(\App\Modules\NetworkData\Models\Pilot::class, "account_id", "id"); // } }
Change criteria for link to billmate checkout
<?php class Link extends LinkCore { public function getPageLink($controller, $ssl = null, $id_lang = null, $request = null, $request_url_encode = false, $id_shop = null, $relative_protocol = false) { if ( $controller == 'order-opc' && Module::isInstalled('billmategateway') && Module::isEnabled('billmategateway') && version_compare(Configuration::get('BILLMATE_VERSION'), '3.0.0', '>=') && Configuration::get('BILLMATE_CHECKOUT_ACTIVATE') == 1 ) { $return = $this->getBaseLink($id_shop, $ssl, $relative_protocol).'module/billmategateway/billmatecheckout'; } else { $return = parent::getPageLink($controller, $ssl, $id_lang, $request, $request_url_encode, $id_shop, $relative_protocol); } return $return; } } ?>
<?php class Link extends LinkCore { public function getPageLink($controller, $ssl = null, $id_lang = null, $request = null, $request_url_encode = false, $id_shop = null, $relative_protocol = false) { if ( $controller == 'order-opc' && Configuration::get('BILLMATE_CHECKOUT_ACTIVATE') == 1 && class_exists('BillmateGateway') == true && class_exists('BillmategatewayBillmatecheckoutModuleFrontController') == true ) { $return = $this->getBaseLink($id_shop, $ssl, $relative_protocol).'module/billmategateway/billmatecheckout'; } else { $return = parent::getPageLink($controller, $ssl, $id_lang, $request, $request_url_encode, $id_shop, $relative_protocol); } return $return; } } ?>
fix(recents-list): Order recents by last used
/* global interfaceConfig */ import { parseURIString, safeDecodeURIComponent } from '../base/util'; /** * Transforms the history list to a displayable list. * * @private * @param {Array<Object>} recentList - The recent list form the redux store. * @returns {Array<Object>} */ export function toDisplayableList(recentList) { return ( [ ...recentList ].reverse() .map(item => { return { date: item.date, duration: item.duration, time: [ item.date ], title: safeDecodeURIComponent(parseURIString(item.conference).room), url: item.conference }; })); } /** * Returns <tt>true</tt> if recent list is enabled and <tt>false</tt> otherwise. * * @returns {boolean} <tt>true</tt> if recent list is enabled and <tt>false</tt> * otherwise. */ export function isRecentListEnabled() { return interfaceConfig.RECENT_LIST_ENABLED; }
/* global interfaceConfig */ import { parseURIString, safeDecodeURIComponent } from '../base/util'; /** * Transforms the history list to a displayable list. * * @private * @param {Array<Object>} recentList - The recent list form the redux store. * @returns {Array<Object>} */ export function toDisplayableList(recentList) { return ( recentList.reverse() .map(item => { return { date: item.date, duration: item.duration, time: [ item.date ], title: safeDecodeURIComponent(parseURIString(item.conference).room), url: item.conference }; })); } /** * Returns <tt>true</tt> if recent list is enabled and <tt>false</tt> otherwise. * * @returns {boolean} <tt>true</tt> if recent list is enabled and <tt>false</tt> * otherwise. */ export function isRecentListEnabled() { return interfaceConfig.RECENT_LIST_ENABLED; }
Revert "Revert "use strict dependency injection""
'use strict'; /** * angular-select-text directive */ angular.module('angular-select-text', []). directive('selectText', ['$window', function ($window) { var selectElement; if ($window.document.selection) { selectElement = function(element) { var range = $window.document.body.createTextRange(); range.moveToElementText(element[0]); range.select(); }; } else if ($window.getSelection) { selectElement = function(element) { var range = $window.document.createRange(); range.selectNode(element[0]); $window.getSelection().addRange(range); }; } return { restrict: 'A', link: function(scope, element, attrs){ element.bind('click', function(){ selectElement(element); }); } }; }]);
'use strict'; /** * angular-select-text directive */ angular.module('angular-select-text', []). directive('selectText', function ($window) { var selectElement; if ($window.document.selection) { selectElement = function(element) { var range = $window.document.body.createTextRange(); range.moveToElementText(element[0]); range.select(); }; } else if ($window.getSelection) { selectElement = function(element) { var range = $window.document.createRange(); range.selectNode(element[0]); $window.getSelection().addRange(range); }; } return { restrict: 'A', link: function(scope, element, attrs){ element.bind('click', function(){ selectElement(element); }); } }; });
Add workaround for bad YouTube results The upstream module used for YouTube search breaks when results are neither videos nor channels. This commit forces YouTube to return only videos and channels, in order to work around the bug. Bug: MaxGfeller/youtube-search#15
/** * To use this module, add youtube.key to your config.json * You need the key for the Youtube Data API: * https://console.developers.google.com/apis/credentials */ var yt = require( 'youtube-search' ); module.exports = { commands: { yt: { help: 'Searches YouTube for a query string', aliases: [ 'youtube' ], command: function ( bot, msg ) { msg.args.shift(); var query = msg.args.join( ' ' ); var opts = bot.config.youtube || {}; opts.maxResults = 1; opts.type = 'video,channel'; yt( query, opts, function ( err, results ) { if ( err ) { return bot.say( msg.to, msg.nick + ': ' + err ); } var result = results[0]; bot.say( msg.to, msg.nick + ': ' + result.link + ' ' + result.title ); } ); } } } };
/** * To use this module, add youtube.key to your config.json * You need the key for the Youtube Data API: * https://console.developers.google.com/apis/credentials */ var yt = require( 'youtube-search' ); module.exports = { commands: { yt: { help: 'Searches YouTube for a query string', aliases: [ 'youtube' ], command: function ( bot, msg ) { msg.args.shift(); var query = msg.args.join( ' ' ); var opts = bot.config.youtube || {}; opts.maxResults = 1; yt( query, opts, function ( err, results ) { if ( err ) { return bot.say( msg.to, msg.nick + ': ' + err ); } var result = results[0]; bot.say( msg.to, msg.nick + ': ' + result.link + ' ' + result.title ); } ); } } } };
Update tags when new comments are left.
import React from 'react' import { connect } from 'react-redux' import { FormattedMessage } from 'react-intl' import { openCommentThreads, acceptSelection } from 'redux/actions.js' function mapStateToProps(state, ownProps) { return { count: state.cardsById[ownProps.cardId].commentThreads .map( e => state.commentThreadsById[e.id].commentIds ) .reduce( (a, e) => [...a, ...e], [] ) .length, } } const CommentThreadsTag = ({count, cardId, openCommentThreads, acceptSelection}) => <div className="CommentThread__banner" onClick={() => { openCommentThreads(cardId) count === 0 && acceptSelection() }} > { count > 0 ? <FormattedMessage id="comments.nResponses" defaultMessage={`{count, number} {count, plural, one {response} other {responses} }`} values={{count}} /> : <FormattedMessage id="comments.respond" defaultMessage="Respond" /> } </div> export default connect( mapStateToProps, {openCommentThreads, acceptSelection} )(CommentThreadsTag)
import React from 'react' import { connect } from 'react-redux' import { FormattedMessage } from 'react-intl' import { openCommentThreads, acceptSelection } from 'redux/actions.js' function mapStateToProps(state, ownProps) { return { count: state.cardsById[ownProps.cardId].commentThreads .reduce( (all, thread) => [...all, ...thread.commentIds], [] ) .length, } } const CommentThreadsTag = ({count, cardId, openCommentThreads, acceptSelection}) => <div className="CommentThread__banner" onClick={() => { openCommentThreads(cardId) count === 0 && acceptSelection() }} > { count > 0 ? <FormattedMessage id="comments.nResponses" defaultMessage={`{count, number} {count, plural, one {response} other {responses} }`} values={{count}} /> : <FormattedMessage id="comments.respond" defaultMessage="Respond" /> } </div> export default connect( mapStateToProps, {openCommentThreads, acceptSelection} )(CommentThreadsTag)
Add semi-useful `__str__` for Result
from subprocess import PIPE from .monkey import Popen from .exceptions import Failure class Result(object): def __init__(self, stdout=None, stderr=None, exited=None): self.exited = self.return_code = exited self.stdout = stdout self.stderr = stderr def __nonzero__(self): # Holy mismatch between name and implementation, Batman! return self.exited == 0 def __str__(self): ret = ["Command exited with status %s." % self.exited] for x in ('stdout', 'stderr'): val = getattr(self, x) ret.append("""=== %s === %s """ % (x, val.rstrip()) if val else "(no %s)" % x) return "\n".join(ret) def run(command, warn=False): """ Execute ``command`` in a local subprocess. By default, raises an exception if the subprocess terminates with a nonzero return code. This may be disabled by setting ``warn=True``. """ process = Popen(command, shell=True, stdout=PIPE, stderr=PIPE ) stdout, stderr = process.communicate() result = Result(stdout=stdout, stderr=stderr, exited=process.returncode) if not (result or warn): raise Failure(result) return result
from subprocess import PIPE from .monkey import Popen from .exceptions import Failure class Result(object): def __init__(self, stdout=None, stderr=None, exited=None): self.exited = self.return_code = exited self.stdout = stdout self.stderr = stderr def __nonzero__(self): # Holy mismatch between name and implementation, Batman! return self.exited == 0 def run(command, warn=False): """ Execute ``command`` in a local subprocess. By default, raises an exception if the subprocess terminates with a nonzero return code. This may be disabled by setting ``warn=True``. """ process = Popen(command, shell=True, stdout=PIPE, stderr=PIPE ) stdout, stderr = process.communicate() result = Result(stdout=stdout, stderr=stderr, exited=process.returncode) if not (result or warn): raise Failure(result) return result
Put back redundant std_deviation output
package hex.schemas; import hex.pca.PCAModel; import water.api.*; public class PCAModelV3 extends ModelSchema<PCAModel, PCAModelV3, PCAModel.PCAParameters, PCAV3.PCAParametersV3, PCAModel.PCAOutput, PCAModelV3.PCAModelOutputV3> { public static final class PCAModelOutputV3 extends ModelOutputSchema<PCAModel.PCAOutput, PCAModelOutputV3> { // Output fields; input fields are in the parameters list // TODO: This field is redundant. Remove in next API change. @API(help = "Standard deviations") public double[] std_deviation; @API(help = "Importance of each principal component") public TwoDimTableBase pc_importance; @API(help = "Principal components matrix") public TwoDimTableBase eigenvectors; @API(help = "Frame key for loading matrix") public KeyV3.FrameKeyV3 loading_key; } // TODO: I think we can implement the following two in ModelSchema, using reflection on the type parameters. public PCAV3.PCAParametersV3 createParametersSchema() { return new PCAV3.PCAParametersV3(); } public PCAModelOutputV3 createOutputSchema() { return new PCAModelOutputV3(); } // Version&Schema-specific filling into the impl @Override public PCAModel createImpl() { PCAModel.PCAParameters parms = parameters.createImpl(); return new PCAModel( model_id.key(), parms, null ); } }
package hex.schemas; import hex.pca.PCAModel; import water.api.*; public class PCAModelV3 extends ModelSchema<PCAModel, PCAModelV3, PCAModel.PCAParameters, PCAV3.PCAParametersV3, PCAModel.PCAOutput, PCAModelV3.PCAModelOutputV3> { public static final class PCAModelOutputV3 extends ModelOutputSchema<PCAModel.PCAOutput, PCAModelOutputV3> { // Output fields; input fields are in the parameters list @API(help = "Importance of each principal component") public TwoDimTableBase pc_importance; @API(help = "Principal components matrix") public TwoDimTableBase eigenvectors; @API(help = "Frame key for loading matrix") public KeyV3.FrameKeyV3 loading_key; } // TODO: I think we can implement the following two in ModelSchema, using reflection on the type parameters. public PCAV3.PCAParametersV3 createParametersSchema() { return new PCAV3.PCAParametersV3(); } public PCAModelOutputV3 createOutputSchema() { return new PCAModelOutputV3(); } // Version&Schema-specific filling into the impl @Override public PCAModel createImpl() { PCAModel.PCAParameters parms = parameters.createImpl(); return new PCAModel( model_id.key(), parms, null ); } }
Fix warning when generating javadoc ; Add class description
package com.boundary.sdk.event; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.net.URL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utilities used for java script execution * * @author davidg * */ public class ScriptUtils { private static Logger LOG = LoggerFactory.getLogger(ScriptUtils.class); public ScriptUtils() { } /** * Finds a script to be tested from * @param scriptPath * @return {@link File} */ static public FileReader getFile(String scriptPath) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL url = loader.getResource(scriptPath); assert(url == null); File f = new File(url.getFile()); FileReader reader = null; try { reader = new FileReader(f); } catch (FileNotFoundException e) { e.printStackTrace(); LOG.error(e.getMessage()); } return reader; } }
package com.boundary.sdk.event; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.net.URL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ScriptUtils { private static Logger LOG = LoggerFactory.getLogger(ScriptUtils.class); public ScriptUtils() { } /** * Finds a script to be tested from * @param scriptName * @return {@link File} */ static public FileReader getFile(String scriptPath) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL url = loader.getResource(scriptPath); assert(url == null); File f = new File(url.getFile()); FileReader reader = null; try { reader = new FileReader(f); } catch (FileNotFoundException e) { e.printStackTrace(); LOG.error(e.getMessage()); } return reader; } }
Add tests for request ids
'use strict'; require('./testUtils'); var Error = require('../lib/Error'); var expect = require('chai').expect; describe('Error', function() { it('Populates with type and message params', function() { var e = new Error('FooError', 'Foo happened'); expect(e).to.have.property('type', 'FooError'); expect(e).to.have.property('message', 'Foo happened'); expect(e).to.have.property('stack'); }); describe('StripeError', function() { it('Generates specific instance depending on error-type', function() { expect(Error.StripeError.generate({ type: 'card_error' })).to.be.instanceOf(Error.StripeCardError); expect(Error.StripeError.generate({ type: 'invalid_request_error' })).to.be.instanceOf(Error.StripeInvalidRequestError); expect(Error.StripeError.generate({ type: 'api_error' })).to.be.instanceOf(Error.StripeAPIError); }); it('Pulls in request IDs', function() { var e = Error.StripeError.generate({ type: 'card_error', requestId: 'foo'}); expect(e).to.have.property('requestId', 'foo'); }); }); });
'use strict'; require('./testUtils'); var Error = require('../lib/Error'); var expect = require('chai').expect; describe('Error', function() { it('Populates with type and message params', function() { var e = new Error('FooError', 'Foo happened'); expect(e).to.have.property('type', 'FooError'); expect(e).to.have.property('message', 'Foo happened'); expect(e).to.have.property('stack'); }); describe('StripeError', function() { it('Generates specific instance depending on error-type', function() { expect(Error.StripeError.generate({ type: 'card_error' })).to.be.instanceOf(Error.StripeCardError); expect(Error.StripeError.generate({ type: 'invalid_request_error' })).to.be.instanceOf(Error.StripeInvalidRequestError); expect(Error.StripeError.generate({ type: 'api_error' })).to.be.instanceOf(Error.StripeAPIError); }); }); });
Create Buffer with encoding 'binary'.
// A mock stream implementation that breaks up provided data into // random-sized chunks and emits 'data' events. This is used to simulate // data arriving with arbitrary packet boundaries. var Buffer = require('buffer').Buffer; var EventEmitter = require('events').EventEmitter; var sys = require('sys'); var TestStream = function(str, min, max) { EventEmitter.call(this); str = str || ''; min = min || 1; max = max || str.length; var self = this; var buf = new Buffer(str, 'binary'); var emitData = function() { var len = Math.min( min + Math.floor(Math.random() * (max - min)), buf.length ); var b = buf.slice(0, len); if (len < buf.length) { buf = buf.slice(len, buf.length); process.nextTick(emitData); } else { process.nextTick(function() { self.emit('end') }); } self.emit('data', b); }; process.nextTick(emitData); }; sys.inherits(TestStream, EventEmitter); exports.TestStream = TestStream;
// A mock stream implementation that breaks up provided data into // random-sized chunks and emits 'data' events. This is used to simulate // data arriving with arbitrary packet boundaries. var Buffer = require('buffer').Buffer; var EventEmitter = require('events').EventEmitter; var sys = require('sys'); var TestStream = function(str, min, max) { EventEmitter.call(this); str = str || ''; min = min || 1; max = max || str.length; var self = this; var buf = new Buffer(str, 'utf-8'); var emitData = function() { var len = Math.min( min + Math.floor(Math.random() * (max - min)), buf.length ); var b = buf.slice(0, len); if (len < buf.length) { buf = buf.slice(len, buf.length); process.nextTick(emitData); } else { process.nextTick(function() { self.emit('end') }); } self.emit('data', b); }; process.nextTick(emitData); }; sys.inherits(TestStream, EventEmitter); exports.TestStream = TestStream;
Fix error of input value in gallery uploader.
<div id="{{ $id or 'gallery-upload' }}" class="gallery-upload {{ $class or ''}}"> <p> <button type="button" class="btn btn-default">{{ $button or 'Upload' }}</button> <input type="file" class="hidden" accept="image/*"> </p> <div class="image-gallery clearfix"> @if (isset($images)) @foreach ($images as $image) <div class="image-preview" style="background-image:url({{$image->getThumbUrl()}})"> <span><i class="fa fa-times"></i></span> <input type="hidden" name="{{ $name or 'images' }}[]" value="{{ $image->id or '' }}"> </div> @endforeach @endif </div> <p class="text-muted">Drag and drop to change the order of images.</p> <template> <div class="image-preview"> <span><i class="fa fa-times"></i></span> <input type="hidden" name="{{ $name or 'images' }}[]"> </div> </template> </div>
<div id="{{ $id or 'gallery-upload' }}" class="gallery-upload {{ $class or ''}}"> <p> <button type="button" class="btn btn-default">{{ $button or 'Upload' }}</button> <input type="file" class="hidden" accept="image/*"> </p> <div class="image-gallery clearfix"> @if (isset($images)) @foreach ($images as $image) <div class="image-preview" style="background-image:url({{$image->getThumbUrl()}})"> <span><i class="fa fa-times"></i></span> <input type="hidden" name="{{ $name or 'images' }}[]" value="{{ $image_id or '' }}"> </div> @endforeach @endif </div> <p class="text-muted">Drag and drop to change the order of images.</p> <template> <div class="image-preview"> <span><i class="fa fa-times"></i></span> <input type="hidden" name="{{ $name or 'images' }}[]"> </div> </template> </div>
Fix infinitely loading infinite list
import update from 'immutability-helper' import ActionTypes from '../actionTypes' const initialState = { currentPageIndex: 0, isLoading: false, listItems: [], totalPageCount: 0, } export default (state = initialState, action) => { switch (action.type) { case ActionTypes.INFINITE_LIST_INITIALIZE: return update(state, { currentPageIndex: { $set: 0 }, isLoading: { $set: true }, listItems: { $set: [] }, totalPageCount: { $set: 0 }, }) case ActionTypes.INFINITE_LIST_REQUEST: return update(state, { currentPageIndex: { $set: action.meta.page }, isLoading: { $set: true }, }) case ActionTypes.INFINITE_LIST_SUCCESS: return update(state, { isLoading: { $set: false }, listItems: { $push: action.payload.data }, totalPageCount: { $set: Math.floor((action.payload.total - 1) / action.payload.limit), }, }) case ActionTypes.INFINITE_LIST_FAILURE: return update(state, { isLoading: { $set: false }, }) default: return state } }
import update from 'immutability-helper' import ActionTypes from '../actionTypes' const initialState = { currentPageIndex: 0, isLoading: false, listItems: [], totalPageCount: 0, } export default (state = initialState, action) => { switch (action.type) { case ActionTypes.INFINITE_LIST_INITIALIZE: return update(state, { currentPageIndex: { $set: 0 }, isLoading: { $set: true }, listItems: { $set: [] }, }) case ActionTypes.INFINITE_LIST_REQUEST: return update(state, { currentPageIndex: { $set: action.meta.page }, isLoading: { $set: true }, }) case ActionTypes.INFINITE_LIST_SUCCESS: return update(state, { isLoading: { $set: false }, listItems: { $push: action.payload.data }, totalPageCount: { $set: Math.floor((action.payload.total - 1) / action.payload.limit), }, }) case ActionTypes.INFINITE_LIST_FAILURE: return update(state, { isLoading: { $set: false }, }) default: return state } }
Fix to iterate over dictionary using items instead of iteritems to make it compatible with python3.x.
# -*- coding: utf-8 -*- from django.conf import settings __all__ = ( 'settings', ) default_settings = { 'SLACK_CLIENT_ID': None, 'SLACK_CLIENT_SECRET': None, 'SLACK_AUTHORIZATION_URL': 'https://slack.com/oauth/authorize', 'SLACK_OAUTH_ACCESS_URL': 'https://slack.com/api/oauth.access', 'SLACK_SUCCESS_REDIRECT_URL': '/', 'SLACK_SCOPE': 'identify,read,post', } class Settings(object): def __init__(self, app_settings, defaults): for k, v in defaults.items(): setattr(self, k, getattr(app_settings, k, v)) settings = Settings(settings, default_settings)
# -*- coding: utf-8 -*- from django.conf import settings __all__ = ( 'settings', ) default_settings = { 'SLACK_CLIENT_ID': None, 'SLACK_CLIENT_SECRET': None, 'SLACK_AUTHORIZATION_URL': 'https://slack.com/oauth/authorize', 'SLACK_OAUTH_ACCESS_URL': 'https://slack.com/api/oauth.access', 'SLACK_SUCCESS_REDIRECT_URL': '/', 'SLACK_SCOPE': 'identify,read,post', } class Settings(object): def __init__(self, app_settings, defaults): for k, v in defaults.iteritems(): setattr(self, k, getattr(app_settings, k, v)) settings = Settings(settings, default_settings)
Refactor test to use BeforeEach to initialize
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class MathUtilsTest { MathUtils mathUtils; @BeforeEach void init(){ mathUtils = new MathUtils(); } @Test void testAdd() { assertEquals(5, mathUtils.add(3,2), "The add method should add two numbers"); } @Test void testDivide(){ assertEquals(3,mathUtils.divide(6,2), "Divide method should divide two numbers"); assertThrows(ArithmeticException.class, () -> mathUtils.divide(1,0), "Divide by zero should throw"); } @Test void testComputeArea() { assertEquals(78,mathUtils.computeArea(5),"Compute area method should return circle area"); } }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class MathUtilsTest { @Test void testAdd() { MathUtils math = new MathUtils(); assertEquals(5, math.add(3,2), "The add method should add two numbers"); } @Test void testDivide(){ MathUtils math = new MathUtils(); assertEquals(3,math.divide(6,2), "Divide method should divide two numbers"); assertThrows(ArithmeticException.class, () -> math.divide(1,0), "Divide by zero should throw"); } @Test void testComputeArea() { MathUtils math = new MathUtils(); assertEquals(78,math.computeArea(5),"Compute area method should return circle area"); } }
[Instabot] Make example bot use keepalive
#!/usr/bin/env python3 # -*- coding: ascii -*- # A small example bot for Instant. import sys import instabot NICKNAME = 'Echo' def post_cb(self, msg, meta): if msg['text'].startswith('!echo '): return msg['text'][6:] def main(): b = instabot.CmdlineBotBuilder(defnick=NICKNAME) b.make_parser(sys.argv[0], desc='An Instant bot bouncing back received messages.') b.parse(sys.argv[1:]) bot = b(keepalive=True, post_cb=post_cb) try: bot.run() except KeyboardInterrupt: sys.stderr.write('\n') finally: bot.close() if __name__ == '__main__': main()
#!/usr/bin/env python3 # -*- coding: ascii -*- # A small example bot for Instant. import sys import instabot NICKNAME = 'Echo' def post_cb(self, msg, meta): if msg['text'].startswith('!echo '): return msg['text'][6:] def main(): b = instabot.CmdlineBotBuilder(defnick=NICKNAME) b.make_parser(sys.argv[0], desc='An Instant bot bouncing back received messages.') b.parse(sys.argv[1:]) bot = b(post_cb=post_cb) try: bot.run() except KeyboardInterrupt: sys.stderr.write('\n') finally: bot.close() if __name__ == '__main__': main()
Fix download link for non-latest releases.
"use strict"; var path = require('path'), exec = require('child_process').exec; module.exports = function (grunt) { grunt.registerTask('data-download', '1. Download data from iana.org/time-zones.', function (version) { version = version || 'latest'; var done = this.async(), src = 'ftp://ftp.iana.org/tz/tzdata-latest.tar.gz', curl = path.resolve('temp/curl', version, 'data.tar.gz'), dest = path.resolve('temp/download', version); if (version !== 'latest') { src = 'http://www.iana.org/time-zones/repository/releases/tzdata' + version + '.tar.gz'; } grunt.file.mkdir(path.dirname(curl)); grunt.file.mkdir(dest); grunt.log.ok('Downloading ' + src); exec('curl ' + src + ' -o ' + curl + ' && cd ' + dest + ' && gzip -dc ' + curl + ' | tar -xf -', function (err) { if (err) { throw err; } grunt.log.ok('Downloaded ' + src); done(); }); }); };
"use strict"; var path = require('path'), exec = require('child_process').exec; module.exports = function (grunt) { grunt.registerTask('data-download', '1. Download data from iana.org/time-zones.', function (version) { version = version || 'latest'; var done = this.async(), src = 'ftp://ftp.iana.org/tz/tzdata-' + version + '.tar.gz', curl = path.resolve('temp/curl', version, 'data.tar.gz'), dest = path.resolve('temp/download', version); grunt.file.mkdir(path.dirname(curl)); grunt.file.mkdir(dest); exec('curl ' + src + ' -o ' + curl + ' && cd ' + dest + ' && gzip -dc ' + curl + ' | tar -xf -', function (err) { if (err) { throw err; } grunt.log.ok('Downloaded ' + src); done(); }); }); };
Use a placeholder for body content.
import { Component } from 'substance' export default class BodyComponent extends Component { render($$) { const body = this.props.node let el = $$('div') .addClass('sc-body') .attr('data-id', body.id) // There can be multiple abstracts. We just take the first const content = body.findChild('body-content') let contentEl if (content) { contentEl = $$(this.getComponent('container'), { placeholder: 'Enter Text', name: 'bodyEditor', node: content, disabled: this.props.disabled }) } else { // TODO: ability to add an abstract } el.append(contentEl) // optional sig-block let sigBlock = body.findChild('sig-block') if (sigBlock) { el.append( $$(this.getComponent('sig-block'), { node: sigBlock }) ) } else { // TODO: means to add a signature } return el } }
import { Component } from 'substance' export default class BodyComponent extends Component { render($$) { const body = this.props.node let el = $$('div') .addClass('sc-body') .attr('data-id', body.id) // There can be multiple abstracts. We just take the first const content = body.findChild('body-content') let contentEl if (content) { contentEl = $$(this.getComponent('container'), { name: 'bodyEditor', node: content, disabled: this.props.disabled }) } else { // TODO: ability to add an abstract } el.append(contentEl) // optional sig-block let sigBlock = body.findChild('sig-block') if (sigBlock) { el.append( $$(this.getComponent('sig-block'), { node: sigBlock }) ) } else { // TODO: means to add a signature } return el } }
Move exclude pattern to its own line.
from django.conf import settings # The name of the iterable ``django-discoverage`` looks for in the discovery # process TESTED_APPS_VAR_NAME = getattr(settings, 'TESTED_APPS_VAR_NAME', 'TESTS_APPS') # Modules not to trace COVERAGE_OMIT_MODULES = getattr(settings, 'COVERAGE_OMIT_MODULES', ['*test*']) COVERAGE_EXCLUDE_PATTERNS = getattr(settings, 'COVERAGE_EXCLUDE_PATTERNS', [ r'def __unicode__\(self\):', r'def __str__\(self\):', r'def get_absolute_url\(self\):', r'from .* import .*', r'import .*', ]) # Determines whether the apps to be included in the coverage report # should be inferred from the test's subpackage name PKG_NAME_APP_DISCOVERY = getattr(settings, 'PKG_NAME_APP_DISCOVERY', True) # Determines whether tested apps are guessed from module names MODULE_NAME_APP_DISCOVERY = getattr(settings, 'MODULE_NAME_APP_DISCOVERY', False) MODULE_NAME_DISCOVERY_PATTERN = getattr(settings, 'MODULE_NAME_DISCOVERY_PATTERN', r'test_?(\w+)')
from django.conf import settings # The name of the iterable ``django-discoverage`` looks for in the discovery # process TESTED_APPS_VAR_NAME = getattr(settings, 'TESTED_APPS_VAR_NAME', 'TESTS_APPS') # Modules not to trace COVERAGE_OMIT_MODULES = getattr(settings, 'COVERAGE_OMIT_MODULES', ['*test*']) COVERAGE_EXCLUDE_PATTERNS = getattr(settings, 'COVERAGE_EXCLUDE_PATTERNS', [ r'def __unicode__\(self\):', r'def __str__\(self\):', r'def get_absolute_url\(self\):', r'from .* import .*', 'import .*', ]) # Determines whether the apps to be included in the coverage report # should be inferred from the test's subpackage name PKG_NAME_APP_DISCOVERY = getattr(settings, 'PKG_NAME_APP_DISCOVERY', True) # Determines whether tested apps are guessed from module names MODULE_NAME_APP_DISCOVERY = getattr(settings, 'MODULE_NAME_APP_DISCOVERY', False) MODULE_NAME_DISCOVERY_PATTERN = getattr(settings, 'MODULE_NAME_DISCOVERY_PATTERN', r'test_?(\w+)')
Fix missing config in verify_config call
var api = require('digio-api') , cmd = require('./cli') , fs = require('fs') , _package = require('../package.json') , path = require('path') , tools = require('./tools') var digio = (function () { cmd .version('Digio v' + _package.version) var _config = tools.load_config() if (_config && tools.verify_config(_config)) { var commands = fs.readdirSync(__dirname + '/commands').filter(function (e) { return /(\.(js)$)/i.test(path.extname(e)) }) commands.forEach(function(command) { require('./commands/' + command)(cmd) }); } cmd.parse() })() module.exports = digio
var api = require('digio-api') , cmd = require('./cli') , fs = require('fs') , _package = require('../package.json') , path = require('path') , tools = require('./tools') var digio = (function () { cmd .version('Digio v' + _package.version) var _config = tools.load_config() if (_config && tools.verify_config()) { var commands = fs.readdirSync(__dirname + '/commands').filter(function (e) { return /(\.(js)$)/i.test(path.extname(e)) }) commands.forEach(function(command) { require('./commands/' + command)(cmd) }); } cmd.parse() })() module.exports = digio
Make Balance get the balance from the Wallets instead of the db
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = mongoose.Schema.Types.ObjectId; var User = require("./user_model"); var Ledger = require("./ledger_model"); var Wallet = require("./wallet_model"); var Currency = require("./currency_model"); var BalanceSchema = new Schema({ user_id: { type: ObjectId, index: true, ref: "User", required: true }, cred_type: { type: String, validate: /space|stuff/, index: true, required: true }, balance: Number, last_update: Date, ledger_id: { type: ObjectId, index: true, ref: "Ledger" }, _owner_id: ObjectId, }); BalanceSchema.set("_perms", { admin: "crud", owner: "cr", user: "r", all: "" }); BalanceSchema.pre("save", function(next) { var self = this; this._owner_id = this.user_id; // Ensure the owner is always the user for this model next(); }); BalanceSchema.post("init", function(o) { Currency.find() .then(currencies => { var currency = currencies.find(currency => { return currency.name.toLowerCase() === o.cred_type; }); return Wallet.find({ user_id: o.user_id, currency_id: currency._id }); }) .then(result => { o.balance = result.reduce((sum, b) => (sum + b), 0); return o; }); }); module.exports = mongoose.model('Balance', BalanceSchema);
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = mongoose.Schema.Types.ObjectId; var User = require("./user_model"); var Ledger = require("./ledger_model"); var Q = require("q"); var BalanceSchema = new Schema({ user_id: { type: ObjectId, index: true, ref: "User", required: true }, cred_type: { type: String, validate: /space|stuff|daily/, index: true, required: true }, balance: Number, last_update: Date, ledger_id: { type: ObjectId, index: true, ref: "Ledger" }, _owner_id: ObjectId, }); BalanceSchema.set("_perms", { admin: "crud", owner: "cr", user: "r", all: "" }); BalanceSchema.pre("save", function(next) { var self = this; this._owner_id = this.user_id; // Ensure the owner is always the user for this model next(); }); module.exports = mongoose.model('Balance', BalanceSchema);
Make use of the lastField variable
var lastField = null; var currentFillColor = ''; // ??? var changeCounter = 0; // ??? function setField(element) { // element contains the current html element if (element.style.backgroundColor !== currentFillColor) { element.style.backgroundColor = currentFillColor; } else { element.style.backgroundColor = '#eee'; } if (lastField === element) { ++changeCounter; } else { changeCounter = 0; } if (changeCounter === 10) { alert('You have clicked 10 times on the field!'); changeCounter = 0; } lastField = element; } function setFillColor(color) { // color should be a string var logEntry = document.createElement('p'); logEntry.appendChild(document.createTextNode('Color changed')); logEntry.style.color = currentFillColor = color; document.getElementById('Log').appendChild(logEntry); }
var lastField = null; var currentFillColor = ''; // ??? var changeCounter = 0; // ??? function setField(element) { // element contains the current html element if (element.style.backgroundColor !== currentFillColor) { element.style.backgroundColor = currentFillColor; } else { element.style.backgroundColor = '#eee'; } if (++changeCounter === 10) { alert('You have clicked 10 times on the field!'); // Should the counter be reset after the alert? // changeCounter = 0; } } function setFillColor(color) { // color should be a string var logEntry = document.createElement('p'); logEntry.appendChild(document.createTextNode('Color changed')); logEntry.style.color = currentFillColor = color; document.getElementById('Log').appendChild(logEntry); }
Fix school vocal term manager test
import Ember from 'ember'; import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; const { Object, RSVP } = Ember; const { resolve } = RSVP; moduleForComponent('school-vocabulary-manager', 'Integration | Component | school vocabulary manager', { integration: true }); test('it renders', function(assert) { let vocabulary = Object.create({ title: 'fake vocab', terms: resolve([]) }); this.set('vocabulary', vocabulary); this.on('nothing', parseInt); this.render(hbs`{{school-vocabulary-manager vocabulary=vocabulary manageTerm=(action 'nothing') manageVocabulary=(action 'nothing') }}`); const all = '.breadcrumbs span:eq(0)'; const vocab = '.breadcrumbs span:eq(1)'; assert.equal(this.$(all).text().trim(), 'All Vocabularies'); assert.equal(this.$(vocab).text().trim(), vocabulary.title); });
import Ember from 'ember'; import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; const { Object, RSVP } = Ember; const { resolve } = RSVP; moduleForComponent('school-vocabulary-manager', 'Integration | Component | school vocabulary manager', { integration: true }); test('it renders', function(assert) { let vocabulary = Object.create({ title: 'fake vocab', topLevelTerms: resolve([]) }); this.set('vocabulary', vocabulary); this.on('nothing', parseInt); this.render(hbs`{{school-vocabulary-manager vocabulary=vocabulary manageTerm=(action 'nothing') manageVocabulary=(action 'nothing') }}`); const all = '.breadcrumbs span:eq(0)'; const vocab = '.breadcrumbs span:eq(1)'; assert.equal(this.$(all).text().trim(), 'All Vocabularies'); assert.equal(this.$(vocab).text().trim(), vocabulary.title); });
Use get_backend in proxy methods
from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.db.models.query import QuerySet from .backends import get_backend class FollowQuerySet(QuerySet): pass class FollowManager(models.Manager): def get_query_set(self): return FollowQuerySet(self.model) @python_2_unicode_compatible class Follow(models.Model): created_at = models.DateTimeField(auto_now_add=True) from_object_id = models.PositiveIntegerField() from_identifier = models.CharField(max_length=50, db_index=True) to_object_id = models.PositiveIntegerField() to_identifier = models.CharField(max_length=50, db_index=True) objects = FollowManager() def __str__(self): return '<%s: %d>' % (self.identifier, self.object_id) def follow(from_instance, to_instance): return get_backend().follow(from_instance, to_instance) def is_following(from_instance, to_instance): return get_backend().is_following(from_instance, to_instance) def unfollow(from_instance, to_instance): return get_backend().unfollow(from_instance, to_instance) def get_followings(instance): return get_backend().get_followings(instance) def get_followers(instance): return get_backend().get_followers(instance)
from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.db.models.query import QuerySet class FollowQuerySet(QuerySet): pass class FollowManager(models.Manager): def get_query_set(self): return FollowQuerySet(self.model) @python_2_unicode_compatible class Follow(models.Model): created_at = models.DateTimeField(auto_now_add=True) from_object_id = models.PositiveIntegerField() from_identifier = models.CharField(max_length=50, db_index=True) to_object_id = models.PositiveIntegerField() to_identifier = models.CharField(max_length=50, db_index=True) objects = FollowManager() def __str__(self): return '<%s: %d>' % (self.identifier, self.object_id) def follow(from_instance, to_instance): pass def is_following(from_instance, to_instance): pass def unfollow(from_instance, to_instance): pass def get_followings(instance): pass def get_followers(instance): pass
Add geometry_application_reference to new unique index.
"""empty message Revision ID: 1815829d365 Revises: 3fcddd64a72 Create Date: 2016-02-09 17:58:47.362133 """ # revision identifiers, used by Alembic. revision = '1815829d365' down_revision = '3fcddd64a72' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### # create new unique index to include geometry_application_ref op.execute("DROP INDEX title_abr_idx") op.execute("CREATE UNIQUE INDEX title_abr_geo_idx ON records((record->'data'->>'title_number'),(record->'data'->>'application_reference'), (record->'data'->>'geometry_application_reference'))") ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.execute("DROP INDEX title_abr_geo_idx") op.execute("CREATE UNIQUE INDEX title_abr_idx ON records((record->'data'->>'title_number'),(record->'data'->>'application_reference'))") ### end Alembic commands ###
"""empty message Revision ID: 1815829d365 Revises: 3fcddd64a72 Create Date: 2016-02-09 17:58:47.362133 """ # revision identifiers, used by Alembic. revision = '1815829d365' down_revision = '3fcddd64a72' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### # create new unique index to include geo app ref op.execute("DROP INDEX title_abr_idx") op.execute("CREATE UNIQUE INDEX title_abr_geo_idx ON records((record->'data'->>'title_number'),(record->'data'->>'application_reference'), (record->'data'->>'geometry_application_reference'))") ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.execute("DROP INDEX title_abr_geo_idx") op.execute("CREATE UNIQUE INDEX title_abr_idx ON records((record->'data'->>'title_number'),(record->'data'->>'application_reference'))") ### end Alembic commands ###
Refactor to avoid dynamic module resolution
'use strict'; /** * Constructor returning an object used to represent a generic, fixed-length raw binary data buffer which can be used to create views of shared memory. * * @module @stdlib/array/shared-buffer * * @example * var ctor = require( '@stdlib/array/shared-buffer' ); * * var buf; * try { * buf = new ctor( 10 ); * // returns <SharedArrayBuffer> * } catch ( err ) { * console.log( 'Environment does not support SharedArrayBuffers.' ); * } */ // MODULES // var hasSharedArrayBufferSupport = require( '@stdlib/utils/detect-sharedarraybuffer-support' ); var builtin = require( './sharedarraybuffer.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasSharedArrayBufferSupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor;
'use strict'; /** * Constructor returning an object used to represent a generic, fixed-length raw binary data buffer which can be used to create views of shared memory. * * @module @stdlib/array/shared-buffer * * @example * var ctor = require( '@stdlib/array/shared-buffer' ); * * var buf; * try { * buf = new ctor( 10 ); * // returns <SharedArrayBuffer> * } catch ( err ) { * console.log( 'Environment does not support SharedArrayBuffers.' ); * } */ // MODULES // var hasSharedArrayBufferSupport = require( '@stdlib/utils/detect-sharedarraybuffer-support' ); // MAIN // var ctor; if ( hasSharedArrayBufferSupport() ) { ctor = require( './sharedarraybuffer.js' ); } else { ctor = require( './polyfill.js' ); } // EXPORTS // module.exports = ctor;
Increment GCS Client PyPi version to 1.9.15.0. - Just doing whatever the most recent GAE version is for the package version. R=tkaitchuck DELTA=1 (0 added, 0 deleted, 1 changed) Revision created by MOE tool push_codebase. MOE_MIGRATION=7186
"""Setup specs for packaging, distributing, and installing gcs lib.""" import distribute_setup distribute_setup.use_setuptools() import setuptools setuptools.setup( name="GoogleAppEngineCloudStorageClient", version="1.9.15.0", packages=setuptools.find_packages(), author="Google App Engine", author_email="app-engine-pipeline-api@googlegroups.com", keywords="google app engine cloud storage", url="https://code.google.com/p/appengine-gcs-client/", license="Apache License 2.0", description=("This library is the preferred way of accessing Google " "Cloud Storage from App Engine. It was designed to " "replace the Files API. As a result it contains much " "of the same functionality (streaming reads and writes but " "not the complete set of GCS APIs). It also provides key " "stability improvements and a better overall developer " "experience."), exclude_package_data={"": ["README"]}, zip_safe=True, )
"""Setup specs for packaging, distributing, and installing gcs lib.""" import distribute_setup distribute_setup.use_setuptools() import setuptools setuptools.setup( name="GoogleAppEngineCloudStorageClient", version="1.9.5.0", packages=setuptools.find_packages(), author="Google App Engine", author_email="app-engine-pipeline-api@googlegroups.com", keywords="google app engine cloud storage", url="https://code.google.com/p/appengine-gcs-client/", license="Apache License 2.0", description=("This library is the preferred way of accessing Google " "Cloud Storage from App Engine. It was designed to " "replace the Files API. As a result it contains much " "of the same functionality (streaming reads and writes but " "not the complete set of GCS APIs). It also provides key " "stability improvements and a better overall developer " "experience."), exclude_package_data={"": ["README"]}, zip_safe=True, )
Fix .format() patterns in test for Python 2.6
"""Tests against HORIZONS numbers.""" from skyfield import api # see the top-level project ./horizons/ directory for where the # following numbers come from; soon, we should automate the fetching of # such numbers and their injection into test cases, as we do for results # from NOVAS. """ Date__(UT)__HR:MN hEcl-Lon hEcl-Lat r rdot ******************************************************************** $$SOE 1980-Jan-01 00:00 151.3229 1.0130 5.378949180806 0.4314383 $$EOE """ def test_ecliptic_latlon(): astrometric = api.sun(utc=(1980, 1, 1)).observe(api.jupiter) lat, lon, distance = astrometric.ecliptic_latlon() assert '{0:.4f}'.format(lat.degrees) == '1.0130' assert '{0:.4f}'.format(lon.degrees) == '151.3227' # That last value should really be '151.3227' according to HORIZONS # but we are just getting started here so the tiny difference is # being filed away as something to look at later!
"""Tests against HORIZONS numbers.""" from skyfield import api # see the top-level project ./horizons/ directory for where the # following numbers come from; soon, we should automate the fetching of # such numbers and their injection into test cases, as we do for results # from NOVAS. """ Date__(UT)__HR:MN hEcl-Lon hEcl-Lat r rdot ******************************************************************** $$SOE 1980-Jan-01 00:00 151.3229 1.0130 5.378949180806 0.4314383 $$EOE """ def test_ecliptic_latlon(): astrometric = api.sun(utc=(1980, 1, 1)).observe(api.jupiter) lat, lon, distance = astrometric.ecliptic_latlon() assert '{:.4f}'.format(lat.degrees) == '1.0130' assert '{:.4f}'.format(lon.degrees) == '151.3227' # That last value should really be '151.3227' according to HORIZONS # but we are just getting started here so the tiny difference is # being filed away as something to look at later!
Remove non used namespace from extension class
<?php namespace Usoft\IDealBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class UsoftIDealExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $container->setParameter('mollie_key', $config['mollie']['key']); $container->setParameter('mollie_description', $config['mollie']['description']); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); } }
<?php namespace Usoft\IDealBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\DefinitionDecorator; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class UsoftIDealExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $container->setParameter('mollie_key', $config['mollie']['key']); $container->setParameter('mollie_description', $config['mollie']['description']); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); } }
Fix typo and file path
var chp = require('child_process'); var Git = { stageFile: function(modulePath, file, callback) { if (file.status === 'deleted') { this._exec(modulePath, 'rm', [file.name], callback); } else { if (file.type === 'submodule') this._exec(modulePath, 'submodule add', ['.' + require('path').sep + file.name], callback); else this._exec(modulePath, 'add', [file.name], callback); } }, unstageFile: function(modulePath, file, callback) { this._exec(modulePath, 'reset HEAD', [file.name], callback); }, commit: function(modulePath, message, callback) { this._exec(modulePath, 'commit -m', [message], callback); }, push: function(modulePath, callback) { this._exec(modulePath, 'push', [], callback); }, _exec: function(modulePath, cmd, args, callback) { var escapedArgs = args.map(function(arg) { return '"' + arg.replace(/["\\]/g, '\\$1') + '"'; }).join(' '); cmd = 'git ' + cmd + ' ' + escapedArgs; chp.exec(cmd, {cwd: modulePath}, function(err, stdout, stderr) { if (err) console.error(err, stdout, stderr); callback(null, stdout); }); } }; module.exports = Git;
var chp = require('child_process'); var Git = { stageFile: function(modulePath, file, callback) { if (file.status === 'deleted') { this._exec(modulePath, 'rm', [file.name], callback); } else { if (file.type === 'submodule') this.exec(modulePath, 'submodule add', [file.name], callback); else this._exec(modulePath, 'add', [file.name], callback); } }, unstageFile: function(modulePath, file, callback) { this._exec(modulePath, 'reset HEAD', [file.name], callback); }, commit: function(modulePath, message, callback) { this._exec(modulePath, 'commit -m', [message], callback); }, push: function(modulePath, callback) { this._exec(modulePath, 'push', [], callback); }, _exec: function(modulePath, cmd, args, callback) { var escapedArgs = args.map(function(arg) { return '"' + arg.replace(/["\\]/g, '\\$1') + '"'; }).join(' '); cmd = 'git ' + cmd + ' ' + escapedArgs; chp.exec(cmd, {cwd: modulePath}, function(err, stdout, stderr) { if (err) console.error(err, stdout, stderr); callback(null, stdout); }); } }; module.exports = Git;
COOPR-652: Set connection close on calls to /status
/* * Copyright © 2012-2014 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package co.cask.coopr.http.handler; import co.cask.http.AbstractHttpHandler; import co.cask.http.HttpResponder; import com.google.common.collect.ImmutableMultimap; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import javax.ws.rs.GET; import javax.ws.rs.Path; /** * Serves status URL. */ public class StatusHandler extends AbstractHttpHandler { /** * Returns the status of the server, which just returns OK if it is handling requests. Used as a healthcheck. * * @param request The request for server status. * @param responder Responder for sending the request. */ @Path("/status") @GET public void status(@SuppressWarnings("UnusedParameters") HttpRequest request, HttpResponder responder) { responder.sendString(HttpResponseStatus.OK, "OK\n", ImmutableMultimap.of("Connection", "close")); } }
/* * Copyright © 2012-2014 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package co.cask.coopr.http.handler; import co.cask.http.AbstractHttpHandler; import co.cask.http.HttpResponder; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import javax.ws.rs.GET; import javax.ws.rs.Path; /** * Serves status URL. */ public class StatusHandler extends AbstractHttpHandler { /** * Returns the status of the server, which just returns OK if it is handling requests. Used as a healthcheck. * * @param request The request for server status. * @param responder Responder for sending the request. */ @Path("/status") @GET public void status(@SuppressWarnings("UnusedParameters") HttpRequest request, HttpResponder responder) { responder.sendString(HttpResponseStatus.OK, "OK\n"); } }
Use forloop instead of filter for backward compliance
/** * The Diode emits a heartbeat whenever any store state has changed. * When Stores change, they can use this entity to broadcast * that state has changed. */ function Diode (target) { var _callbacks = [] if (this instanceof Diode) { target = this } else { target = target || {} } /** * Given a CALLBACK function, add it to the Set of all callbacks. */ target.listen = target.subscribe = function (callback) { if (typeof callback !== 'function') { throw new TypeError('callback must be a function') } _callbacks.push(callback) return target } /** * Given a CALLBACK function, remove it from the set of callbacks. * Throws an error if the callback is not included in the set. */ target.ignore = target.unsubscribe = function (callback) { for (var i = 0, len = _callbacks.length; i < len; i++) { if (_callbacks[i] === callback) { _callbacks.splice(i, 1) } } return target } /** * Immediately trigger every callback */ target.emit = target.publish = function (...args) { /** * Important: do not cache the length of _callbacks * in the event a callback causes later subscriptions * to disappear */ for (var i = 0; i < _callbacks.length; i++) { _callbacks[i].apply(target, args) } return target } return target } module.exports = Diode(Diode) module.exports.decorate = Diode
/** * The Diode emits a heartbeat whenever any store state has changed. * When Stores change, they can use this entity to broadcast * that state has changed. */ function Diode (target) { var _callbacks = [] if (this instanceof Diode) { target = this } else { target = target || {} } /** * Given a CALLBACK function, add it to the Set of all callbacks. */ target.listen = target.subscribe = function (callback) { if (typeof callback !== 'function') { throw new TypeError('callback must be a function') } _callbacks.push(callback) return target } /** * Given a CALLBACK function, remove it from the set of callbacks. * Throws an error if the callback is not included in the Set. */ target.ignore = target.unsubscribe = function (callback) { _callbacks = _callbacks.filter(function (i) { return i !== callback }) return target } /** * Immediately trigger every callback */ target.emit = target.publish = function (...args) { /** * Important: do not cache the length of _callbacks * in the event a callback causes later subscriptions * to disappear */ for (var i = 0; i < _callbacks.length; i++) { _callbacks[i].apply(target, args) } return target } return target } module.exports = Diode(Diode) module.exports.decorate = Diode
Fix arity of skip param
package me.coley.recaf.util; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import me.coley.recaf.Logging; import picocli.CommandLine.Option; public class LaunchParams implements Runnable { @Option(names = { "-i", "--input" }, description = "Jar file to read.") public File initialFile; @Option(names = { "-c", "--class" }, description = "Initial class to open.") public String initialClass; @Option(names = { "-s", "--skip" }, description = "Classes in the input to ignore.", arity = "0..*") public List<String> skipped = new ArrayList<>(); @Override public void run() { if (initialFile != null) Logging.info("CLI file: " + initialFile); if (initialClass != null) Logging.info("CLI class: " + initialClass); if (skipped != null) Logging.info("CLI Skipped packages: " + skipped.size()); } }
package me.coley.recaf.util; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import me.coley.recaf.Logging; import picocli.CommandLine.Option; public class LaunchParams implements Runnable { @Option(names = { "-i", "--input" }, description = "Jar file to read.") public File initialFile; @Option(names = { "-c", "--class" }, description = "Initial class to open.") public String initialClass; @Option(names = { "-s", "--skip" }, description = "Classes in the input to ignore.", arity = "1..*") public List<String> skipped = new ArrayList<>(); @Override public void run() { if (initialFile != null) Logging.info("CLI file: " + initialFile); if (initialClass != null) Logging.info("CLI class: " + initialClass); if (skipped != null) Logging.info("CLI Skipped packages: " + skipped.size()); } }
Fix broken relative route check logic. href.slice(root.length) returns the href _without_ the root. We want the href without the fragments.
require([ // Application. "app", // Main Router. "router" ], function(app, Router) { // Define your master router on the application namespace and trigger all // navigation from this instance. app.router = new Router(); // Trigger the initial route and enable HTML5 History API support, set the // root folder to '/' by default. Change in app.js. Backbone.history.start({ pushState: true, root: app.root }); // All navigation that is relative should be passed through the navigate // method, to be processed by the router. If the link has a `data-bypass` // attribute, bypass the delegation completely. $(document).on("click", "a:not([data-bypass])", function(evt) { // Get the absolute anchor href. var href = $(this).prop("href"); // Get the absolute root. var root = location.protocol + "//" + location.host + app.root; // Ensure the root is part of the anchor href, meaning it's relative. if (href && href.slice(0, root.length) === root) { // Stop the default event to ensure the link will not cause a page // refresh. evt.preventDefault(); // `Backbone.history.navigate` is sufficient for all Routers and will // trigger the correct events. The Router's internal `navigate` method // calls this anyways. The fragment is sliced from the root. Backbone.history.navigate(href.slice(root.length), true); } }); });
require([ // Application. "app", // Main Router. "router" ], function(app, Router) { // Define your master router on the application namespace and trigger all // navigation from this instance. app.router = new Router(); // Trigger the initial route and enable HTML5 History API support, set the // root folder to '/' by default. Change in app.js. Backbone.history.start({ pushState: true, root: app.root }); // All navigation that is relative should be passed through the navigate // method, to be processed by the router. If the link has a `data-bypass` // attribute, bypass the delegation completely. $(document).on("click", "a:not([data-bypass])", function(evt) { // Get the absolute anchor href. var href = $(this).prop("href"); // Get the absolute root. var root = location.protocol + "//" + location.host + app.root; // Ensure the root is part of the anchor href, meaning it's relative. if (href && href.slice(root.length) === root) { // Stop the default event to ensure the link will not cause a page // refresh. evt.preventDefault(); // `Backbone.history.navigate` is sufficient for all Routers and will // trigger the correct events. The Router's internal `navigate` method // calls this anyways. The fragment is sliced from the root. Backbone.history.navigate(href.slice(root.length), true); } }); });
Add create method in Transcation controller. -cwc Next thing to do is add update method.
'use strict'; var mongoose = require('mongoose'); var Transaction = require('../models/Transaction'); mongoose.Promise = global.Promise; module.exports = mongoose.connection; var index = function (req, res, next) { Transaction.find({}).exec().then(function (trans) { res.json(trans); }).catch(function(error){ next(error); }); }; var show = function (req, res, next) { Transaction.find({"_id": req.params.id}).exec() .then(function(trans){ res.json(trans); }).catch(function(error){ next(error); }); }; var create = function (req, res, next) { // console.log(req.get('Content-Type')); // res.json(req.body.user_id); Transaction.create({ "user_id": req.body.user_id, "product_id": req.body.product_id, "status": req.body.status, "qty": req.body.qty }).then(function(trans){ res.json(trans); }) .catch(function(error){ next(error); }); }; var update = function (req, res, next) { // Transaction.findByIdAndUpdate(req.params.id, { $set: modify }, { new: true }).exec().then(function(trans) { // //console.log(person.toJSON()); // }) // .catch(console.error) }; module.exports = { index, show, create, update };
'use strict'; var mongoose = require('mongoose'); var Transaction = require('../models/Transaction'); mongoose.Promise = global.Promise; module.exports = mongoose.connection; var index = function (req, res, next) { Transaction.find({}).exec().then(function (trans) { res.json(trans); }).catch(function(error){ next(error); }); }; var show = function (req, res, next) { Transaction.find({"_id": req.params.id}).exec() .then(function(trans){ res.json(trans); }).catch(function(error){ next(error); }); }; var create = function (req, res, next) { Transaction.create({ user_id: req.body.user_id, product_id: req.body.product_id, status: req.body.status, qty: req.body.qty }).then(function(trans){ res.json(trans); }) .catch(function(error){ next(error); }); }; var update = function (req, res, next) { // Transaction.findByIdAndUpdate(req.params.id, { $set: modify }, { new: true }).exec().then(function(trans) { // //console.log(person.toJSON()); // }) // .catch(console.error) }; module.exports = { index, show, create, update };
Fix conflict with other js file
<?php /** * Plugin Name: Remove Post Attachment * Plugin URI: https://github.com/romainberger/wordpress-remove-post-attachment * Description: Allows detaching medias from a post from the gallery * Version: 0.1.2 * Author: Romain Berger * Author URI: http://romainberger.com * License: MIT */ /** * Add the js file to the admin */ function removePostAdminJs() { wp_enqueue_script('remove-post-attachment', plugins_url('/js/remove-post-attachment.js', __FILE__), false, 1, true); } add_filter('admin_enqueue_scripts', 'removePostAdminJs'); function removePostAttachmentAjax() { if (isset($_POST['id']) && $_POST['id']) { global $wpdb; if (current_user_can('upload_files')) { $wpdb->update($wpdb->posts, array( 'post_parent' => 0 ), array( 'id' => $_POST['id'], 'post_type' => 'attachment' )); } } exit; } add_action('wp_ajax_my_action', 'removePostAttachmentAjax');
<?php /** * Plugin Name: Remove Post Attachment * Plugin URI: https://github.com/romainberger/wordpress-remove-post-attachment * Description: Allows detaching medias from a post from the gallery * Version: 0.1.1 * Author: Romain Berger * Author URI: http://romainberger.com * License: MIT */ /** * Add the js file to the admin */ function removePostAdminJs() { wp_enqueue_script('admin-gallery', plugins_url('/js/remove-post-attachment.js', __FILE__), false, 1, true); } add_filter('admin_enqueue_scripts', 'removePostAdminJs'); function removePostAttachmentAjax() { if (isset($_POST['id']) && $_POST['id']) { global $wpdb; if (current_user_can('upload_files')) { $wpdb->update($wpdb->posts, array( 'post_parent' => 0 ), array( 'id' => $_POST['id'], 'post_type' => 'attachment' )); } } exit; } add_action('wp_ajax_my_action', 'removePostAttachmentAjax');
Add nullable on api_token column
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddApiTokenOnUsers extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (Schema::hasTable('users')) { Schema::table('users', function ($table) { $table->string('api_token')->unique()->nullable()->after('role'); }); } } /** * Reverse the migrations. * * @return void */ public function down() { if (Schema::hasColumn('users', 'api_token')) { Schema::table('users', function ($table) { $table->dropColumn('api_token'); }); } } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddApiTokenOnUsers extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function ($table) { $table->string('api_token')->unique()->after('role'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function ($table) { $table->dropColumn('api_token'); }); } }
Use string of Rho Namespace Instead of the URI object, need to use the string.
""" Knowledge provider that will respond to requests made by the rdf publisher or another bot. """ from sleekxmpp.plugins.base import base_plugin from rhobot.components.storage.client import StoragePayload from rdflib.namespace import FOAF from rhobot.namespace import RHO import logging logger = logging.getLogger(__name__) class KnowledgeProvider(base_plugin): name = 'knowledge_provider' description = 'Knowledge Provider' dependencies = {'rho_bot_storage_client', 'rho_bot_rdf_publish', } type_requirements = {str(FOAF.Person), str(RHO.Owner), } def plugin_init(self): pass def post_init(self): base_plugin.post_init(self) self.xmpp['rho_bot_rdf_publish'].add_message_handler(self._rdf_request_message) def _rdf_request_message(self, rdf_payload): logger.info('Looking up knowledge') form = rdf_payload['form'] payload = StoragePayload(form) intersection = self.type_requirements.intersection(set(payload.types())) if len(intersection) == len(payload.types()): results = self.xmpp['rho_bot_storage_client'].find_nodes(payload) if len(results['command']['form'].get_items()): return results['command']['form'] return None knowledge_provider = KnowledgeProvider
""" Knowledge provider that will respond to requests made by the rdf publisher or another bot. """ from sleekxmpp.plugins.base import base_plugin from rhobot.components.storage.client import StoragePayload from rdflib.namespace import FOAF import logging logger = logging.getLogger(__name__) class KnowledgeProvider(base_plugin): name = 'knowledge_provider' description = 'Knowledge Provider' dependencies = {'rho_bot_storage_client', 'rho_bot_rdf_publish', } type_requirements = {str(FOAF.Person), 'rho::owner', } def plugin_init(self): pass def post_init(self): base_plugin.post_init(self) self.xmpp['rho_bot_rdf_publish'].add_message_handler(self._rdf_request_message) def _rdf_request_message(self, rdf_payload): logger.info('Looking up knowledge') form = rdf_payload['form'] payload = StoragePayload(form) intersection = self.type_requirements.intersection(set(payload.types())) if len(intersection) == len(payload.types()): results = self.xmpp['rho_bot_storage_client'].find_nodes(payload) if len(results['command']['form'].get_items()): return results['command']['form'] return None knowledge_provider = KnowledgeProvider
Add openssl command to generate certificate
//@ts-check const fs = require("fs"); const https = require('https'); const tls = require("tls"); // use this command to create a new self-signed certificate // openssl req -x509 -sha256 -nodes -newkey rsa:2048 -days 365 -keyout localhost.key -out localhost.crt module.exports = function (iface) { /** @type { import("tls").TlsOptions } Server options object */ const serveroptions = { key: [fs.readFileSync("tiddlyserver.key")], // server key file cert: [fs.readFileSync("tiddlyserver.cer")], //server certificate // pfx: [fs.readFileSync("server.pfx")], //server pfx (key and cert) //passphrase for password protected server key and pfx files // passphrase: "", //list of certificate authorities for client certificates // ca: [fs.readFileSync("clients-laptop.cer")], //request client certificate // requestCert: true, //reject connections from clients that cannot present a certificate signed by one of the ca certificates // rejectUnauthorized: false, }; return serveroptions; }
//@ts-check const fs = require("fs"); const https = require('https'); const tls = require("tls"); module.exports = function (iface) { /** @type { import("tls").TlsOptions } Server options object */ const serveroptions = { key: [fs.readFileSync("tiddlyserver.key")], // server key file cert: [fs.readFileSync("tiddlyserver.cer")], //server certificate // pfx: [fs.readFileSync("server.pfx")], //server pfx (key and cert) //passphrase for password protected server key and pfx files // passphrase: "", //list of certificate authorities for client certificates // ca: [fs.readFileSync("clients-laptop.cer")], //request client certificate // requestCert: true, //reject connections from clients that cannot present a certificate signed by one of the ca certificates // rejectUnauthorized: false, }; return serveroptions; }
Allow for min version to be env var.
"use strict"; const cheerio = require("cheerio"); const semver = require("semver"); const scraper = require("./scraper"); const RELEASE = /^v\d+\.\d+\.\d+\/$/; const MIN_VERSION = process.env.MIN_NW_VERSION || "0.13.0"; scraper("http://dl.nwjs.io/") .then(function(body) { const $ = cheerio.load(body); const versions = $("a") .map(function(i, link) { return $(link).text(); }) .get() .filter(function(version) { return RELEASE.test(version); }) .map(function(version) { return version.replace("v", "").replace("/", ""); }) .filter(function(version) { return semver.gte(version, MIN_VERSION); }); versions.forEach(function(version) { console.log(version); }) });
"use strict"; const cheerio = require("cheerio"); const semver = require("semver"); const scraper = require("./scraper"); const RELEASE = /^v\d+\.\d+\.\d+\/$/; const MIN_VERSION = "0.13.0"; scraper("http://dl.nwjs.io/") .then(function(body) { const $ = cheerio.load(body); const versions = $("a") .map(function(i, link) { return $(link).text(); }) .get() .filter(function(version) { return RELEASE.test(version); }) .map(function(version) { return version.replace("v", "").replace("/", ""); }) .filter(function(version) { return semver.gte(version, MIN_VERSION); }); versions.forEach(function(version) { console.log(version); }) });
Add JSON Iterator Method to Utility
module.exports = { generateQueryString: function (data) { var ret = [] for (var d in data) if (data[d]) ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d])) return ret.join("&") }, base64Encoding: function (data) { return new Buffer(data).toString('base64') }, base64Decoding: function (data) { return new Buffer(data, 'base64') }, getUnixTimeStamp: function () { return Math.floor((new Date).getTime() / 1000) }, stringReplace: function (source, find, replace) { return source.replace(find, replace) }, inputChecker: function (reqInput, whiteList) { var input = Object.keys(reqInput) for (var i = 0; i < input.length; i++) if (whiteList.indexOf(input[i]) <= -1) return false return true }, JSONIterator: function (input, validator) { for (var i = 0; i < input.length; i++) if (validator.indexOf(input[i]) <= -1) return false return true } }
module.exports = { generateQueryString: function (data) { var ret = [] for (var d in data) if (data[d]) ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d])) return ret.join("&") }, base64Encoding: function (data) { return new Buffer(data).toString('base64') }, base64Decoding: function (data) { return new Buffer(data, 'base64') }, getUnixTimeStamp: function () { return Math.floor((new Date).getTime() / 1000) }, stringReplace: function (source, find, replace) { return source.replace(find, replace) }, inputChecker: function (reqInput, whiteList) { var input = Object.keys(reqInput) if (input.length != whiteList.length) return false for (var i = 0; i < input.length; i++) if (whiteList.indexOf(input[i]) <= -1) return false return true } }
Make path detection working properly on windows and less dependent on concrete project name
#!/usr/bin/env php <?php namespace Lmc\Steward; use Symfony\Component\Console\Application; use Lmc\Steward\Command\InstallCommand; use Lmc\Steward\Command\RunTestsCommand; function requireIfExists($file) { if (file_exists($file)) { return require_once $file; } } if (!requireIfExists(__DIR__ . '/../vendor/autoload.php') // when used directly && !requireIfExists(__DIR__ . '/../../../autoload.php') // when installed as dependency ) { die( 'You must set up the project dependencies, run the following commands:' . PHP_EOL . 'curl -sS https://getcomposer.org/installer | php' . PHP_EOL . 'php composer.phar install' . PHP_EOL ); } if (strpos(__DIR__, DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR) !== false) { // when installed as dependency define('STEWARD_BASE_DIR', realpath(__DIR__ . '/../../../..')); } else { // when used directly define('STEWARD_BASE_DIR', realpath(__DIR__ . '/..')); } $application = new Application('Steward', '0.0.1'); $application ->addCommands( [ new RunTestsCommand(), new InstallCommand(), ] ); $application->run();
#!/usr/bin/env php <?php namespace Lmc\Steward; use Symfony\Component\Console\Application; use Lmc\Steward\Command\InstallCommand; use Lmc\Steward\Command\RunTestsCommand; function requireIfExists($file) { if (file_exists($file)) { return require_once $file; } } if (!requireIfExists(__DIR__ . '/../vendor/autoload.php') // when used directly && !requireIfExists(__DIR__ . '/../../../autoload.php') // when installed as dependency ) { die( 'You must set up the project dependencies, run the following commands:' . PHP_EOL . 'curl -sS https://getcomposer.org/installer | php' . PHP_EOL . 'php composer.phar install' . PHP_EOL ); } if (strpos(__DIR__, 'vendor/lmc/steward/bin') !== false) { // when installed as dependency define('STEWARD_BASE_DIR', realpath(__DIR__ . '/../../../..')); } else { // when used directly define('STEWARD_BASE_DIR', realpath(__DIR__ . '/..')); } $application = new Application('Steward', '0.0.1'); $application ->addCommands( [ new RunTestsCommand(), new InstallCommand(), ] ); $application->run();
Test category and listener (removed the sources that are tested in their module) git-svn-id: afcf11d89342f630bd950d18a70234a9e277d909@60164 523d945c-050c-4681-91ec-863ad3bb968a
/* * Created on Mar 30, 2004 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package com.cosylab.acs.alarm; import junit.framework.Test; import junit.framework.TestSuite; /** * @author kzagar * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public class AllTests { public static Test suite() { TestSuite suite = new TestSuite("Test for com.cosylab.acs.alarm"); //$JUnit-BEGIN$ //suite.addTest(new TestSuite(AlarmSourceTest.class)); suite.addTest(new TestSuite(ACSCategoryDAOTest.class)); suite.addTest(new TestSuite(AlarmListener.class)); //$JUnit-END$ // suite.addTest(new TestSuite(AlarmUserTest.class)); // suite.addTest(new TestSuite(AlarmDefinitionTest.class)); return suite; } }
/* * Created on Mar 30, 2004 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package com.cosylab.acs.alarm; import junit.framework.Test; import junit.framework.TestSuite; /** * @author kzagar * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public class AllTests { public static Test suite() { TestSuite suite = new TestSuite("Test for com.cosylab.acs.alarm"); //$JUnit-BEGIN$ suite.addTest(new TestSuite(AlarmSourceTest.class)); suite.addTest(new TestSuite(ACSCategoryDAOTest.class)); suite.addTest(new TestSuite(AlarmListener.class)); //$JUnit-END$ // suite.addTest(new TestSuite(AlarmUserTest.class)); // suite.addTest(new TestSuite(AlarmDefinitionTest.class)); return suite; } }
Upgrade CTA dialog will appear when import fails with error 8001
var cdb = require('cartodb.js'); /** * Error details view, to be used together with an error object from an import model. */ module.exports = cdb.core.View.extend({ initialize: function() { this.user = this.options.user; this.err = this.options.err; }, render: function() { // Preventing problems checking if the error_code is a number or a string // we make the comparision with only double =. var sizeError = this.err.error_code && this.err.error_code == '8001'; var userCanUpgrade = !cdb.config.get('custom_com_hosted') && (!this.user.isInsideOrg() || this.user.isOrgAdmin()); var template = cdb.templates.getTemplate( sizeError && userCanUpgrade ? 'common/views/error_details_upgrade' : 'common/views/error_details' ); this.$el.html( template({ sizeError: sizeError, errorCode: this.err.error_code, title: this.err.title, text: this.err.what_about, itemQueueId: this.err.item_queue_id, userCanUpgrade: userCanUpgrade, showTrial: this.user.canStartTrial(), upgradeUrl: cdb.config.get('upgrade_url') }) ); return this; } });
var cdb = require('cartodb.js'); /** * Error details view, to be used together with an error object from an import model. */ module.exports = cdb.core.View.extend({ initialize: function() { this.user = this.options.user; this.err = this.options.err; }, render: function() { var sizeError = this.err.error_code && this.err.error_code === '8001'; var userCanUpgrade = !cdb.config.get('custom_com_hosted') && (!this.user.isInsideOrg() || this.user.isOrgAdmin()); var template = cdb.templates.getTemplate( sizeError && userCanUpgrade ? 'common/views/error_details_upgrade' : 'common/views/error_details' ); this.$el.html( template({ sizeError: sizeError, errorCode: this.err.error_code, title: this.err.title, text: this.err.what_about, itemQueueId: this.err.item_queue_id, userCanUpgrade: userCanUpgrade, showTrial: this.user.canStartTrial(), upgradeUrl: cdb.config.get('upgrade_url') }) ); return this; } });
Use collection instead of project
from django import dispatch from django.db import transaction from django.db.models import signals as model_signals from . import client from .pool import pool from resolwe.flow import models as flow_models, serializers as flow_serializers, views as flow_views # Register all viewsets with the query observer pool. # TODO: This should be moved to a separate application. pool.register_viewset(flow_views.CollectionViewSet) pool.register_viewset(flow_views.DataViewSet) # Setup model notifications. observer_client = client.QueryObserverClient() @dispatch.receiver(model_signals.post_save) def model_post_save(sender, instance, created=False, **kwargs): """ Signal emitted after any model is saved via Django ORM. :param sender: Model class that was saved :param instance: The actual instance that was saved :param created: True if a new row was created """ def notify(): table = sender._meta.db_table if created: observer_client.notify_table_insert(table) else: observer_client.notify_table_update(table) transaction.on_commit(notify) @dispatch.receiver(model_signals.post_delete) def model_post_delete(sender, instance, **kwargs): """ Signal emitted after any model is deleted via Django ORM. :param sender: Model class that was deleted :param instance: The actual instance that was removed """ def notify(): table = sender._meta.db_table observer_client.notify_table_remove(table) transaction.on_commit(notify)
from django import dispatch from django.db import transaction from django.db.models import signals as model_signals from . import client from .pool import pool from resolwe.flow import models as flow_models, serializers as flow_serializers, views as flow_views # Register all viewsets with the query observer pool. # TODO: This should be moved to a separate application. pool.register_viewset(flow_views.ProjectViewSet) pool.register_viewset(flow_views.DataViewSet) # Setup model notifications. observer_client = client.QueryObserverClient() @dispatch.receiver(model_signals.post_save) def model_post_save(sender, instance, created=False, **kwargs): """ Signal emitted after any model is saved via Django ORM. :param sender: Model class that was saved :param instance: The actual instance that was saved :param created: True if a new row was created """ def notify(): table = sender._meta.db_table if created: observer_client.notify_table_insert(table) else: observer_client.notify_table_update(table) transaction.on_commit(notify) @dispatch.receiver(model_signals.post_delete) def model_post_delete(sender, instance, **kwargs): """ Signal emitted after any model is deleted via Django ORM. :param sender: Model class that was deleted :param instance: The actual instance that was removed """ def notify(): table = sender._meta.db_table observer_client.notify_table_remove(table) transaction.on_commit(notify)
Fix missing required elements in SiteIdentification
package au.gov.ga.geodesy.support.mapper.dozer.populator; import au.gov.ga.geodesy.support.utils.GMLMiscTools; import au.gov.xml.icsm.geodesyml.v_0_3.SiteIdentificationType; /** * The translate simply copied the Countries (in Sopac Sitelog XML) across to the GeoesyML CountryCode elements. * This cleans those up by converting to the actual CountryCodes. * * @author brookes * */ public class SiteIdentificationTypePopulator extends GeodesyMLElementPopulator<SiteIdentificationType> { /** * Consider all required elements for this type and add any missing ones with default values. * * @param gnssReceiverType */ void checkAllRequiredElementsPopulated(SiteIdentificationType sensorType) { checkElementPopulated(sensorType, "siteName", GMLMiscTools.getEmptyString()); checkElementPopulated(sensorType, "cdpNumber", GMLMiscTools.getEmptyString()); checkElementPopulated(sensorType, "iersDOMESNumber", GMLMiscTools.getEmptyString()); } }
package au.gov.ga.geodesy.support.mapper.dozer.populator; import au.gov.ga.geodesy.support.utils.GMLGmlTools; import au.gov.ga.geodesy.support.utils.GMLMiscTools; import au.gov.xml.icsm.geodesyml.v_0_3.SiteIdentificationType; /** * The translate simply copied the Countries (in Sopac Sitelog XML) across to the GeoesyML CountryCode elements. * This cleans those up by converting to the actual CountryCodes. * * @author brookes * */ public class SiteIdentificationTypePopulator extends GeodesyMLElementPopulator<SiteIdentificationType> { /** * Consider all required elements for this type and add any missing ones with default values. * * @param gnssReceiverType */ void checkAllRequiredElementsPopulated(SiteIdentificationType sensorType) { checkElementPopulated(sensorType, "cdpNumber", GMLMiscTools.getEmptyString()); checkElementPopulated(sensorType, "iersDOMESNumber", GMLMiscTools.getEmptyString()); } }
Write what to do when there is a match: add to the repeated count
// Method that performs basic string compression using the counts of repeated characters function compressStr(str) { var output = "", // will return this variable as final compressed string currChar = "", // represents character we are searching for in string currCount = "", // counts number of times character is repeated maxCount = ""; // maximum count for (i = 0; i < str.length; i++) { // if the character we are searching for in string matches the character being looked at if ( currChar !== str[i]) { output = output + currChar + currCount; // output is sum of the output we have so far plus the character we have been searching for in our string plus the number of times that character is repeated maxCount = Math.max(maxCount, currCount); // choose the larger value between maxCount and currCount currChar = str[i]; // move on to the next character currCount = 1; // count resets to 1 since we have moved on to the next character } else { // if there is a match add to the repeated count currCount++; } } }
// Method that performs basic string compression using the counts of repeated characters function compressStr(str) { var output = "", // will return this variable as final compressed string currChar = "", // represents character we are searching for in string currCount = "", // counts number of times character is repeated maxCount = ""; // maximum count for (i = 0; i < str.length; i++) { // if the character we are searching for in string matches the character being looked at if ( currChar !== str[i]) { output = output + currChar + currCount; // output is sum of the output we have so far plus the character we have been searching for in our string plus the number of times that character is repeated maxCount = Math.max(maxCount, currCount); // choose the larger value between maxCount and currCount currChar = str[i]; // move on to the next character currCount = 1; // count resets to 1 since we have moved on to the next character } } }
Fix confusing import (no change in functionality)
""" Extend the Python Grammar ============================== This example demonstrates how to use the `%extend` statement, to add new syntax to the example Python grammar. """ from lark.lark import Lark from lark.indenter import PythonIndenter GRAMMAR = r""" %import python (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT) %extend compound_stmt: match_stmt match_stmt: "match" test ":" cases cases: _NEWLINE _INDENT case+ _DEDENT case: "case" test ":" suite // test is not quite correct. %ignore /[\t \f]+/ // WS %ignore /\\[\t \f]*\r?\n/ // LINE_CONT %ignore COMMENT """ parser = Lark(GRAMMAR, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter()) tree = parser.parse(r""" def name(n): match n: case 1: print("one") case 2: print("two") case _: print("number is too big") """, start='file_input') # Remove the 'python3__' prefix that was added to the implicitly imported rules. for t in tree.iter_subtrees(): t.data = t.data.rsplit('__', 1)[-1] print(tree.pretty())
""" Extend the Python Grammar ============================== This example demonstrates how to use the `%extend` statement, to add new syntax to the example Python grammar. """ from lark.lark import Lark from python_parser import PythonIndenter GRAMMAR = r""" %import python (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT) %extend compound_stmt: match_stmt match_stmt: "match" test ":" cases cases: _NEWLINE _INDENT case+ _DEDENT case: "case" test ":" suite // test is not quite correct. %ignore /[\t \f]+/ // WS %ignore /\\[\t \f]*\r?\n/ // LINE_CONT %ignore COMMENT """ parser = Lark(GRAMMAR, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter()) tree = parser.parse(r""" def name(n): match n: case 1: print("one") case 2: print("two") case _: print("number is too big") """, start='file_input') # Remove the 'python3__' prefix that was added to the implicitly imported rules. for t in tree.iter_subtrees(): t.data = t.data.rsplit('__', 1)[-1] print(tree.pretty())
Fix update chipmunk src script to run on python 3
import sys, os.path import subprocess import shutil pymunk_src_path = os.path.join("..", "chipmunk_src") shutil.rmtree(os.path.join(pymunk_src_path, "src"), True) shutil.rmtree(os.path.join(pymunk_src_path, "include"), True) if len(sys.argv) > 1: chipmunk_git_path = sys.argv[1] else: chipmunk_git_path = input("Enter path to chipmunk source") shutil.copytree(os.path.join(chipmunk_git_path,"src"), os.path.join(pymunk_src_path,"src")) shutil.copytree(os.path.join(chipmunk_git_path,"include"), os.path.join(pymunk_src_path,"include")) subprocess.call("git rev-parse HEAD", shell=True) print("Remember to update git version string of chipmunk!")
import sys, os.path import subprocess import shutil pymunk_src_path = os.path.join("..", "chipmunk_src") shutil.rmtree(os.path.join(pymunk_src_path, "src"), True) shutil.rmtree(os.path.join(pymunk_src_path, "include"), True) if len(sys.argv) > 1: chipmunk_git_path = sys.argv[1] else: chipmunk_git_path = raw_input("Enter path to chipmunk source") shutil.copytree(os.path.join(chipmunk_git_path,"src"), os.path.join(pymunk_src_path,"src")) shutil.copytree(os.path.join(chipmunk_git_path,"include"), os.path.join(pymunk_src_path,"include")) subprocess.call("git rev-parse HEAD", shell=True) print("Remember to update git version string of chipmunk!")
Use Fullfledged editor as Surface model.
var Substance = require('substance'); var $$ = React.createElement; var _ = require("underscore"); var Surface = Substance.Surface; // Container Node // ---------------- // // Represents a flat collection of nodes var ContainerNode = React.createClass({ displayName: "ContainerNode", render: function() { var containerNode = this.props.node; var doc = this.props.doc; var writerCtrl = this.props.writerCtrl; var components = containerNode.nodes.map(function(nodeId) { var node = doc.get(nodeId); var ComponentClass = writerCtrl.getNodeComponentClass(node.type); return $$(ComponentClass, { key: node.id, writerCtrl: writerCtrl, doc: doc, node: node }); }); return $$("div", {className: "container-node " + this.props.node.id, contentEditable: true }, $$('div', {className: "nodes"}, components) ); }, componentDidMount: function() { if (this.surface) { this.surface.dispose(); } var surfaceModel = new Surface.FullfledgedEditor(this.props.node); this.surface = new Surface(this.getDOMNode(), surfaceModel); this.surface.attach(); }, }); module.exports = ContainerNode;
var Substance = require('substance'); var $$ = React.createElement; var _ = require("underscore"); var Surface = Substance.Surface; // Container Node // ---------------- // // Represents a flat collection of nodes var ContainerNode = React.createClass({ displayName: "ContainerNode", render: function() { var containerNode = this.props.node; var doc = this.props.doc; var writerCtrl = this.props.writerCtrl; var components = containerNode.nodes.map(function(nodeId) { var node = doc.get(nodeId); var ComponentClass = writerCtrl.getNodeComponentClass(node.type); return $$(ComponentClass, { key: node.id, writerCtrl: writerCtrl, doc: doc, node: node }); }); return $$("div", {className: "container-node " + this.props.node.id, contentEditable: true }, $$('div', {className: "nodes"}, components) ); }, componentDidMount: function() { if (this.surface) { this.surface.dispose(); } this.surface = new Surface(this.getDOMNode(), this.props.node); this.surface.attach(); }, }); module.exports = ContainerNode;
Use console.info instead of console.log for output.
#!/usr/bin/env node var path = require('path') var linklocal = require('../') var program = require('commander') var pkg = require('../package.json') program .version(pkg.version) .option('-u, --unlink', 'Unlink local dependencies') // ignore --link only for api balancing with unlink .option('-l, --link', 'Link local dependencies [default]') .usage('[options] <dir>') program.on('--help', function(){ console.info(' Examples:') console.info('') console.info(' $ linklocal') console.info(' $ linklocal --unlink') console.info('') console.info(' $ linklocal mydir') console.info(' $ linklocal --unlink mydir') console.info('') }) program.parse(process.argv) var command = program.unlink ? 'unlink' : 'link' program.args[0] = program.args[0] || '' var dir = path.resolve(process.cwd(), program.args[0]) || process.cwd() linklocal[command](dir, function(err, items) { if (err) throw err var commandName = command[0].toUpperCase() + command.slice(1) console.error('%sed %d dependencies', commandName, items.length) items.forEach(function(item) { console.info('%sed %s', commandName, path.relative(process.cwd(), item)) }) })
#!/usr/bin/env node var path = require('path') var linklocal = require('../') var program = require('commander') var pkg = require('../package.json') program .version(pkg.version) .option('-u, --unlink', 'Unlink local dependencies') // ignore --link only for api balancing with unlink .option('-l, --link', 'Link local dependencies [default]') .usage('[options] <dir>') program.on('--help', function(){ console.log(' Examples:') console.log('') console.log(' $ linklocal') console.log(' $ linklocal --unlink') console.log('') console.log(' $ linklocal mydir') console.log(' $ linklocal --unlink mydir') console.log('') }) program.parse(process.argv) var command = program.unlink ? 'unlink' : 'link' program.args[0] = program.args[0] || '' var dir = path.resolve(process.cwd(), program.args[0]) || process.cwd() linklocal[command](dir, function(err, items) { if (err) throw err var commandName = command[0].toUpperCase() + command.slice(1) console.error('%sed %d dependencies', commandName, items.length) items.forEach(function(item) { console.info('%sed %s', commandName, path.relative(process.cwd(), item)) }) })
Add the How To Play state Add the state that shows the player how to play the game. The background is not added in this state now. It will be added in a future patch.
State.HowToPlay = function (game) { "use strict"; this.game = game; }; State.HowToPlay.prototype = { preload: function () { "use strict"; this.game.load.image('howtoplay-bg', Config.howToPlay.dir); }, create: function () { "use strict"; var background = this.game.add.sprite(Config.howToPlay.x, Config.howToPlay.y, 'howtoplay-bg'); var backButton = this.game.add.button(Config.Menu.buttonBack.x, Config.Menu.buttonBack.y, 'button-back', this.backToMenu, this, 1, 0, 1, 0); }, backToMenu: function () { "use strict"; this.game.state.start('menu-state'); } };
/*global State, Config, Phaser*/ State.HowToPlay = function (game) { "use strict"; this.game = game; }; State.HowToPlay.prototype = { preload: function () { "use strict"; }, create: function () { "use strict"; var background = this.game.add.sprite(Config.howToPlay.x, Config.howToPlay.y, 'how-to-play'); background.inputEnabled = true; background.events.onInputDown.add(this.onClick, this); }, update: function () { "use strict"; Config.global.screen.resize(this.game); if (this.game.input.keyboard.isDown(Phaser.Keyboard.ENTER)) { this.game.state.start('Menu'); } }, onClick: function () { "use strict"; this.game.state.start('Menu'); } };
Add @Override annotation for implemented method `hearShake` is implemented from `ShakeDetector.Listener`.
package com.squareup.seismic.sample; import android.app.Activity; import android.hardware.SensorManager; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import com.squareup.seismic.ShakeDetector; import static android.view.Gravity.CENTER; import static android.view.ViewGroup.LayoutParams; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; public class Demo extends Activity implements ShakeDetector.Listener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); ShakeDetector sd = new ShakeDetector(this); sd.start(sensorManager); TextView tv = new TextView(this); tv.setGravity(CENTER); tv.setText("Shake me, bro!"); setContentView(tv, new LayoutParams(MATCH_PARENT, MATCH_PARENT)); } @Override public void hearShake() { Toast.makeText(this, "Don't shake me, bro!", Toast.LENGTH_SHORT).show(); } }
package com.squareup.seismic.sample; import android.app.Activity; import android.hardware.SensorManager; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import com.squareup.seismic.ShakeDetector; import static android.view.Gravity.CENTER; import static android.view.ViewGroup.LayoutParams; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; public class Demo extends Activity implements ShakeDetector.Listener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); ShakeDetector sd = new ShakeDetector(this); sd.start(sensorManager); TextView tv = new TextView(this); tv.setGravity(CENTER); tv.setText("Shake me, bro!"); setContentView(tv, new LayoutParams(MATCH_PARENT, MATCH_PARENT)); } public void hearShake() { Toast.makeText(this, "Don't shake me, bro!", Toast.LENGTH_SHORT).show(); } }
Use parent process id, that of the apache process.
import os from pyramid.httpexceptions import HTTPNotFound from pyramid.view import view_config from random import randint from ..contentbase import ( Root, location_root, ) def includeme(config): config.registry['encoded.processid'] = os.getppid() config.add_route('schema', '/profiles/{item_type}.json') config.add_route('graph', '/profiles/graph.dot') config.scan() @location_root class EncodedRoot(Root): properties = { 'title': 'Home', 'portal_title': 'ENCODE 3', } @view_config(context=Root, request_method='GET') def home(context, request): result = context.__json__(request) result.update({ '@id': request.resource_path(context), '@type': ['portal'], # 'login': {'href': request.resource_path(context, 'login')}, }) return result @view_config(route_name='schema', request_method='GET') def schema(context, request): item_type = request.matchdict['item_type'] try: collection = context.by_item_type[item_type] except KeyError: raise HTTPNotFound(item_type) return collection.schema
from pyramid.httpexceptions import HTTPNotFound from pyramid.view import view_config from random import randint from ..contentbase import ( Root, location_root, ) def includeme(config): # Random processid so etags are invalidated after restart. config.registry['encoded.processid'] = randint(0, 2 ** 32) config.add_route('schema', '/profiles/{item_type}.json') config.add_route('graph', '/profiles/graph.dot') config.scan() @location_root class EncodedRoot(Root): properties = { 'title': 'Home', 'portal_title': 'ENCODE 3', } @view_config(context=Root, request_method='GET') def home(context, request): result = context.__json__(request) result.update({ '@id': request.resource_path(context), '@type': ['portal'], # 'login': {'href': request.resource_path(context, 'login')}, }) return result @view_config(route_name='schema', request_method='GET') def schema(context, request): item_type = request.matchdict['item_type'] try: collection = context.by_item_type[item_type] except KeyError: raise HTTPNotFound(item_type) return collection.schema
Set snapshot to fixed date rather than using today
import React from "react"; import { shallow } from "enzyme"; import toJson from "enzyme-to-json"; import moment from "moment"; import DateSlider from "../src/DateSlider"; describe("DateSlider Component", () => { it("should shallow render without issues", () => { const component = shallow( <DateSlider selectedDate={moment.utc("2017-05-11")} /> ); expect(component.length).toBe(1); expect(toJson(component)).toMatchSnapshot(); }); it("should render a DateSliderComponent", () => { const isoStartDay = 4; const onDateSelected = jest.fn(); const onWeekChanged = jest.fn(); const selectedDate = new moment(); const component = shallow( <DateSlider isoStartDay={isoStartDay} onDateSelected={onDateSelected} onWeekChanged={onWeekChanged} selectedDate={selectedDate} /> ); expect(component.name()).toBe("DateSliderComponent"); }); });
import React from "react"; import { shallow } from "enzyme"; import toJson from "enzyme-to-json"; import moment from "moment"; import DateSlider from "../src/DateSlider"; describe("DateSlider Component", () => { it("should shallow render without issues", () => { const component = shallow(<DateSlider />); expect(component.length).toBe(1); expect(toJson(component)).toMatchSnapshot(); }); it("should render a DateSliderComponent", () => { const isoStartDay = 4; const onDateSelected = jest.fn(); const onWeekChanged = jest.fn(); const selectedDate = new moment(); const component = shallow( <DateSlider isoStartDay={isoStartDay} onDateSelected={onDateSelected} onWeekChanged={onWeekChanged} selectedDate={selectedDate} /> ); expect(component.name()).toBe("DateSliderComponent"); }); });
Exit after sending a 404
<?php /* * Show debug code. */ error_reporting(E_ALL); ini_set('display_errors', 1); /* * Establish our routing table. */ $router = array(); $router['registrars'] = 'registrars'; $router['validator'] = 'validator'; $router['submit'] = 'submit'; $router['bounce'] = 'bounce'; /* * Identify which method is being requested, and whether any parameters are being passed to that * method. */ $url_components = parse_url($_SERVER['REQUEST_URI']); $method = str_replace('/api/', '', $url_components['path']); if (strpos($method, '/') !== FALSE) { $tmp = explode('/', $method); $method = $tmp[0]; if (!empty($tmp[1])) { $parameter = $tmp[1]; } } /* * If our method is invalid, fail with a 404. */ if ( ($method === FALSE) || !isset($router[$method]) ) { header("HTTP/1.0 404 Not Found"); echo '404 Not Found'; exit(); } include $router[$method] . '.php'; /* * Enable cross-origin resource sharing (CORS). */ header("Access-Control-Allow-Origin: *");
<?php /* * Show debug code. */ error_reporting(E_ALL); ini_set('display_errors', 1); /* * Establish our routing table. */ $router = array(); $router['registrars'] = 'registrars'; $router['validator'] = 'validator'; $router['submit'] = 'submit'; $router['bounce'] = 'bounce'; /* * Identify which method is being requested, and whether any parameters are being passed to that * method. */ $url_components = parse_url($_SERVER['REQUEST_URI']); $method = str_replace('/api/', '', $url_components['path']); if (strpos($method, '/') !== FALSE) { $tmp = explode('/', $method); $method = $tmp[0]; if (!empty($tmp[1])) { $parameter = $tmp[1]; } } /* * If our method is invalid, fail with a 404. */ if ( ($method === FALSE) || !isset($router[$method]) ) { header("HTTP/1.0 404 Not Found"); echo '404 Not Found'; } include $router[$method] . '.php'; /* * Enable cross-origin resource sharing (CORS). */ header("Access-Control-Allow-Origin: *");
Correct bug when compiling JavaScript sources Compiled JavaScript files were empty due to previous modifications on routes architecture. Configuration of grunt concat task wasn't conform to this new architecture.
'use strict'; var applicationConf = process.requirePublish('conf.json'); /** * Gets the list of minified JavaScript files from the given list of files. * * It will just replace ".js" by ".min.js". * * @param Array files The list of files * @return Array The list of minified files */ function getMinifiedJSFiles(files) { var minifiedFiles = []; files.forEach(function(path) { minifiedFiles.push('<%= publish.uglify %>/' + path.replace('.js', '.min.js').replace('/publish/', '')); }); return minifiedFiles; } module.exports = { lib: { // Concatenate back office JavaScript library files src: getMinifiedJSFiles(applicationConf['backOffice']['scriptLibFiles']['dev']), // Concatenate all files into libOpenveoPublish.js dest: '<%= publish.beJSAssets %>/libOpenveoPublish.js' }, publishjs: { // Concatenate all back office JavaScript files src: getMinifiedJSFiles(applicationConf['backOffice']['scriptFiles']['dev']), // Concatenate all files into openveoPublish.js dest: '<%= publish.beJSAssets %>/openveoPublish.js' }, frontJS: { // Concatenate all front JavaScript files src: getMinifiedJSFiles(applicationConf['custom']['scriptFiles']['publishPlayer']['dev']), // Concatenate all files into openveoPublishPlayer.js dest: '<%= publish.playerJSAssets %>/openveoPublishPlayer.js' } };
'use strict'; var applicationConf = process.requirePublish('conf.json'); /** * Gets the list of minified JavaScript files from the given list of files. * * It will just replace ".js" by ".min.js". * * @param Array files The list of files * @return Array The list of minified files */ function getMinifiedJSFiles(files) { var minifiedFiles = []; files.forEach(function(path) { minifiedFiles.push('<%= publish.uglify %>/' + path.replace('.js', '.min.js')); }); return minifiedFiles; } module.exports = { lib: { // Concatenate back office JavaScript library files src: getMinifiedJSFiles(applicationConf['backOffice']['scriptLibFiles']['dev']), // Concatenate all files into libOpenveoPublish.js dest: '<%= publish.beJSAssets %>/libOpenveoPublish.js' }, publishjs: { // Concatenate all back office JavaScript files src: getMinifiedJSFiles(applicationConf['backOffice']['scriptFiles']['dev']), // Concatenate all files into openveoPublish.js dest: '<%= publish.beJSAssets %>/openveoPublish.js' }, frontJS: { // Concatenate all front JavaScript files src: getMinifiedJSFiles(applicationConf['custom']['scriptFiles']['publishPlayer']['dev']), // Concatenate all files into openveoPublishPlayer.js dest: '<%= publish.playerJSAssets %>/openveoPublishPlayer.js' } };
Add Etherscan list txs unused address test
// Import AVA import test from 'ava' // Imports import sleep from '../../../src/util/sleep' import Client from '../../../src/client/etherscan' // Test data const testAddress = '0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae' const testUnusedAddress = '0xe148E5AA46401b7bEe89D1F6103776ba508024e0' // Sleep before each test test.beforeEach('rate limit', async t => { console.log() console.log('-- Rate limiting') console.log() await sleep(1000) }) /** * Valid address. */ test.serial('valid address', async t => { console.log('Acquire with valid address') const client = new Client() const prom = client .listAccountTransactions(testAddress) await t.notThrows(prom) const txs = await prom const numTxs = txs.length console.log('Found ' + numTxs + ' txs') }) /** * Valid unused address. */ test.serial('valid unused address', async t => { console.log('Acquire with valid unused address') const client = new Client() const prom = client .listAccountTransactions(testUnusedAddress) await t.notThrows(prom) const txs = await prom const numTxs = txs.length console.log('Found ' + numTxs + ' txs') t.true(numTxs === 0) }) /** * Bad address. */ test.serial('bad address', async t => { console.log('Acquire with bad address') const client = new Client() const prom = client .listAccountTransactions('test') await t.throws(prom) })
// Import AVA import test from 'ava' // Imports import sleep from '../../../src/util/sleep' import Client from '../../../src/client/etherscan' // Test data const testAddress = '0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae' // Sleep before each test test.beforeEach('rate limit', async t => { console.log() console.log('-- Rate limiting') console.log() await sleep(1000) }) /** * Valid address. */ test.serial('valid address', async t => { console.log('Acquire with valid address') const client = new Client() const prom = client .listAccountTransactions(testAddress) await t.notThrows(prom) const txs = await prom const numTxs = txs.length console.log('Found ' + numTxs + ' txs') }) /** * Bad address. */ test.serial('bad address', async t => { console.log('Acquire with bad address') const client = new Client() const prom = client .listAccountTransactions('test') await t.throws(prom) })
Revert "Another minor fix for the speed/direction conversion" This reverts commit f6ab42ffd5ffd4af8af6e117237df59c9addf056.
/* Currently managed by Tarun Sunkaraneni, and Ben Rose * This class manages all motor writing and managment. May need to deal with complex Gyro * input. */ package edu.ames.frc.robot; public class MotorControl { /* This converts the direction we want to go (from 0 to 1, relative to the robot's base) * and speed (from 0 to 1) directly to values for the three omni-wheeled motors. */ double[] convertHeadingToMotorCommands(double direction, double speed) { double[] motorvalue = new double[3]; /* so, we'll define the direction we want to go as "forward". There are * 3 different points where only two motors will need to run (if the direction * is parallel to a motor's axle). */ // 0 is what we define as the "front" motor - what we measure our heading angle from, // 1 is the motor one position clockwise from that, and // 2 is the motor one position counter-clockwise from 0. motorvalue[0] = speed * Math.sin(direction); motorvalue[1] = speed * Math.sin(direction - (2 * Math.PI / 3)); motorvalue[2] = speed * Math.sin(direction + (2 * Math.PI)) / 3; return motorvalue; } }
/* Currently managed by Tarun Sunkaraneni, and Ben Rose * This class manages all motor writing and managment. May need to deal with complex Gyro * input. */ package edu.ames.frc.robot; public class MotorControl { /* This converts the direction we want to go (from 0 to 1, relative to the robot's base) * and speed (from 0 to 1) directly to values for the three omni-wheeled motors. */ double[] convertHeadingToMotorCommands(double direction, double speed) { double[] motorvalue = new double[3]; /* so, we'll define the direction we want to go as "forward". There are * 3 different points where only two motors will need to run (if the direction * is parallel to a motor's axle). */ // 0 is what we define as the "front" motor - what we measure our heading angle from, // 1 is the motor one position clockwise from that, and // 2 is the motor one position counter-clockwise from 0. motorvalue[0] = speed * Math.sin(direction); motorvalue[1] = speed * Math.sin(direction - (2 * Math.PI / 3)); motorvalue[2] = speed * Math.sin(direction + (2 * Math.PI / 3)); return motorvalue; } }
Update gradient labels to use signal directive.
import {Perc, Label} from './constants'; import guideMark from './guide-mark'; import {TextMark} from '../marks/marktypes'; import {LegendLabelRole} from '../marks/roles'; var alignExpr = 'datum.' + Perc + '<=0?"left"' + ':datum.' + Perc + '>=1?"right":"center"'; export default function(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}, enter, update; encode.enter = enter = { opacity: zero, text: {field: Label}, fill: {value: config.labelColor}, font: {value: config.labelFont}, fontSize: {value: config.labelFontSize}, baseline: {value: config.gradientLabelBaseline} }; encode.exit = { opacity: zero }; encode.update = update = { opacity: {value: 1} }; enter.x = update.x = { field: Perc, mult: config.gradientWidth }; enter.y = update.y = { value: config.gradientHeight, offset: config.gradientLabelOffset }; enter.align = update.align = {signal: alignExpr}; return guideMark(TextMark, LegendLabelRole, Label, dataRef, encode, userEncode); }
import {Perc, Label} from './constants'; import guideMark from './guide-mark'; import {TextMark} from '../marks/marktypes'; import {LegendLabelRole} from '../marks/roles'; var alignExpr = 'datum.' + Perc + '<=0?"left"' + ':datum.' + Perc + '>=1?"right":"center"'; export default function(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}, enter, update; encode.enter = enter = { opacity: zero, text: {field: Label}, fill: {value: config.labelColor}, font: {value: config.labelFont}, fontSize: {value: config.labelFontSize}, baseline: {value: config.gradientLabelBaseline} }; encode.exit = { opacity: zero }; encode.update = update = { opacity: {value: 1} }; enter.x = update.x = { field: Perc, mult: config.gradientWidth }; enter.y = update.y = { value: config.gradientHeight, offset: config.gradientLabelOffset }; enter.align = update.align = {expr: alignExpr}; return guideMark(TextMark, LegendLabelRole, Label, dataRef, encode, userEncode); }
Fix broken test after contribution
<?php namespace phpDocumentor\Partials; use Mockery as m; class CollectionTest extends \PHPUnit_Framework_TestCase { /** @var Collection */ protected $fixture; /** @var m\MockInterface|\Parsedown */ protected $parser; /** * Constructs the fixture and adds mocked dependencies. */ protected function setUp() { $this->parser = m::mock('\Parsedown'); $this->fixture = new Collection($this->parser); } /** * @covers phpDocumentor\Partials\Collection::__construct */ public function testIfParserIsRegisteredWithCollectionUponInstantiation() { $this->assertAttributeSame($this->parser, 'parser', $this->fixture); } /** * @covers phpDocumentor\Partials\Collection::set */ public function testProvidedPartialIsConvertedIntoHTMLWhenSettingIt() { // Arrange $input = 'This is a *Partial* text'; $output = 'This is a <em>Partial</em> text'; $this->parser->shouldReceive('text')->with($input)->andReturn($output); // Act $this->fixture->set('test', $input); // Assert $this->assertSame($output, $this->fixture['test']); } }
<?php namespace phpDocumentor\Partials; use Mockery as m; class CollectionTest extends \PHPUnit_Framework_TestCase { /** @var Collection */ protected $fixture; /** @var m\MockInterface|\Parsedown */ protected $parser; /** * Constructs the fixture and adds mocked dependencies. */ protected function setUp() { $this->parser = m::mock('\Parsedown'); $this->fixture = new Collection($this->parser); } /** * @covers phpDocumentor\Partials\Collection::__construct */ public function testIfParserIsRegisteredWithCollectionUponInstantiation() { $this->assertAttributeSame($this->parser, 'parser', $this->fixture); } /** * @covers phpDocumentor\Partials\Collection::set */ public function testProvidedPartialIsConvertedIntoHTMLWhenSettingIt() { // Arrange $input = 'This is a *Partial* text'; $output = 'This is a <em>Partial</em> text'; $this->parser->shouldReceive('parse')->with($input)->andReturn($output); // Act $this->fixture->set('test', $input); // Assert $this->assertSame($output, $this->fixture['test']); } }
Make sure all bot plugins are hinted
module.exports = function (grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON( 'package.json' ), jshint: { all: [ 'bot.js', '*.botplug.js' ], options: { jshintrc: '.jshintrc' } } }); grunt.loadNpmTasks( 'grunt-contrib-jshint' ); grunt.registerTask( 'test', [ 'jshint' ] ); grunt.registerTask( 'default', [ 'test' ] ); };
module.exports = function (grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON( 'package.json' ), jshint: { all: [ 'Gruntfile.js', 'bot.js', 'DagensMix.js', 'GitHub.js' ], options: { jshintrc: '.jshintrc' } } }); grunt.loadNpmTasks( 'grunt-contrib-jshint' ); grunt.registerTask( 'test', [ 'jshint' ] ); grunt.registerTask( 'default', [ 'test' ] ); };
Refactor preload to handle more cases
import Ember from 'ember'; const { RSVP } = Ember; function getPromise(object, property) { return RSVP.resolve(Ember.get(object, property)); } function preloadRecord(record, toPreload) { if (!record) { return RSVP.resolve(record); } switch(Ember.typeOf(toPreload)) { case 'string': return getPromise(record, toPreload).then(() => record); case 'array': return RSVP.all(toPreload.map((p) => preloadRecord(record, p))).then(() => record); case 'object': return RSVP.all(Object.keys(toPreload).map((p) => getPromise(record, p).then((data) => preload(data, toPreload[p])))).then(() => record); default: throw 'Illegal Argument'; } } function preloadAll(records, toPreload) { return RSVP.all(records.map((record) => preload(record, toPreload))); } function preload(thing, toPreload) { return RSVP.resolve(thing).then(() => { return Ember.isArray(thing) ? preloadAll(thing, toPreload) : preloadRecord(thing, toPreload); }); } export default preload;
import Ember from 'ember'; const { RSVP } = Ember; function preloadRecord(record, toPreload) { return preloadAll([record], toPreload).then(() => { return record; }); } function preloadAll(records, toPreload) { switch(Ember.typeOf(toPreload)) { case 'object': const properties = Object.keys(toPreload); return RSVP.all(properties.map((p) => { return RSVP.all(records.map((record) => { return record.get(p); })).then((data) => { const subRecords = data.reduce((prev, cur) => prev.concat(cur.toArray()), []); return preloadAll(subRecords, toPreload[p]); }); })).then(() => records); case 'string': return RSVP.all(records.map((record) => record.get(toPreload))) .then(() => records); default: throw 'Illegal Argument'; } } function preload(thing, toPreload) { if (thing.then) { return thing.then(() => { return Ember.isArray(thing) ? preloadAll(thing, toPreload) : preloadRecord(thing, toPreload); }); } else { return Ember.isArray(thing) ? preloadAll(thing, toPreload) : preloadRecord(thing, toPreload); } } export default preload;
Allow apps to specify an alternative hoodie.js dependency If you project needs a hoodie.js that is different from the default, you can now specify an alternate dependency source for `hoodie`. e.g.: ``` { "name": "foo", "version": "1.0.1", "type": "app", "dependencies": { "hoodie-server": "~0.8.12", "hoodie-plugin-appconfig": "~0.1.0", "hoodie-plugin-email": "~0.1.1", "hoodie-plugin-users": "0.0.9", "hoodie": "git://github.com/hoodiehq/hoodie.js.git" }, "subdomain": "hoodie-foo", "domains": [ "admin.hoodie-foo.jit.su", "couch.hoodie-foo.jit.su" ], "scripts": { "start": "node node_modules/hoodie-server/bin/start" }, "hoodie": { "plugins": [ "hoodie-plugin-appconfig", "hoodie-plugin-email", "hoodie-plugin-users" ] } } ``` Closes #164. * * * This commit was sponsored by The Hoodie Firm. You can hire The Hoodie Firm: http://go.hood.ie/thehoodiefirm
var dispatch = require('dispatch'); var path = require('path'); var fs = require('fs'); var _ = require('underscore'); var plugins = require('../plugins'); /* jshint unused:false*/ module.exports = function (config) { var names = plugins.getPluginNames(config); var paths = names.map(function (name) { return path.resolve( config.plugins[name].path, 'hoodie.' + name + '.js' ); }); var bufferToString = function (buf) { return buf.toString(); }; var readString = _.compose(bufferToString, function (filename) { return fs.readFileSync(filename); }); var extensions = paths.filter(fs.existsSync).map(readString); var hoodie_dir = path.resolve(__dirname, '../../node_modules/hoodie/dist'); // if the user's project has defined a hoodie.js dependency, // then favour that over our own dependency. if(config.app.dependencies.hoodie) { hoodie_dir = path.resolve(config.project_dir, 'node_modules/hoodie/dist'); console.log('loading alternative hoodie.js from %s', hoodie_dir); } var base = readString(hoodie_dir + '/hoodie.js'); var hoodiejs = base + extensions.join('\n'); return dispatch({ '/_api/_files/hoodie.js': function (req, res, next) { res.writeHead(200, {'Content-Type': 'application/javascript'}); res.end(hoodiejs); } }); };
var dispatch = require('dispatch'); var path = require('path'); var fs = require('fs'); var _ = require('underscore'); var plugins = require('../plugins'); /* jshint unused:false*/ module.exports = function (config) { var names = plugins.getPluginNames(config); var paths = names.map(function (name) { return path.resolve( config.plugins[name].path, 'hoodie.' + name + '.js' ); }); var bufferToString = function (buf) { return buf.toString(); }; var readString = _.compose(bufferToString, function (filename) { return fs.readFileSync(filename); }); var extensions = paths.filter(fs.existsSync).map(readString); var hoodie_dir = path.resolve(__dirname, '../../node_modules/hoodie/dist'); var base = readString(hoodie_dir + '/hoodie.js'); var hoodiejs = base + extensions.join('\n'); return dispatch({ '/_api/_files/hoodie.js': function (req, res, next) { res.writeHead(200, {'Content-Type': 'application/javascript'}); res.end(hoodiejs); } }); };
Use Date.now() and add startTime
var os = Npm.require('os'); var uvmon = Npm.require('nodefly-uvmon'); var SYSTEM_METRICS_FIELDS = ['testfield']; SystemModel = function () { var self = this; this.lastGetData = Date.now(); } _.extend(SystemModel.prototype, ApmModel.prototype); SystemModel.prototype.getEventLoopData = function() { var data = uvmon.getData(); var time = Date.now(); data.time = time - this.lastGetData; this.lastGetData = time; return data; }; SystemModel.prototype.buildPayload = function() { var metrics = {}; var uvData = this.getEventLoopData(); metrics.startTime = Date.now(); metrics.sessions = Meteor.default_server.sessions.length; metrics.rssBytes = process.memoryUsage().rss; metrics.loadAverage = os.loadavg()[0]; metrics.eventLoopTime = uvData.sum_ms; metrics.eventLoopCount = uvData.count; metrics.totalTime = uvData.time; return {systemMetrics: metrics}; };
var os = Npm.require('os'); var uvmon = Npm.require('nodefly-uvmon'); var SYSTEM_METRICS_FIELDS = ['testfield']; SystemModel = function () { var self = this; this.lastGetData = new Date().getTime(); } _.extend(SystemModel.prototype, ApmModel.prototype); SystemModel.prototype.getEventLoopData = function() { var data = uvmon.getData(); var time = new Date().getTime(); data.time = time - this.lastGetData; this.lastGetData = time; return data; }; SystemModel.prototype.buildPayload = function() { var metrics = {}; var uvData = this.getEventLoopData(); metrics.sessions = Meteor.default_server.sessions.length; metrics.rssBytes = process.memoryUsage().rss; metrics.loadAverage = os.loadavg()[0]; metrics.eventLoopTime = uvData.sum_ms; metrics.eventLoopCount = uvData.count; metrics.totalTime = uvData.time; return {systemMetrics: metrics}; };
Fix Syntax error for Python<3.5
from datetime import datetime import jinja2 from django.utils.safestring import mark_safe from django_jinja import library from .. import json from ..jsonld import graph @library.filter(name='json') def json_encode(data): return json.dumps(data) @library.filter @library.global_function @jinja2.contextfunction def jsonld(context, *data): if 'page' in context and hasattr(context['page'], '__jsonld__'): page = context['page'] if page not in data: data = [page] + list(data) return mark_safe(''.join(( '<script type="application/ld+json">', json.dumps(graph(context, *data)), '</script>' ))) @library.global_function def now(): return datetime.now() @library.global_function @library.render_with('includes/pager.html') @jinja2.contextfunction def pager_for(page, previous_label=None, next_label=None): return { "page": page, 'previous_label': previous_label, 'next_label': next_label, # "querystring": querystring, }
from datetime import datetime import jinja2 from django.utils.safestring import mark_safe from django_jinja import library from .. import json from ..jsonld import graph @library.filter(name='json') def json_encode(data): return json.dumps(data) @library.filter @library.global_function @jinja2.contextfunction def jsonld(context, *data): if 'page' in context and hasattr(context['page'], '__jsonld__'): page = context['page'] if page not in data: data = [page, *data] return mark_safe(''.join(( '<script type="application/ld+json">', json.dumps(graph(context, *data)), '</script>' ))) @library.global_function def now(): return datetime.now() @library.global_function @library.render_with('includes/pager.html') @jinja2.contextfunction def pager_for(page, previous_label=None, next_label=None): return { "page": page, 'previous_label': previous_label, 'next_label': next_label, # "querystring": querystring, }
Return Empty array when annotations are missing
package nl.dykam.dev.reutil.data; import nl.dykam.dev.reutil.data.annotations.ApplicableTo; import nl.dykam.dev.reutil.data.annotations.Defaults; import nl.dykam.dev.reutil.data.annotations.ObjectType; import nl.dykam.dev.reutil.data.annotations.Require; import java.lang.reflect.Array; class ComponentInfo { public static final ObjectType[] OBJECT_TYPES = new ObjectType[0]; @SuppressWarnings("unchecked") public static final Class<? extends Component>[] CLASSES = (Class<? extends Component>[]) Array.newInstance(Class.class, 0); public static <T extends Component> Defaults getDefaults(Class<T> type) { return type.getAnnotation(Defaults.class); } private static <T extends Component> ComponentBuilder<T> getBuilder(Class<T> type) { return ComponentBuilder.getBuilder(type); } public static <T extends Component> ObjectType[] getApplicables(Class<T> type) { ApplicableTo annotation = type.getAnnotation(ApplicableTo.class); return annotation == null ? OBJECT_TYPES : annotation.value(); } @SuppressWarnings("unchecked") public static <T extends Component> Class<? extends Component>[] getRequired(Class<T> type) { Require annotation = type.getAnnotation(Require.class); return annotation == null ? CLASSES : annotation.value(); } }
package nl.dykam.dev.reutil.data; import nl.dykam.dev.reutil.data.annotations.ApplicableTo; import nl.dykam.dev.reutil.data.annotations.Defaults; import nl.dykam.dev.reutil.data.annotations.ObjectType; import nl.dykam.dev.reutil.data.annotations.Require; class ComponentInfo { public static <T extends Component> Defaults getDefaults(Class<T> type) { return type.getAnnotation(Defaults.class); } private static <T extends Component> ComponentBuilder<T> getBuilder(Class<T> type) { return ComponentBuilder.getBuilder(type); } public static <T extends Component> ObjectType[] getApplicables(Class<T> type) { return type.getAnnotation(ApplicableTo.class).value(); } public static <T extends Component> Class<? extends Component>[] getRequired(Class<T> type) { return type.getAnnotation(Require.class).value(); } }
Make download first step for install_software process type
import virtool.db.processes FIRST_STEPS = { "delete_reference": "delete_indexes", "clone_reference": "copy_otus", "import_reference": "load_file", "remote_reference": "download", "update_remote_reference": "download", "update_software": "download", "install_hmms": "download" } class ProgressTracker: def __init__(self, db, process_id, total, factor=1, increment=0.03, initial=0): self.db = db self.process_id = process_id self.total = total self.factor = factor self.increment = increment self.initial = initial self.count = 0 self.last_reported = 0 self.progress = self.initial async def add(self, value): count = self.count + value if count > self.total: raise ValueError("Count cannot exceed total") self.count = count self.progress = self.initial + round(self.count / self.total * self.factor, 2) if self.progress - self.last_reported >= self.increment: await virtool.db.processes.update(self.db, self.process_id, progress=self.progress) self.last_reported = self.progress return self.progress
import virtool.db.processes FIRST_STEPS = { "delete_reference": "delete_indexes", "clone_reference": "copy_otus", "import_reference": "load_file", "remote_reference": "download", "update_remote_reference": "download", "update_software": "", "install_hmms": "" } class ProgressTracker: def __init__(self, db, process_id, total, factor=1, increment=0.03, initial=0): self.db = db self.process_id = process_id self.total = total self.factor = factor self.increment = increment self.initial = initial self.count = 0 self.last_reported = 0 self.progress = self.initial async def add(self, value): count = self.count + value if count > self.total: raise ValueError("Count cannot exceed total") self.count = count self.progress = self.initial + round(self.count / self.total * self.factor, 2) if self.progress - self.last_reported >= self.increment: await virtool.db.processes.update(self.db, self.process_id, progress=self.progress) self.last_reported = self.progress return self.progress
Add cases for either CSS or template not existing
import os import os.path from . import database THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes")) def getCurrentTheme(): databaseConnection = database.ConnectionManager.getConnection("main") query = (databaseConnection.session .query(database.tables.Setting) .filter(database.tables.Setting.name == "theme")) if query.count() > 0: themeName = query.first().value themes = os.listdir(THEME_PATH) folderName = None try: folderName = next(theme for theme in themes if theme.lower() == themeName.lower()) except StopIteration: return None themePath = os.path.join(THEME_PATH, folderName, "theme.css") theme = "" #No CSS if os.path.isfile(themePath): themeFile = open(themePath, "r") theme = themeFile.read() themeFile.close() templatePath = os.path.join(THEME_PATH, folderName, "template.html") template = None #If this is None, the default template can be used. if os.path.isfile(templatePath): templateFile = open(templatePath, "r") template = templatefile.read() templateFile.close() return {"template": template, "theme": theme} def getAvailableThemes(): files = os.listdir(THEME_PATH) for item in files: path = os.path.join(THEME_PATH, item) if not os.path.isdir(path): files.remove(item) return files
import os import os.path from . import database THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes")) def getCurrentTheme(): databaseConnection = database.ConnectionManager.getConnection("main") query = (databaseConnection.session .query(database.tables.Setting) .filter(database.tables.Setting.name == "theme")) if query.count() > 0: themeName = query.first().value themes = os.listdir(THEME_PATH) folderName = None try: folderName = next(theme for theme in themes if theme.lower() == themeName.lower()) except StopIteration: return None themeFile = open( os.path.join(THEME_PATH, folderName, "theme.css"), "r") theme = themeFile.read() themeFile.close() templateFile = open( os.path.join(THEME_PATH, folderName, "template.html"), "r") template = templatefile.read() templateFile.close() return {"template": template, "theme": theme} def getAvailableThemes(): files = os.listdir(THEME_PATH) for item in files: path = os.path.join(THEME_PATH, item) if not os.path.isdir(path): files.remove(item) return files
Set mytheme on fallback UI
package org.madura.mobile.demo; import com.vaadin.annotations.Theme; import com.vaadin.server.VaadinRequest; import com.vaadin.ui.Button; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.UI; /** * This UI is served for browsers that don't support TouchKit. */ @SuppressWarnings("serial") @Theme("mytheme") //// Disable browser caching the app for running it when offline //@CacheManifestEnabled(false) //// Prevent showing OfflineMode client UI if network fails //@OfflineModeEnabled(false) public class MaduraMobileDemoFallbackUI extends UI { @Override protected void init(VaadinRequest request) { HorizontalLayout layout = new HorizontalLayout(); layout.setSpacing(true); layout.setMargin(true); Button button = new Button("Continue anyway.", new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { getSession().setAttribute("mobile", true); getUI().getPage().reload(); } }); button.addStyleName("link"); layout.addComponent(new Label("You seem to be using a desktop browser.")); layout.addComponent(button); setContent(layout); } }
package org.madura.mobile.demo; import com.vaadin.server.VaadinRequest; import com.vaadin.ui.Button; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.UI; /** * This UI is served for browsers that don't support TouchKit. */ @SuppressWarnings("serial") //// Disable browser caching the app for running it when offline //@CacheManifestEnabled(false) //// Prevent showing OfflineMode client UI if network fails //@OfflineModeEnabled(false) public class MaduraMobileDemoFallbackUI extends UI { @Override protected void init(VaadinRequest request) { HorizontalLayout layout = new HorizontalLayout(); layout.setSpacing(true); layout.setMargin(true); Button button = new Button("Continue anyway.", new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { getSession().setAttribute("mobile", true); getUI().getPage().reload(); } }); button.addStyleName("link"); layout.addComponent(new Label("You seem to be using a desktop browser.")); layout.addComponent(button); setContent(layout); } }
Use older style string formatting for Python 2.6
import warnings from django.conf import settings from armstrong.utils.backends import GenericBackend NEW = "ARMSTRONG_LAYOUT_BACKEND" OLD = "ARMSTRONG_RENDER_MODEL_BACKEND" render_model = (GenericBackend(NEW, defaults="armstrong.core.arm_layout.backends.BasicLayoutBackend") .get_backend()) if hasattr(settings, OLD): msg = "%s is deprecated and will be removed in ArmLayout 1.4. Use %s." % (OLD, NEW) warnings.warn(msg, DeprecationWarning) render_model = (GenericBackend(OLD, defaults="armstrong.core.arm_layout.backends.BasicLayoutBackend") .get_backend()) # DEPRECATED: To be removed in ArmLayout 1.4. Here for backwards compatibility from django.utils.safestring import mark_safe from django.template.loader import render_to_string def deprecate(func): def wrapper(*args, **kwargs): msg = "Importing `%s` from this module is deprecated and will be removed in ArmLayout 1.4" warnings.warn(msg % func.__name__, DeprecationWarning) return func(*args, **kwargs) return wrapper mark_safe = deprecate(mark_safe) render_to_string = deprecate(render_to_string) get_layout_template_name = deprecate(render_model.get_layout_template_name)
import warnings from django.conf import settings from armstrong.utils.backends import GenericBackend NEW = "ARMSTRONG_LAYOUT_BACKEND" OLD = "ARMSTRONG_RENDER_MODEL_BACKEND" render_model = (GenericBackend(NEW, defaults="armstrong.core.arm_layout.backends.BasicLayoutBackend") .get_backend()) if hasattr(settings, OLD): msg = "{} is deprecated and will be removed in ArmLayout 1.4. Use {}.".format(OLD, NEW) warnings.warn(msg, DeprecationWarning) render_model = (GenericBackend(OLD, defaults="armstrong.core.arm_layout.backends.BasicLayoutBackend") .get_backend()) # DEPRECATED: To be removed in ArmLayout 1.4. Here for backwards compatibility from django.utils.safestring import mark_safe from django.template.loader import render_to_string def deprecate(func): def wrapper(*args, **kwargs): msg = "Importing `{}` from this module is deprecated and will be removed in ArmLayout 1.4" warnings.warn(msg.format(func.__name__), DeprecationWarning) return func(*args, **kwargs) return wrapper mark_safe = deprecate(mark_safe) render_to_string = deprecate(render_to_string) get_layout_template_name = deprecate(render_model.get_layout_template_name)
Remove instanbul preloader for dev
'use strict'; var path = require('path'), webpack = require('webpack'); module.exports = { cache: true, entry: { main: './client/src/js/main.js' }, output: { path: path.join(__dirname, 'public/js/'), publicPath: 'js/', filename: '[name].js', chunkFilename: '[chunkhash].js' }, module: { loaders: [{ test: /\.scss$/, loaders: ['style', 'css', 'sass', 'sass?sourceMap'] }, { test: /\.hbs/, loader: 'handlebars-loader' }] }, plugins: [ new webpack.ProvidePlugin({ // FIXME this is lazy, do something better with backbone and underscore // Automtically detect jQuery and $ as free var in modules // and inject the jquery library // This is required by many jquery plugins jQuery: 'jquery', $: 'jquery', Backbone: 'backbone', _: 'underscore' }) ] };
'use strict'; var path = require('path'), webpack = require('webpack'); module.exports = { cache: true, entry: { main: './client/src/js/main.js' }, output: { path: path.join(__dirname, 'public/js/'), publicPath: 'js/', filename: '[name].js', chunkFilename: '[chunkhash].js' }, module: { preLoaders: [{ test: /\.js$/, include: path.resolve('client/src/js/'), loader: 'istanbul-instrumenter' }], loaders: [{ test: /\.scss$/, loaders: ['style', 'css', 'sass', 'sass?sourceMap'] }, { test: /\.hbs/, loader: 'handlebars-loader' }] }, plugins: [ new webpack.ProvidePlugin({ // FIXME this is lazy, do something better with backbone and underscore // Automtically detect jQuery and $ as free var in modules // and inject the jquery library // This is required by many jquery plugins jQuery: 'jquery', $: 'jquery', Backbone: 'backbone', _: 'underscore' }) ] };
Check muted value is true
function talk() { var participants = gapi.hangout.getParticipants(); for (var index in participants) { var participant = participants[index]; if (participant.id !== gapi.hangout.getLocalParticipantId()) { gapi.hangout.av.muteParticipantMicrophone(participant.id); } else { activeParticipant = participant; document.getElementById('talker-image').src = activeParticipant.person.image.url; } } gapi.hangout.av.setMicrophoneMute(false); } function unmute() { gapi.hangout.data.setValue("muted", "false"); } function onStateChange(stateChangeEvent) { var muted = gapi.hangout.data.getValue("muted"); gapi.hangout.av.setMicrophoneMute(muted === "true"); } function configureSession() { var muted = gapi.hangout.data.getValue("muted"); if (typeof muted === 'undefined') { gapi.hangout.data.setValue("muted", "true"); } else { gapi.hangout.av.setMicrophoneMute(muted === "true"); } } // This runs when the gadget is ready function init() { // When API is ready... gapi.hangout.onApiReady.add( function(eventObj) { if (eventObj.isApiReady) { configureSession(); gapi.hangout.data.onStateChanged.add(onStateChange); } } ); } // Wait for gadget to load. gadgets.util.registerOnLoadHandler(init);
function talk() { var participants = gapi.hangout.getParticipants(); for (var index in participants) { var participant = participants[index]; if (participant.id !== gapi.hangout.getLocalParticipantId()) { gapi.hangout.av.muteParticipantMicrophone(participant.id); } else { activeParticipant = participant; document.getElementById('talker-image').src = activeParticipant.person.image.url; } } gapi.hangout.av.setMicrophoneMute(false); } function unmute() { gapi.hangout.data.setValue("muted", "false"); } function onStateChange(stateChangeEvent) { var muted = gapi.hangout.data.getValue("muted"); gapi.hangout.av.setMicrophoneMute(muted); } function configureSession() { var muted = gapi.hangout.data.getValue("muted"); if (typeof muted === 'undefined') { gapi.hangout.data.setValue("muted", "true"); } else { gapi.hangout.av.setMicrophoneMute(muted); } } // This runs when the gadget is ready function init() { // When API is ready... gapi.hangout.onApiReady.add( function(eventObj) { if (eventObj.isApiReady) { configureSession(); gapi.hangout.data.onStateChanged.add(onStateChange); } } ); } // Wait for gadget to load. gadgets.util.registerOnLoadHandler(init);
Add proper requirements on lettuce_webdriver, update for alpha release.
from setuptools import setup, find_packages import sys, os version = '0.20a1' setup(name='velruse', version=version, description="Simplifying third-party authentication for web applications.", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Ben Bangert', author_email='ben@groovie.org', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ "WebOb>=1.0.4", "python-openid>=2.2.4", "nose>=0.11", "oauth2>=1.1.3", "pyyaml", "beaker", "routes", ], tests_require = [ 'lettuce>=0.1.21', 'lettuce_webdriver>=0.1.2', 'selenium' ], entry_points=""" [paste.app_factory] main = velruse.app:make_velruse_app """, )
from setuptools import setup, find_packages import sys, os version = '0.20' setup(name='velruse', version=version, description="Simplifying third-party authentication for web applications.", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Ben Bangert', author_email='ben@groovie.org', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ "WebOb>=1.0.4", "python-openid>=2.2.4", "nose>=0.11", "oauth2>=1.1.3", "pyyaml", "beaker", "routes", ], tests_require = [ 'lettuce>=0.1.21', 'lettuce_webdriver>=0.12', 'selenium' ], entry_points=""" [paste.app_factory] main = velruse.app:make_velruse_app """, )
Change from class to id
$(document).ready(function() { $('#submit_new_content').on('click', function() { window.btn_clicked = true; }) window.onbeforeunload = function(event){ if(!window.btn_clicked){ // Need to add alert to prevent user from leaving page. if($('.edit_snippet')){ var $url = $('.edit_snippet')[0].action; $.ajax({ type: "DELETE", url: $url, dataType: "text" }).done(function(response){ console.log("Success"); }); } } }; })
$(document).ready(function() { $('.submit_new_content').on('click', function() { window.btn_clicked = true; }) window.onbeforeunload = function(event){ if(!window.btn_clicked){ // Need to add alert to prevent user from leaving page. if($('.edit_snippet')){ var $url = $('.edit_snippet')[0].action; $.ajax({ type: "DELETE", url: $url, dataType: "text" }).done(function(response){ console.log("Success"); }); } } }; })
Use README.rst instead od README.md for doc.
from distutils.core import setup setup( name='permission', version='0.2.0', author='Zhipeng Liu', author_email='hustlzp@qq.com', url='https://github.com/hustlzp/permission', packages=['permission'], license='MIT', description='Simple and flexible permission control for Flask app.', long_description=open('README.rst').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
from distutils.core import setup setup( name='permission', version='0.2.0', author='Zhipeng Liu', author_email='hustlzp@qq.com', url='https://github.com/hustlzp/permission', packages=['permission'], license='MIT', description='Simple and flexible permission control for Flask app.', long_description=open('README.md').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Use POST instead of get
"use strict"; angular.module('services.jsonp', []) .factory('jsonp', ['$rootScope', '$q', '$http', '$parse', '$interpolate', function ($rootScope, $q, $http, $parse, $interpolate) { // We return this object to anything injecting our service var factory = {}; var isConnected = false; var urlFn; var msgCallback; factory.isConnected = function () { return isConnected; }; factory.register = function (method, callback) { }; factory.send = function (request) { var defer = $q.defer(); var req = { method: 'POST', url: urlFn, headers: { 'Content-Type': 'application/json' }, data: { request: request } }; $http(req).success(function (data) { msgCallback(data); }); return defer.promise; }; factory.unregister = function (method, callback) { }; factory.connect = function (partial, connectCallback, disconnectCallback) { urlFn = 'http://'+partial; isConnected = true; connectCallback(); }; factory.subscribe = function (callback) { msgCallback = callback }; return factory; } ]);
"use strict"; angular.module('services.jsonp', []) .factory('jsonp', ['$rootScope', '$q', '$http', '$parse', '$interpolate', function ($rootScope, $q, $http, $parse, $interpolate) { // We return this object to anything injecting our service var factory = {}; var isConnected = false; var urlFn; var msgCallback; factory.isConnected = function () { return isConnected; }; factory.register = function (method, callback) { }; factory.send = function (request) { var defer = $q.defer(); var request =JSON.stringify(request); var url = urlFn({request : request}) $http.jsonp(url).success(function (data) { msgCallback(data); }); return defer.promise; }; factory.unregister = function (method, callback) { }; factory.connect = function (partial, connectCallback, disconnectCallback) { urlFn = $interpolate('http://'+partial+'?request={{request}}'); isConnected = true; connectCallback(); }; factory.subscribe = function (callback) { msgCallback = callback }; return factory; } ]);
Fix compatibility with Python 2 ;)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # © 2017 qsuscs, TobiX from __future__ import print_function, unicode_literals import os import sys from glob import glob os.chdir(os.path.dirname(os.path.abspath(__file__))) exit = 0 for f in glob('dot.*'): dst = os.path.expanduser('~/' + f[3:].replace(u'\u2571', '/')) src = os.path.join(os.getcwd(), f) src_rel = os.path.relpath(src, os.path.dirname(dst)) try: os.makedirs(os.path.dirname(dst)) except OSError: pass try: os.symlink(src_rel, dst) except OSError: # Broken symbolic links do not "exist" if not os.path.exists(dst) or not os.path.samefile(src, dst): print(dst + " exists and does not link do " + src) exit = 1 sys.exit(exit)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # © 2017 qsuscs, TobiX import os import sys from glob import glob os.chdir(os.path.dirname(__file__)) exit = 0 for f in glob('dot.*'): dst = os.path.expanduser('~/' + f[3:].replace(u'\u2571', '/')) src = os.path.join(os.getcwd(), f) src_rel = os.path.relpath(src, os.path.dirname(dst)) try: os.makedirs(os.path.dirname(dst)) except OSError: pass try: os.symlink(src_rel, dst) except FileExistsError: # Broken symbolic links do not "exist" if not os.path.exists(dst) or not os.path.samefile(src, dst): print(dst + " exists and does not link do " + src) exit = 1 sys.exit(exit)
Fix 'bug' with kit toString Was always returning null. Not good for debugging.
/** * The MIT License (MIT) * * Copyright (c) 2015 Sekai Kyoretsuna * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.fudev.laye.vm; /** * @author Sekai Kyoretsuna */ public class LayeKit extends LayeObject { public LayeKit() { } @Override public String toString() { return("LayeKit:" + hashCode()); } public void setField(LayeVM vm, String key, LayeFunction.Callback callback) { setField(vm, key, new LayeFunction(callback)); } }
/** * The MIT License (MIT) * * Copyright (c) 2015 Sekai Kyoretsuna * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.fudev.laye.vm; /** * @author Sekai Kyoretsuna */ public class LayeKit extends LayeObject { public LayeKit() { } @Override public String toString() { return(null); } public void setField(LayeVM vm, String key, LayeFunction.Callback callback) { setField(vm, key, new LayeFunction(callback)); } }
Add users to the list of models.
from pymongo import MongoClient # Magic decorator for defining constants def constant(f): def fset(self, value): raise TypeError def fget(self): return f() return property(fget, fset) class Model: def __init__(self): pass @staticmethod @constant def COLLECTION_NAME(): return Model.__name__ class Post(Model): def __init__(self): Model.__init__(self) @staticmethod @constant def COLLECTION_NAME(): return "posts" class User(Model): def __init__(self): Model.__init__(self) @staticmethod @constant def COLLECTION_NAME(): return "users" class GideonDatabaseClient: @staticmethod @constant def DATABASE_NAME(): return "test-database" def __init__(self): self.client = MongoClient("mongodb://localhost:27017/") self.db = self.client[GideonDatabaseClient.DATABASE_NAME()] def get_collection(self, model_cls): return self.db[model_cls.COLLECTION_NAME()]
from pymongo import MongoClient # Magic decorator for defining constants def constant(f): def fset(self, value): raise TypeError def fget(self): return f() return property(fget, fset) class Model: def __init__(self): pass @staticmethod @constant def COLLECTION_NAME(): return Model.__name__ class Post(Model): def __init__(self): Model.__init__(self) @staticmethod @constant def COLLECTION_NAME(): return "posts" class GideonDatabaseClient: @staticmethod @constant def DATABASE_NAME(): return "test-database" def __init__(self): self.client = MongoClient("mongodb://localhost:27017/") self.db = self.client[GideonDatabaseClient.DATABASE_NAME()] def get_collection(self, model_cls): return self.db[model_cls.COLLECTION_NAME()]
Add posibility to use env variable for the port
package main import ( "flag" "log" "net/http" "net/url" "os" "strings" "text/template" "github.com/rollbrettler/daily-stars/stars" ) var port string func init() { flag.StringVar(&port, "port", ":8001", "Port to listen on") } func main() { flag.Parse() envPort := os.Getenv("PORT") if envPort != "" { port = ":" + envPort } http.HandleFunc("/", showStar) fs := http.FileServer(http.Dir("assets")) http.Handle("/assets/", http.StripPrefix("/assets/", fs)) http.HandleFunc("/favicon.ico", handleFavicon) http.ListenAndServe(port, nil) } func handleFavicon(w http.ResponseWriter, r *http.Request) { w.Write([]byte("")) } func showStar(w http.ResponseWriter, r *http.Request) { username := username(r.URL) log.Printf("%v\n", username) s := stars.Stars{ Username: username, } repos, err := s.Repos() if err != nil { w.Write([]byte("Wrong username")) } t, _ := template.ParseFiles("html/index.html") t.Execute(w, repos) } func username(s *url.URL) string { return strings.SplitN(s.Path, "/", 3)[1] }
package main import ( "flag" "log" "net/http" "net/url" "strings" "text/template" "github.com/rollbrettler/daily-stars/stars" ) var port string func init() { flag.StringVar(&port, "port", ":8001", "Port to listen on") } func main() { flag.Parse() http.HandleFunc("/", showStar) fs := http.FileServer(http.Dir("assets")) http.Handle("/assets/", http.StripPrefix("/assets/", fs)) http.HandleFunc("/favicon.ico", handleFavicon) http.ListenAndServe(port, nil) } func handleFavicon(w http.ResponseWriter, r *http.Request) { w.Write([]byte("")) } func showStar(w http.ResponseWriter, r *http.Request) { username := username(r.URL) log.Printf("%v\n", username) s := stars.Stars{ Username: username, } repos, err := s.Repos() if err != nil { w.Write([]byte("Wrong username")) } t, _ := template.ParseFiles("html/index.html") t.Execute(w, repos) } func username(s *url.URL) string { return strings.SplitN(s.Path, "/", 3)[1] }
Fix exports so module.exports is defined
'use strict' import validateKey from 'firebase-validate-key' import extend from 'xtend' import find from 'babel-runtime/core-js/array/find' import * as serverValue from 'firebase-server-value' export default function valueToFirebase (value) { if (typeof value === 'undefined') { throw new Error('Firebase cannot accept undefined values') } if (typeof value === 'function') { throw new Error(`Firebase cannot accept function values: ${value.toString()}`) } if (value instanceof Date || value instanceof RegExp || value === null) { return null } if (typeof value === 'object') { if (serverValue.is(value)) return serverValue.parse(value) if (Array.isArray(value)) { if (!value.length) return null value = extend({}, value) } const keys = Object.keys(value) if (!keys.length) return null keys.forEach(validateKey) } return value } valueToFirebase.sv = sv
'use strict' import validateKey from 'firebase-validate-key' import extend from 'xtend' import find from 'babel-runtime/core-js/array/find' import * as serverValue from 'firebase-server-value' export default function valueToFirebase (value) { if (typeof value === 'undefined') { throw new Error('Firebase cannot accept undefined values') } if (typeof value === 'function') { throw new Error(`Firebase cannot accept function values: ${value.toString()}`) } if (value instanceof Date || value instanceof RegExp || value === null) { return null } if (typeof value === 'object') { if (serverValue.is(value)) return serverValue.parse(value) if (Array.isArray(value)) { if (!value.length) return null value = extend({}, value) } const keys = Object.keys(value) if (!keys.length) return null keys.forEach(validateKey) } return value } export const sv = serverValue
Add Exception to all with's block.
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file')
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip() for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys: r.write(line) else: print('./passwd_change.py keys_file.txt passwd_file result_file')
Add checking of empty query
#!/usr/bin/env node const request = require('request') const cheerio = require('cheerio') const chalk = require('chalk') const Spinner = require('cli-spinner').Spinner const isChinese = require('is-chinese') const urlencode = require('urlencode') const config = require('./lib/config') const Parser = require('./lib/parser') const word = process.argv.slice(2).join(' ') if(!word){ console.log("Usage: yd <WORD_TO_QUERY>") return } const spinner = new Spinner('努力查询中... %s') if (config.spinner) { spinner.setSpinnerString('|/-\\') spinner.start() } // const word = yargs[0] const is_CN = isChinese(word) const options = { 'url': config.getURL(word) + urlencode(word), 'proxy': config.proxy || null } const ColorOutput = chalk.keyword(config.color) request(options, (error, response, body) => { if (error) { console.error(error) } if (config.spinner) { spinner.stop(true) } console.log(ColorOutput(Parser.parse(is_CN, body))) })
#!/usr/bin/env node const request = require('request') const cheerio = require('cheerio') const chalk = require('chalk') const Spinner = require('cli-spinner').Spinner const isChinese = require('is-chinese') const urlencode = require('urlencode') const config = require('./lib/config') const Parser = require('./lib/parser') const spinner = new Spinner('努力查询中... %s') if (config.spinner) { spinner.setSpinnerString('|/-\\') spinner.start() } const word = process.argv.slice(2).join(' ') const is_CN = isChinese(word) const options = { 'url': config.getURL(word) + urlencode(word), 'proxy': config.proxy || null } const ColorOutput = chalk.keyword(config.color) request(options, (error, response, body) => { if (error) { console.error(error) } if (config.spinner) { spinner.stop(true) } console.log(ColorOutput(Parser.parse(is_CN, body))) })
Allow to provide a custom `occurred_at` value when building a user event
""" byceps.services.user.event_service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from datetime import datetime from typing import Optional, Sequence from ...database import db from ...typing import UserID from .models.event import UserEvent, UserEventData def create_event(event_type: str, user_id: UserID, data: UserEventData) -> None: """Create a user event.""" event = _build_event(event_type, user_id, data) db.session.add(event) db.session.commit() def _build_event(event_type: str, user_id: UserID, data: UserEventData, occurred_at: Optional[datetime]=None) -> UserEvent: """Assemble, but not persist, a user event.""" if occurred_at is None: occurred_at = datetime.utcnow() return UserEvent(occurred_at, event_type, user_id, data) def get_events_for_user(user_id: UserID) -> Sequence[UserEvent]: """Return the events for that user.""" return UserEvent.query \ .filter_by(user_id=user_id) \ .order_by(UserEvent.occurred_at) \ .all()
""" byceps.services.user.event_service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from datetime import datetime from typing import Sequence from ...database import db from ...typing import UserID from .models.event import UserEvent, UserEventData def create_event(event_type: str, user_id: UserID, data: UserEventData) -> None: """Create a user event.""" event = _build_event(event_type, user_id, data) db.session.add(event) db.session.commit() def _build_event(event_type: str, user_id: UserID, data: UserEventData ) -> UserEvent: """Assemble, but not persist, a user event.""" now = datetime.utcnow() return UserEvent(now, event_type, user_id, data) def get_events_for_user(user_id: UserID) -> Sequence[UserEvent]: """Return the events for that user.""" return UserEvent.query \ .filter_by(user_id=user_id) \ .order_by(UserEvent.occurred_at) \ .all()
Add filename to parent error og
if (document.location.hostname == "localhost") { var baseurl = ""; } else { var baseurl = "https://noconfidencevote.openup.org.za"; } function logError(e) { try { var strValues = "description=" + escape(e.message); strValues += "&errLine=" + e.lineno; strValues += "&errFile=" + e.filename; var xhr = new XMLHttpRequest(); xhr.open('GET', baseurl + "/errorSave/?" + strValues, false); xhr.send(); document.write("."); return xhr; } catch (er) { // Do absolutely nothing to avoid error loop } } var agent = navigator.userAgent.toLowerCase(); var isAndroidApp = agent.includes("android") && window.location.href.includes("local.app"); if (isAndroidApp) { // addEventListener only available in later chrome versions if ('addEventListener' in window) { window.addEventListener('error', logError); } else { alert("no addEventListener"); } } document.write('<div id="contactmps-embed-parent"></div>'); document.write('<script type="text/javascript" src="' + baseurl + '/static/javascript/pym.v1.min.js" crossorigin="anonymous"></script>'); document.write("<script>var pymParent = new pym.Parent('contactmps-embed-parent', '" + baseurl + "/campaign/secretballot/', {});</script>");
if (document.location.hostname == "localhost") { var baseurl = ""; } else { var baseurl = "https://noconfidencevote.openup.org.za"; } function logError(e) { try { var strValues = "description=" + escape(e.message); strValues += "&errLine=" + e.lineno; var xhr = new XMLHttpRequest(); xhr.open('GET', baseurl + "/errorSave/?" + strValues, false); xhr.send(); document.write("."); return xhr; } catch (er) { // Do absolutely nothing to avoid error loop } } var agent = navigator.userAgent.toLowerCase(); var isAndroidApp = agent.includes("android") && window.location.href.includes("local.app"); if (isAndroidApp) { // addEventListener only available in later chrome versions if ('addEventListener' in window) { window.addEventListener('error', logError); } else { alert("no addEventListener"); } } document.write('<div id="contactmps-embed-parent"></div>'); document.write('<script type="text/javascript" src="' + baseurl + '/static/javascript/pym.v1.min.js" crossorigin="anonymous"></script>'); document.write("<script>var pymParent = new pym.Parent('contactmps-embed-parent', '" + baseurl + "/campaign/secretballot/', {});</script>"); if (!isAndroidApp) { document.write('...'); }
Make return value of function a tuple This should make the return value consistent with what struct.unpack would return.
# The note off event contains no data, except for the least significant bits # represening the polyphonic ID, so that all notes with that particular # polyphonic ID can be turned off. def parse_noteOff(bmsfile, read, strict, commandID): return (commandID & 0b111,) # Several commands use three bytes of data and one byte for # something else. Because Python's struct module does not have # a way to parse three bytes at once, we need to do it as follows. def parse_1Byte_1Tripplet(bmsfile, read, strict, commandID): byte = read.byte() tripplet = read.tripplet() return (byte, tripplet) # Variable-length delay def parse_VL_delay(bmsfile, read, strict, commandID): start = bmsfile.tell() value = read.byte() while (value >> 7) == 1: value = read.byte() dataLen = bmsfile.tell() - start bmsfile.seek(start) data = read.byteArray(dataLen) return (data, )
# The note off event contains no data, except for the least significant bits # represening the polyphonic ID, so that all notes with that particular # polyphonic ID can be turned off. def parse_noteOff(bmsfile, read, strict, commandID): return commandID & 0b111 # Several commands use three bytes of data and one byte for # something else. Because Python's struct module does not have # a way to parse three bytes at once, we need to do it as follows. def parse_1Byte_1Tripplet(bmsfile, read, strict, commandID): byte = read.byte() tripplet = read.tripplet() return (byte, tripplet) # Variable-length delay def parse_VL_delay(bmsfile, read, strict, commandID): start = bmsfile.tell() value = read.byte() while (value >> 7) == 1: value = read.byte() dataLen = bmsfile.tell() - start bmsfile.seek(start) data = read.byteArray(dataLen) return (data, )
Add debug animation on text change
package com.sometrik.framework; import com.sometrik.formtest.R; import android.content.Context; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; public class FWButton extends Button implements NativeCommandHandler { FrameWork frame; public FWButton(FrameWork frameWork) { super(frameWork); this.frame = frameWork; } @Override public void addChild(View view) { System.out.println("FWButton couldn't handle command"); } @Override public void removeChild(int id) { System.out.println("FWButton couldn't handle command"); } @Override public void addOption(int optionId, String text) { System.out.println("FWButton couldn't handle command"); } @Override public void setValue(String v) { setText(v); //FIXME Debug animation Animation shake = AnimationUtils.loadAnimation(frame, R.anim.shake); startAnimation(shake); } @Override public void setValue(int v) { System.out.println("FWButton couldn't handle command"); } @Override public int getElementId() { return getId(); } @Override public void setEnabled(Boolean enabled) { System.out.println("FWButton couldn't handle command"); } }
package com.sometrik.framework; import android.content.Context; import android.view.View; import android.widget.Button; public class FWButton extends Button implements NativeCommandHandler { FrameWork frame; public FWButton(FrameWork frameWork) { super(frameWork); this.frame = frameWork; } @Override public void addChild(View view) { System.out.println("FWButton couldn't handle command"); } @Override public void removeChild(int id) { System.out.println("FWButton couldn't handle command"); } @Override public void addOption(int optionId, String text) { System.out.println("FWButton couldn't handle command"); } @Override public void setValue(String v) { setText(v); } @Override public void setValue(int v) { System.out.println("FWButton couldn't handle command"); } @Override public int getElementId() { return getId(); } @Override public void setEnabled(Boolean enabled) { System.out.println("FWButton couldn't handle command"); } }
Fix many to many polymorphic pivot updates `$morphType ` set by `setMorphType` is being included in queries from x->pivot->save() and the like. As the object is being added as a public data member on an object with an empty original, it is treated as an attribute and added as a column to the queries. As this column doesn't exist, the query will be erroneous. https://github.com/laravel/framework/issues/3693
<?php namespace Illuminate\Database\Eloquent\Relations; use Illuminate\Database\Eloquent\Builder; class MorphPivot extends Pivot { /** * The type of the polymorphic relation. * * @var string */ protected $morphType; /** * Set the keys for a save update query. * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ protected function setKeysForSaveQuery(Builder $query) { $query->where($this->morphType, $this->getAttribute($this->morphType)); return parent::setKeysForSaveQuery($query); } /** * Delete the pivot model record from the database. * * @return int */ public function delete() { $query = $this->getDeleteQuery(); $query->where($this->morphType, $this->getAttribute($this->morphType)); return $query->delete(); } /** * Set the morph type for the pivot. * * @param string $morphType * @return \Illuminate\Database\Eloquent\Relations\MorphPivot */ public function setMorphType($morphType) { $this->morphType = $morphType; return $this; } }
<?php namespace Illuminate\Database\Eloquent\Relations; use Illuminate\Database\Eloquent\Builder; class MorphPivot extends Pivot { /** * Set the keys for a save update query. * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ protected function setKeysForSaveQuery(Builder $query) { $query->where($this->morphType, $this->getAttribute($this->morphType)); return parent::setKeysForSaveQuery($query); } /** * Delete the pivot model record from the database. * * @return int */ public function delete() { $query = $this->getDeleteQuery(); $query->where($this->morphType, $this->getAttribute($this->morphType)); return $query->delete(); } /** * Set the morph type for the pivot. * * @param string $morphType * @return \Illuminate\Database\Eloquent\Relations\MorphPivot */ public function setMorphType($morphType) { $this->morphType = $morphType; return $this; } }
Remove require of old dependency "shell-escape"
var _ = require("lodash"); var Q = require("q"); var fs = require("./fs"); var spawn = require('spawn-cmd').spawn; var links = require("./links"); // Convert a svg file var convertSVG = function(source, dest, options) { if (!fs.existsSync(source)) return Q.reject(new Error("File doesn't exist: "+source)); var d = Q.defer(); options = _.defaults(options || {}, { }); //var command = shellescape(['svgexport', source, dest]); var child = spawn('svgexport', [source, dest]); child.on("error", function(error) { if (error.code == "ENOENT") error = new Error("Need to install 'svgexport' using 'npm install svgexport -g'"); return d.reject(error); }); child.on("close", function(code) { if (code == 0 && fs.existsSync(dest)) { d.resolve(); } else { d.reject(new Error("Error converting "+source+" into "+dest)); } }); return d.promise; }; module.exports = { convertSVG: convertSVG, INVALID: [".svg"] };
var _ = require("lodash"); var Q = require("q"); var fs = require("./fs"); var shellescape = require('shell-escape'); var spawn = require('spawn-cmd').spawn; var links = require("./links"); // Convert a svg file var convertSVG = function(source, dest, options) { if (!fs.existsSync(source)) return Q.reject(new Error("File doesn't exist: "+source)); var d = Q.defer(); options = _.defaults(options || {}, { }); //var command = shellescape(['svgexport', source, dest]); var child = spawn('svgexport', [source, dest]); child.on("error", function(error) { if (error.code == "ENOENT") error = new Error("Need to install 'svgexport' using 'npm install svgexport -g'"); return d.reject(error); }); child.on("close", function(code) { if (code == 0 && fs.existsSync(dest)) { d.resolve(); } else { d.reject(new Error("Error converting "+source+" into "+dest)); } }); return d.promise; }; module.exports = { convertSVG: convertSVG, INVALID: [".svg"] };
Fix migrate to ia script
from django.core.management.base import BaseCommand from bulbs.content.models import Content, FeatureType from bulbs.content.tasks import post_to_instant_articles_api import timezone class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('feature', nargs="+", type=str) def handle(self, *args, **options): feature_types = FeatureType.objects.all(instant_article=True) feature = options['feature'][0] if feature: feature_types = feature_types.objects.filter(slug=feature) for ft in feature_types: # All published content belonging to feature type content = Content.objects.filter( feature_type=ft, published__isnull=False, published__lte=timezone.now()) for c in content: post_to_instant_articles_api.delay(c.id)
from django.core.management.base import BaseCommand from bulbs.content.models import Content, FeatureType from bulbs.content.tasks import post_to_instant_articles_api import timezone class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('feature', nargs="+", type=str) def handle(self, *args, **options): feature_types = FeatureType.objects.all() feature = options['feature'][0] if feature: feature_types.objects.filter(slug=feature) for ft in feature_types: if ft.instant_article: # All published content belonging to feature type content = Content.objects.filter( feature_type=ft, published__isnull=False, published__lte=timezone.now()) for c in content: post_to_instant_articles_api.delay(c.id)
Update minimum supported browser versions
/** * Copyright (c) 2017 * Thomas Müller <thomas.mueller@tmit.eu> * * This file is licensed under the Affero General Public License version 3 or later. * See the COPYING-README file. */ $(document).ready(function() { // You can Customize here window.$buoop = { vs: { i: 10, f: 54, o: 0, s: 9, c: 60 }, reminder: 0, // after how many hours should the message reappear test: false, // true = always show the bar (for testing) newwindow: true, // open link in new window/tab url: null, // the url to go to after clicking the notification noclose:true // Do not show the "ignore" button to close the notification }; var path = OC.filePath('core','vendor','browser-update/browser-update.js'); $.getScript(path); });
/** * Copyright (c) 2017 * Thomas Müller <thomas.mueller@tmit.eu> * * This file is licensed under the Affero General Public License version 3 or later. * See the COPYING-README file. */ $(document).ready(function() { // You can Customize here window.$buoop = { vs: { i: 10, f: 45, o: 0, s: 8, c: 45 }, reminder: 0, // after how many hours should the message reappear test: false, // true = always show the bar (for testing) newwindow: true, // open link in new window/tab url: null, // the url to go to after clicking the notification noclose:true // Do not show the "ignore" button to close the notification }; var path = OC.filePath('core','vendor','browser-update/browser-update.js'); $.getScript(path); });
[js] Set default rule to `program`
module.exports = (function() { return function(options) { var src, rule, syntax, getTokens, mark, rules, tokens; if (!options || !options.src) throw new Error('Please, pass a string to parse'); src = typeof options === 'string' ? options : options.src; syntax = options.syntax || 'css'; rule = options.rule || (syntax === 'js' ? 'program' : 'stylesheet'); try { getTokens = require('./' + syntax + '/tokenizer'); mark = require('./' + syntax + '/mark'); rules = require('./' + syntax + '/rules'); } catch (e) { return console.error('Syntax "' + syntax + '" is not supported yet, sorry'); } tokens = getTokens(src); mark(tokens); return rules(tokens, rule); } })();
module.exports = (function() { return function(options) { var src, rule, syntax, getTokens, mark, rules, tokens; if (!options || !options.src) throw new Error('Please, pass a string to parse'); src = typeof options === 'string' ? options : options.src; rule = options.rule || 'stylesheet'; syntax = options.syntax || 'css'; try { getTokens = require('./' + syntax + '/tokenizer'); mark = require('./' + syntax + '/mark'); rules = require('./' + syntax + '/rules'); } catch (e) { return console.error('Syntax "' + syntax + '" is not supported yet, sorry'); } tokens = getTokens(src); mark(tokens); return rules(tokens, rule); } })();
Install Composer dev deps in local stage
<?php require_once __DIR__ . '/deployer/recipe/configure.php'; require_once __DIR__ . '/deployer/recipe/yii2-app-basic.php'; serverList(__DIR__ . '/stage/servers.yml'); set('repository', '{{repository}}'); if('{{stage}}' === 'local') { env('composer_options', 'install --verbose --no-progress --no-interaction'); } set('keep_releases', 2); set('shared_files', [ 'config/db.php' ]); task('deploy:build_assets', function () { runLocally('gulp build'); upload(__DIR__ . '/web/css', '{{release_path}}/web/css'); upload(__DIR__ . '/web/js', '{{release_path}}/web/js'); upload(__DIR__ . '/web/fonts', '{{release_path}}/web/fonts'); })->desc('Build assets'); after('deploy:shared', 'deploy:configure'); after('deploy:run_migrations', 'deploy:build_assets');
<?php require_once __DIR__ . '/deployer/recipe/configure.php'; require_once __DIR__ . '/deployer/recipe/yii2-app-basic.php'; serverList(__DIR__ . '/stage/servers.yml'); set('repository', '{{repository}}'); set('keep_releases', 2); set('shared_files', [ 'config/db.php' ]); task('deploy:build_assets', function () { runLocally('gulp build'); upload(__DIR__ . '/web/css', '{{release_path}}/web/css'); upload(__DIR__ . '/web/js', '{{release_path}}/web/js'); upload(__DIR__ . '/web/fonts', '{{release_path}}/web/fonts'); })->desc('Build assets'); after('deploy:shared', 'deploy:configure'); after('deploy:run_migrations', 'deploy:build_assets');
Use trial unittest instead of python unittest
import os from twisted.trial import unittest from ooni.utils import pushFilenameStack class TestUtils(unittest.TestCase): def test_pushFilenameStack(self): basefilename = os.path.join(os.getcwd(), 'dummyfile') f = open(basefilename, "w+") f.write("0\n") f.close() for i in xrange(1, 5): f = open(basefilename+".%s" % i, "w+") f.write("%s\n" % i) f.close() pushFilenameStack(basefilename) for i in xrange(1, 5): f = open(basefilename+".%s" % i) c = f.readlines()[0].strip() self.assertEqual(str(i-1), str(c)) f.close()
import os import unittest from ooni.utils import pushFilenameStack class TestUtils(unittest.TestCase): def test_pushFilenameStack(self): basefilename = os.path.join(os.getcwd(), 'dummyfile') f = open(basefilename, "w+") f.write("0\n") f.close() for i in xrange(1, 5): f = open(basefilename+".%s" % i, "w+") f.write("%s\n" % i) f.close() pushFilenameStack(basefilename) for i in xrange(1, 5): f = open(basefilename+".%s" % i) c = f.readlines()[0].strip() self.assertEqual(str(i-1), str(c)) f.close()
Add diagnostic output for when X-SendFile is misconfigured
import json import os from django.conf import settings from django.http import HttpResponse from django.views.decorators.cache import cache_page from .wordcloud import popular_words @cache_page(60*60*4) def wordcloud(request, max_entries=30): """ Return tag cloud JSON results""" max_entries = int(max_entries) leaf_name = 'wordcloud-{0}.json'.format(max_entries) cache_path = os.path.join( settings.MEDIA_ROOT, 'wordcloud_cache', leaf_name ) if os.path.exists(cache_path): response = HttpResponse(json.dumps({ 'error': ("If you can see this, then X-SendFile isn't configured " "correctly in your webserver. (If you're using Nginx, you'll " "have to change the code to add a X-Accel-Redirect header - " "this hasn't currently been tested.)") })) response['Content-Type'] = 'application/json' response['X-Sendfile'] = cache_path.encode('utf-8') return response content = json.dumps(popular_words(max_entries=max_entries)) return HttpResponse( content, content_type='application/json', )
import json import os from django.conf import settings from django.http import HttpResponse from django.views.decorators.cache import cache_page from .wordcloud import popular_words @cache_page(60*60*4) def wordcloud(request, max_entries=30): """ Return tag cloud JSON results""" max_entries = int(max_entries) leaf_name = 'wordcloud-{0}.json'.format(max_entries) cache_path = os.path.join( settings.MEDIA_ROOT, 'wordcloud_cache', leaf_name ) if os.path.exists(cache_path): response = HttpResponse() response['Content-Type'] = 'application/json' response['X-Sendfile'] = cache_path.encode('utf-8') return response content = json.dumps(popular_words(max_entries=max_entries)) return HttpResponse( content, content_type='application/json', )
Change from eql to equal
import { expect } from 'chai'; import post911GIBStatus from '../../../src/js/post-911-gib-status/reducers'; const initialState = { enrollmentData: null, available: false }; describe('post911GIBStatus reducer', () => { it('should handle failure to fetch enrollment information', () => { const state = post911GIBStatus.post911GIBStatus( initialState, { type: 'GET_ENROLLMENT_DATA_FAILURE' } ); expect(state.enrollmentData).to.be.null; expect(state.available).to.be.false; }); it('should handle a successful request for enrollment information', () => { const state = post911GIBStatus.post911GIBStatus( initialState, { type: 'GET_ENROLLMENT_DATA_SUCCESS', data: { firstName: 'Jane', lastName: 'Austen', dateOfBirth: '9/1/1980', vaFileNumber: '111223333' } } ); expect(state.enrollmentData.firstName).to.equal('Jane'); expect(state.available).to.be.true; }); });
import { expect } from 'chai'; import post911GIBStatus from '../../../src/js/post-911-gib-status/reducers'; const initialState = { enrollmentData: null, available: false }; describe('post911GIBStatus reducer', () => { it('should handle failure to fetch enrollment information', () => { const state = post911GIBStatus.post911GIBStatus( initialState, { type: 'GET_ENROLLMENT_DATA_FAILURE' } ); expect(state.enrollmentData).to.be.null; expect(state.available).to.be.false; }); it('should handle a successful request for enrollment information', () => { const state = post911GIBStatus.post911GIBStatus( initialState, { type: 'GET_ENROLLMENT_DATA_SUCCESS', data: { firstName: 'Jane', lastName: 'Austen', dateOfBirth: '9/1/1980', vaFileNumber: '111223333' } } ); expect(state.enrollmentData.firstName).to.eql('Jane'); expect(state.available).to.be.true; }); });
Raise memory limit for coverage tests
<?php /** * A few common settings for all unit tests. * * Also remember do define the @package attribute for your test class to make it appear under * the right package in unit test and code coverage reports. */ define('PRADO_TEST_RUN', true); define('PRADO_FRAMEWORK_DIR', dirname(__FILE__).'/../../framework'); define('VENDOR_DIR', dirname(__FILE__).'/../../vendor'); set_include_path(PRADO_FRAMEWORK_DIR.PATH_SEPARATOR.get_include_path()); // coverage tests waste a lot of memory! ini_set('memory_limit', '1G'); if (!@include_once VENDOR_DIR.'/autoload.php') { die('You must set up the project dependencies, run the following commands: wget http://getcomposer.org/composer.phar php composer.phar install'); } require_once(PRADO_FRAMEWORK_DIR.'/prado.php'); // for FunctionalTests require_once(__DIR__.'/PradoGenericSeleniumTest.php');
<?php /** * A few common settings for all unit tests. * * Also remember do define the @package attribute for your test class to make it appear under * the right package in unit test and code coverage reports. */ define('PRADO_TEST_RUN', true); define('PRADO_FRAMEWORK_DIR', dirname(__FILE__).'/../../framework'); define('VENDOR_DIR', dirname(__FILE__).'/../../vendor'); set_include_path(PRADO_FRAMEWORK_DIR.PATH_SEPARATOR.get_include_path()); if (!@include_once VENDOR_DIR.'/autoload.php') { die('You must set up the project dependencies, run the following commands: wget http://getcomposer.org/composer.phar php composer.phar install'); } require_once(PRADO_FRAMEWORK_DIR.'/prado.php'); // for FunctionalTests require_once(__DIR__.'/PradoGenericSeleniumTest.php');
Change forEach to use map instead
const fse = require("fs-extra"); const findUpdatedFiles = ( sourceFilesArtifacts, sourceFilesArtifactsUpdatedTimes ) => { // Stat all the source files, getting there updated times, and comparing them to // the artifact updated times. const sourceFiles = Object.keys(sourceFilesArtifacts); let sourceFileStats; sourceFileStats = sourceFiles.map(file => { try { return fse.statSync(file); } catch (error) { // Ignore it. This means the source file was removed // but the artifact file possibly exists. Return null // to signfy that we should ignore it. return null; } }); return sourceFiles .map((sourceFile, index) => { const sourceFileStat = sourceFileStats[index]; // Ignore updating artifacts if source file has been removed. if (sourceFileStat == null) return; const artifactsUpdatedTime = sourceFilesArtifactsUpdatedTimes[sourceFile] || 0; const sourceFileUpdatedTime = ( sourceFileStat.mtime || sourceFileStat.ctime ).getTime(); if (sourceFileUpdatedTime > artifactsUpdatedTime) return sourceFile; }) .filter(file => file); }; module.exports = { findUpdatedFiles };
const fse = require("fs-extra"); const findUpdatedFiles = ( sourceFilesArtifacts, sourceFilesArtifactsUpdatedTimes ) => { let updatedFiles = []; // Stat all the source files, getting there updated times, and comparing them to // the artifact updated times. const sourceFiles = Object.keys(sourceFilesArtifacts); let sourceFileStats; sourceFileStats = sourceFiles.map(file => { try { return fse.statSync(file); } catch (error) { // Ignore it. This means the source file was removed // but the artifact file possibly exists. Return null // to signfy that we should ignore it. return null; } }); sourceFiles.forEach((sourceFile, index) => { const sourceFileStat = sourceFileStats[index]; // Ignore updating artifacts if source file has been removed. if (sourceFileStat == null) return; const artifactsUpdatedTime = sourceFilesArtifactsUpdatedTimes[sourceFile] || 0; const sourceFileUpdatedTime = ( sourceFileStat.mtime || sourceFileStat.ctime ).getTime(); if (sourceFileUpdatedTime > artifactsUpdatedTime) { updatedFiles.push(sourceFile); } }); return updatedFiles; }; module.exports = { findUpdatedFiles };
Fix whitespace at the end of the URL breaking routing
<?php require __DIR__.'/../includes/init.php'; use App\RegExp; use App\HTTP; use App\Users; use App\CoreUtils; $permRedirectPattern = new RegExp('^\s*(.*?)\.php(\?.*)?$','i'); if (preg_match($permRedirectPattern, $_SERVER['REQUEST_URI'])) HTTP::redirect(preg_replace($permRedirectPattern, '$1$2', $_SERVER['REQUEST_URI'])); $decoded_uri = urldecode(CoreUtils::trim($_SERVER['REQUEST_URI'])); if (!preg_match($REWRITE_REGEX,strtok($decoded_uri,'?'),$matches)){ Users::authenticate(); CoreUtils::notFound(); } $do = empty($matches[1]) ? 'index' : $matches[1]; $data = $matches[2] ?? ''; require INCPATH.'routes.php'; /** @var $match array */ $match = $router->match($decoded_uri); if (!isset($match['target'])) CoreUtils::notFound(); (\App\RouteHelper::processHandler($match['target']))($match['params']);
<?php require __DIR__.'/../includes/init.php'; use App\RegExp; use App\HTTP; use App\Users; use App\CoreUtils; $permRedirectPattern = new RegExp('^\s*(.*?)\.php(\?.*)?$','i'); if (preg_match($permRedirectPattern, $_SERVER['REQUEST_URI'])) HTTP::redirect(preg_replace($permRedirectPattern, '$1$2', $_SERVER['REQUEST_URI'])); $decoded_uri = urldecode($_SERVER['REQUEST_URI']); if (!preg_match($REWRITE_REGEX,strtok($decoded_uri,'?'),$matches)){ Users::authenticate(); CoreUtils::notFound(); } $do = empty($matches[1]) ? 'index' : $matches[1]; $data = $matches[2] ?? ''; require INCPATH.'routes.php'; /** @var $match array */ $match = $router->match($decoded_uri); if (!isset($match['target'])) CoreUtils::notFound(); (\App\RouteHelper::processHandler($match['target']))($match['params']);