text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Introduce bounds for generics in annotation
/** * * Copyright (c) 2006-2015, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.speedment.core; import com.speedment.core.manager.Manager; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks this class as an Entity. * <p> * A Class with this annotation is marked as an entity. * * @author pemi */ @Retention(value = RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Entity { /** * Class that holds the manager type. * * @return the manager class type */ Class<? extends Manager<?, ?, ?>> managerType(); /** * Class that holds the builder type. * * @return the builder class type */ Class<? extends Buildable<?>> builderType(); /** * Class that holds the primary key type. * * @return the primary key class type */ Class<?> primaryKeyType(); }
/** * * Copyright (c) 2006-2015, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.speedment.core; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks this class as an Entity. * <p> * A Class with this annotation is marked as an entity. * * @author pemi */ @Retention(value = RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Entity { /** * Class that holds the manager type. * * @return the manager class type */ Class<?> managerType(); /** * Class that holds the builder type. * * @return the builder class type */ Class<?> builderType(); /** * Class that holds the primary key type. * * @return the primary key class type */ Class<?> primaryKeyType(); }
Use BlobBuilder (supported by Chrome for Android)
// Based on http://www.html5rocks.com/en/tutorials/workers/basics/ define(function() { var URL = window.URL || window.webkitURL // BlobBuilder is deprecated but Chrome for Android fails with an "Illegal constructor" // instantiating the Blob directly var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder if (URL && Worker && Blob && BlobBuilder) { var blobBuilder = new BlobBuilder blobBuilder.append('self.onmessage = function(event) { setInterval(function() { self.postMessage({}) }, event.data.interval) }') var blob = blobBuilder.getBlob('text/javascript') var blobUrl = URL.createObjectURL(blob) return function(callback, interval) { var worker = new Worker(blobUrl) worker.addEventListener('message', callback) worker.postMessage({interval: interval}) } } console.log("Worker or Blob not available, falling back to setInterval()") return setInterval })
// Based on http://www.html5rocks.com/en/tutorials/workers/basics/ define(function() { var URL = window.URL || window.webkitURL if (URL && Worker && Blob) { var blobUrl = URL.createObjectURL(new Blob( ['self.onmessage = function(event) { setInterval(function() { self.postMessage({}) }, event.data.interval) }'], {type: 'text/javascript'} )) return function(callback, interval) { var worker = new Worker(blobUrl) worker.addEventListener('message', callback) worker.postMessage({interval: interval}) } } console.log("Worker or Blob not available, falling back to setInterval()") return setInterval })
Use simple array for added index in MemoryStore
var SortedArray = require('sorted-array') var compareTime = require('./compare-time') function compareCreated (a, b) { return compareTime(b[1].created, a[1].created) } /** * Simpliest memory-based events store. * * It is good for tests, but not for server or client usage, * because it doesn’t save events to file or localStorage. * * @example * import { MemoryStore } from 'logux-core' * * var log = new Log({ * store: new MemoryStore(), * timer: createTestTimer() * }) * * @class */ function MemoryStore () { this.created = new SortedArray([], compareCreated) this.added = [] } MemoryStore.prototype = { get: function get (order) { if (order === 'added') { return Promise.resolve({ data: this.added }) } else { return Promise.resolve({ data: this.created.array }) } }, add: function add (entry) { this.created.insert(entry) this.added.unshift(entry) }, remove: function remove (entry) { this.created.remove(entry) for (var i = this.added.length - 1; i >= 0; i--) { if (compareTime(this.added[i][1].created, entry[1].created) === 0) { this.added.splice(i, 1) break } } } } module.exports = MemoryStore
var SortedArray = require('sorted-array') var compareTime = require('./compare-time') function compareCreated (a, b) { return compareTime(b[1].created, a[1].created) } function compareAdded (a, b) { return b[1].added - a[1].added } /** * Simpliest memory-based events store. * * It is good for tests, but not for server or client usage, * because it doesn’t save events to file or localStorage. * * @example * import { MemoryStore } from 'logux-core' * * var log = new Log({ * store: new MemoryStore(), * timer: createTestTimer() * }) * * @class */ function MemoryStore () { this.created = new SortedArray([], compareCreated) this.added = new SortedArray([], compareAdded) } MemoryStore.prototype = { get: function get (order) { var data = order === 'added' ? this.added : this.created return Promise.resolve({ data: data.array }) }, add: function add (entry) { this.created.insert(entry) this.added.insert(entry) }, remove: function remove (entry) { this.created.remove(entry) this.added.remove(entry) } } module.exports = MemoryStore
Add todo for future work
import xbmc,xbmcaddon,xbmcgui,json,random def getAllMovies(): # TODO: determine all/unwatched/watched from settings... # rpccmd = {'jsonrpc': '2.0', 'method': 'VideoLibrary.GetMovies', 'params': { 'filter': { 'field': 'playcount', 'operator': 'lessthan', 'value': '1' }, 'properties': [ 'file' ] }, 'id': 'libMovies'} rpccmd = {'jsonrpc': '2.0', 'method': 'VideoLibrary.GetMovies', 'params': { 'properties': [ 'file' ] }, 'id': 'libMovies'} rpccmd = json.dumps(rpccmd) result = xbmc.executeJSONRPC(rpccmd) result = json.loads(result) return result addon = xbmcaddon.Addon() addonName = addon.getAddonInfo('name') addonIcon = addon.getAddonInfo('icon') movies = getAllMovies() movie = random.choice(movies['result']['movies']) time = 5000 xbmc.executebuiltin('PlayMedia(%s)'%(movie['file'])) xbmc.executebuiltin('Notification(%s, %s %s, %d, %s)'%(addonName,"Playing ",movie['label'],time,addonIcon))
import xbmc,xbmcaddon,xbmcgui,json,random def getAllMovies(): rpccmd = {'jsonrpc': '2.0', 'method': 'VideoLibrary.GetMovies', 'params': { 'properties': [ 'file' ] }, 'id': 'libMovies'} rpccmd = json.dumps(rpccmd) result = xbmc.executeJSONRPC(rpccmd) result = json.loads(result) return result addon = xbmcaddon.Addon() addonName = addon.getAddonInfo('name') addonIcon = addon.getAddonInfo('icon') movies = getAllMovies() movie = random.choice(movies['result']['movies']) time = 5000 xbmc.executebuiltin('PlayMedia(%s)'%(movie['file'])) xbmc.executebuiltin('Notification(%s, %s %s, %d, %s)'%(addonName,"Playing ",movie['label'],time,addonIcon))
Stop exporting internal symbols from the shared libraries.
#!/usr/bin/env python # # # Generate linker script to only expose symbols of the public API # import sys import re if __name__ == '__main__': funcs = list() last_line = '' for line in sys.stdin: m = re.match(r'^(\S+.*\s+\**)?(rd_kafka_\S+)\s*\(', line) if m: sym = m.group(2) m2 = re.match(r'(RD_UNUSED|__attribute__\(\(unused\)\))', line) if not m2: funcs.append(sym) last_line = '' else: last_line = line print('# Automatically generated by lds-gen.py - DO NOT EDIT') print('{\n global:') if len(funcs) == 0: print(' *;') else: for f in sorted(funcs): print(' %s;' % f) print('local:\n *;') print('};')
#!/usr/bin/env python # # # Generate linker script to only expose symbols of the public API # import sys import re if __name__ == '__main__': funcs = list() last_line = '' for line in sys.stdin: m = re.match(r'^(\S+.*\s+\**)?(rd_kafka_\S+)\s*\(', line) if m: sym = m.group(2) m2 = re.match(r'(RD_UNUSED|__attribute__\(\(unused\)\))', line) if not m2: funcs.append(sym) last_line = '' else: last_line = line print('# Automatically generated by lds-gen.py - DO NOT EDIT') print('{\n global:') if len(funcs) == 0: print(' *;') else: for f in sorted(funcs): print(' %s;' % f) print('};')
Sort module files before injecting. The fs.list() does not guarantee the files in a specific order. Sort the module list before injecting them.
/** * @file Ingress-ICE, the main script * @author nibogd (https://github.com/nibogd) * @version 4.4.1 * @license MIT * @see {@link https://github.com/nibogd/ingress-ice|GitHub } * @see {@link https://ingress.netlify.com/|Website } */ "use strict"; /*global phantom */ /*global require */ /*global ice */ var system = require('system'); var args = system.args; var fs = require('fs'); var version = '4.4.1'; var filename = 'ice.js'; var iceFolder = args[0].substring(0, args[0].length - filename.length) + 'modules/'; var iceModules= fs.list(iceFolder).sort(); /* * Loads all scripts in the 'modules' folder */ function loadModules() { for(var i = 0; i < iceModules.length; i++) { var file = iceFolder + iceModules[i]; if(fs.isFile(file)){ phantom.injectJs(file); } } } loadModules(); window.setTimeout(ice, 1000);
/** * @file Ingress-ICE, the main script * @author nibogd (https://github.com/nibogd) * @version 4.4.1 * @license MIT * @see {@link https://github.com/nibogd/ingress-ice|GitHub } * @see {@link https://ingress.netlify.com/|Website } */ "use strict"; /*global phantom */ /*global require */ /*global ice */ var system = require('system'); var args = system.args; var fs = require('fs'); var version = '4.4.1'; var filename = 'ice.js'; var iceFolder = args[0].substring(0, args[0].length - filename.length) + 'modules/'; var iceModules= fs.list(iceFolder); /* * Loads all scripts in the 'modules' folder */ function loadModules() { for(var i = 0; i < iceModules.length; i++) { var file = iceFolder + iceModules[i]; if(fs.isFile(file)){ phantom.injectJs(file); } } } loadModules(); window.setTimeout(ice, 1000);
Increase the amount of output in build scan performance tests.
package ${packageName}; import static org.junit.Assert.*; public class ${testClassName} { private final ${productionClassName} production = new ${productionClassName}("value"); @org.junit.Test public void testOne() { for (int i = 0; i < 500; i++) { System.out.println("Some test output from ${testClassName}.testOne - " + i); System.err.println("Some test error from ${testClassName}.testOne - " + i); } assertEquals(production.getProperty(), "value"); } @org.junit.Test public void testTwo() { for (int i = 0; i < 500; i++) { System.out.println("Some test output from ${testClassName}.testTwo - " + i); System.err.println("Some test error from ${testClassName}.testTwo - " + i); } String expected = <%= binding.hasVariable("halfTestsFail") && binding.halfTestsFail ? "\"foo\"" : "\"value\"" %>; assertEquals(production.getProperty(), expected); } }
package ${packageName}; import static org.junit.Assert.*; public class ${testClassName} { private final ${productionClassName} production = new ${productionClassName}("value"); @org.junit.Test public void testOne() { for (int i = 0; i < 100; i++) { System.out.println("Some test output from ${testClassName}.testOne - " + i); System.err.println("Some test error from ${testClassName}.testOne - " + i); } assertEquals(production.getProperty(), "value"); } @org.junit.Test public void testTwo() { for (int i = 0; i < 100; i++) { System.out.println("Some test output from ${testClassName}.testTwo - " + i); System.err.println("Some test error from ${testClassName}.testTwo - " + i); } String expected = <%= binding.hasVariable("halfTestsFail") && binding.halfTestsFail ? "\"foo\"" : "\"value\"" %>; assertEquals(production.getProperty(), expected); } }
Fix for inability to define contact information.
# encoding: utf-8 """Event model.""" import mongoengine as db from web.extras.contentment.components.page.model import Page from widgets import fields log = __import__('logging').getLogger(__name__) __all__ = ['EventContact', 'Event'] class EventContact(db.EmbeddedDocument): name = db.StringField(max_length=250) email = db.StringField(max_length=250) phone = db.StringField(max_length=64) class Event(Page): _widgets = fields default = db.StringField(default="view:event", max_length=128) organizer = db.StringField(max_length=250) location = db.StringField(max_length=250) starts = db.DateTimeField() stops = db.DateTimeField() allday = db.BooleanField(default=False) contact = db.EmbeddedDocumentField(EventContact) def process(self, formdata): formdata = super(Event, self).process(formdata) contact = EventContact() for field in 'name', 'email', 'phone': combined = 'contact.' + field if combined in formdata: setattr(contact, field, formdata[combined]) del formdata[combined] formdata['contact'] = contact return formdata
# encoding: utf-8 """Event model.""" import mongoengine as db from web.extras.contentment.components.page.model import Page from widgets import fields log = __import__('logging').getLogger(__name__) __all__ = ['EventContact', 'Event'] class EventContact(db.EmbeddedDocument): name = db.StringField(max_length=250) email = db.StringField(max_length=250) phone = db.StringField(max_length=64) class Event(Page): _widgets = fields default = db.StringField(default="view:event", max_length=128) organizer = db.StringField(max_length=250) location = db.StringField(max_length=250) starts = db.DateTimeField() stops = db.DateTimeField() allday = db.BooleanField(default=False) contact = db.EmbeddedDocumentField(EventContact)
Use authExpired action; fix session timeout notification logic
// import {replace} from 'react-router-redux' import {authExpired} from 'shared/actions/auth' import {publishNotification as notify} from 'shared/actions/notifications' import {HTTP_FORBIDDEN} from 'shared/constants' const errorsMiddleware = store => next => action => { if (action.type === 'ERROR_THROWN') { const {error, error: {status, auth}} = action console.error(error) if (status === HTTP_FORBIDDEN) { const {auth: {me}} = store.getState() const wasSessionTimeout = me !== null next(authExpired(auth)) if (wasSessionTimeout) { store.dispatch(notify('error', 'Session timed out. Please login again.')) } else { store.dispatch(notify('error', 'Please login to use Chronograf.')) } } else { store.dispatch(notify('error', 'Cannot communicate with server.')) } } next(action) } export default errorsMiddleware
// import {replace} from 'react-router-redux' import {authReceived, meReceived} from 'shared/actions/auth' import {publishNotification as notify} from 'shared/actions/notifications' import {HTTP_FORBIDDEN} from 'shared/constants' const errorsMiddleware = store => next => action => { if (action.type === 'ERROR_THROWN') { const {error, error: {status, auth}} = action console.error(error) if (status === HTTP_FORBIDDEN) { const {auth: {me}} = store.getState() const wasSessionTimeout = me === null store.dispatch(authReceived(auth)) store.dispatch(meReceived(null)) if (wasSessionTimeout) { store.dispatch(notify('error', 'Please login to use Chronograf.')) } else { store.dispatch(notify('error', 'Session timed out. Please login again.')) } } else { store.dispatch(notify('error', 'Cannot communicate with server.')) } } next(action) } export default errorsMiddleware
Upgrade to 1.3.1, add Zepto support
!function(a){a.fn.hugeOnFacebook=function(b){var c={linkClass:"",addData:!1,minLikes:10,hugeLikes:50,popClass:"popular",hugeClass:"hugeonfacebook",likesVisible:!1,likesVisibleClass:"likesVisible"},d=a.extend({},c,b);if(this.attr("id"))var e="#"+this.attr("id")+" ";else if(this.attr("class"))var f="."+this.attr("class");if(d.linkClass)var g="."+d.linkClass;else if(f)var g=f;else var g="";if(e)var h=e;else var h="";a(h+"a"+g).each(function(){var b=a(this),c=b.attr("href"),e="http://graph.facebook.com/"+c;a.getJSON(e,function(a){var c=a.shares;c>=d.minLikes&&(b.addClass(d.popClass),c>=d.hugeLikes&&b.addClass(d.hugeClass),d.likesVisible&&b.append('<span class="'+d.likesVisibleClass+'">'+c+" Likes</span>"),d.addData&&b.attr("data-likes",c))})})}}(window.jQuery||window.Zepto);
(function(e){e.fn.hugeOnFacebook=function(t){var n={linkClass:"",addData:!1,minLikes:10,hugeLikes:50,popClass:"popular",hugeClass:"hugeonfacebook",likesVisible:!1,likesVisibleClass:"likesVisible"},r=e.extend({},n,t);if(this.attr("id"))var i="#"+this.attr("id")+" ";else if(this.attr("class"))var s="."+this.attr("class");if(r.linkClass)var o="."+r.linkClass;else if(s)var o=s;else var o="";if(i)var u=i;else var u="";e(u+"a"+o).each(function(){var t=e(this),n=t.attr("href"),i="http://graph.facebook.com/"+n;e.getJSON(i,function(e){var n=e.shares;n>=r.minLikes&&(t.addClass(r.popClass),n>=r.hugeLikes&&t.addClass(r.hugeClass),r.likesVisible&&t.append('<span class="'+r.likesVisibleClass+'">'+n+" Likes</span>"),r.addData&&t.attr("data-likes",n))})})}})(jQuery)
Test iter_zones instead of get_zones
import os import types from unittest import TestCase from yoconfigurator.base import read_config from yoconfig import configure_services from pycloudflare.services import CloudFlareService app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) conf = read_config(app_dir) class ZonesTest(TestCase): def setUp(self): configure_services('cloudflare', ['cloudflare'], conf.common) self.cloudflare = CloudFlareService() def test_get_all_zones(self): zones = self.cloudflare.iter_zones() self.assertIsInstance(zones, types.GeneratorType) def test_get_zone(self): zone_id = self.cloudflare.get_zones()[0]['id'] zone = self.cloudflare.get_zone(zone_id) self.assertIsInstance(zone, dict)
import os from unittest import TestCase from yoconfigurator.base import read_config from yoconfig import configure_services from pycloudflare.services import CloudFlareService app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) conf = read_config(app_dir) class ZonesTest(TestCase): def setUp(self): configure_services('cloudflare', ['cloudflare'], conf.common) self.cloudflare = CloudFlareService() def test_get_all_zones(self): zones = self.cloudflare.get_zones() self.assertIsInstance(zones, list) def test_get_zone(self): zone_id = self.cloudflare.get_zones()[0]['id'] zone = self.cloudflare.get_zone(zone_id) self.assertIsInstance(zone, dict)
Remove dead code in test stub. This code does not work and will trigger notice errors if it was actually run.
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 3.0.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace TestApp\Controller\Component; use Cake\Controller\Component; use Cake\Controller\Controller; use Cake\Event\Event; /** * AppleComponent class * */ class AppleComponent extends Component { /** * components property * * @var array */ public $components = array('Orange'); /** * startup method * * @param Event $event * @param mixed $controller * @return void */ public function startup(Event $event) { } }
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 3.0.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace TestApp\Controller\Component; use Cake\Controller\Component; use Cake\Controller\Controller; use Cake\Event\Event; /** * AppleComponent class * */ class AppleComponent extends Component { /** * components property * * @var array */ public $components = array('Orange'); /** * testName property * * @var mixed */ public $testName = null; /** * startup method * * @param Event $event * @param mixed $controller * @return void */ public function startup(Event $event) { $this->testName = $controller->name; } }
Update add braces to control statement
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; import {Wrapper} from "./Wrapper"; /** * Container Component for BuildSnapshots. * * @param {*} props input property containing an array of build data to be * rendered through BuildSnapshot. */ export const BuildSnapshotContainer = React.memo((props) => { const SOURCE = '/data'; const [data, setData] = React.useState([]); /** * Fetch data when component is mounted. * Pass in empty array as second paramater to prevent * infinite callbacks as component refreshes. * @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a> */ React.useEffect(() => { fetch(SOURCE).then(res => setData(res.json())); }, []); return ( <Wrapper> {data.map(snapshotData => <BuildSnapshot data={snapshotData}/>)} </Wrapper> ); } );
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; import {Wrapper} from "./Wrapper"; /** * Container Component for BuildSnapshots. * * @param {*} props input property containing an array of build data to be * rendered through BuildSnapshot. */ export const BuildSnapshotContainer = React.memo((props) => { const SOURCE = '/data'; const [data, setData] = React.useState([]); /** * Fetch data when component is mounted. * Pass in empty array as second paramater to prevent * infinite callbacks as component refreshes. * @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a> */ React.useEffect(() => fetch(SOURCE).then(res => setData(res.json())), []); return ( <Wrapper> {data.map(snapshotData => <BuildSnapshot data={snapshotData}/>)} </Wrapper> ); } );
Make default output consistent with old version I flipped the hyphen around: should be 'anchorhub-out', accidentally was 'out-anchorhub'
""" Defaults for all settings used by AnchorHub """ WRAPPER = '{ }' INPUT = '.' OUTPUT = 'anchorhub-out' ARGPARSER = { 'description': "anchorhub parses through Markdown files and precompiles " "links to specially formatted anchors." } ARGPARSE_INPUT = { 'help': "Path of directory tree to be parsed", } ARGPARSE_OUTPUT = { 'help': "Desired output location (default is \"" + OUTPUT + "\")", 'default': OUTPUT } ARGPARSE_OVERWRITE = { 'help': "Overwrite input files; ignore output location" } ARGPARSE_EXTENSION = { 'help': "Indicate which file extensions to search and run anchorhub on.", 'default': [".md"] } ARGPARSE_WRAPPER = { 'help': "Specify custom wrapper format (default is \"" + WRAPPER + "\")", 'default': WRAPPER }
""" Defaults for all settings used by AnchorHub """ WRAPPER = '{ }' INPUT = '.' OUTPUT = 'out-anchorhub' ARGPARSER = { 'description': "anchorhub parses through Markdown files and precompiles " "links to specially formatted anchors." } ARGPARSE_INPUT = { 'help': "Path of directory tree to be parsed", } ARGPARSE_OUTPUT = { 'help': "Desired output location (default is \"" + OUTPUT + "\")", 'default': OUTPUT } ARGPARSE_OVERWRITE = { 'help': "Overwrite input files; ignore output location" } ARGPARSE_EXTENSION = { 'help': "Indicate which file extensions to search and run anchorhub on.", 'default': [".md"] } ARGPARSE_WRAPPER = { 'help': "Specify custom wrapper format (default is \"" + WRAPPER + "\")", 'default': WRAPPER }
Remove array spread for node v4 compatibility
const conf = require('./gulp.conf'); const wiredep = require('wiredep'); module.exports = function listFiles() { const wiredepOptions = Object.assign({}, conf.wiredep, { <% if (framework === 'react') { -%> overrides: { react: { main: [ 'react-with-addons.js' ] } }, <% } -%> dependencies: true, devDependencies: true }); const patterns = wiredep(wiredepOptions).js.concat([ <% if (framework === 'angular1') { -%> conf.path.tmp('**/*.js'), conf.path.src('**/*.html') <% } -%> <% if (framework === 'react') { -%> conf.path.tmp('app/**/*.js') <% } -%> ]; var files = patterns.map(pattern => ({ pattern: pattern })); files.push({ pattern: conf.path.src('assets/**/*'), included: false, served: true, watched: false }); return files; }
const conf = require('./gulp.conf'); const wiredep = require('wiredep'); module.exports = function listFiles() { const wiredepOptions = Object.assign({}, conf.wiredep, { <% if (framework === 'react') { -%> overrides: { react: { main: [ 'react-with-addons.js' ] } }, <% } -%> dependencies: true, devDependencies: true }); const patterns = [ ...wiredep(wiredepOptions).js, <% if (framework === 'angular1') { -%> conf.path.tmp('**/*.js'), conf.path.src('**/*.html') <% } -%> <% if (framework === 'react') { -%> conf.path.tmp('app/**/*.js') <% } -%> ]; var files = patterns.map(pattern => ({ pattern: pattern })); files.push({ pattern: conf.path.src('assets/**/*'), included: false, served: true, watched: false }); return files; }
Add _format when constructing store.query request
import Ember from "ember"; import DS from "ember-data"; const { get, inject: { service } } = Ember; export default DS.JSONAPIAdapter.extend({ namespace: 'api', drupalMapper: service(), pathForType(modelName) { let drupalMapper = get(this, 'drupalMapper'), entity = drupalMapper.entityFor(modelName), bundle = drupalMapper.bundleFor(modelName); return entity + '/' + bundle; }, buildQuery(snapshot) { let query = this._super(...arguments); query._format = 'api_json'; return query; }, query(store, type, query) { let drupalQuery = { filter: {} }, queryFields = Object.keys(query), mapper = get(this, 'drupalMapper'); queryFields.forEach((field) => { let fieldName = mapper.fieldName(type.modelName, field); drupalQuery.filter[fieldName] = drupalQuery.filter[fieldName] || {}; drupalQuery.filter[fieldName]['value'] = query[field]; }); var url = this.buildURL(type.modelName, null, null, 'query', drupalQuery); if (this.sortQueryParams) { query = this.sortQueryParams(drupalQuery); } query._format = 'api_json'; return this.ajax(url, 'GET', { data: query }); }, });
import Ember from "ember"; import DS from "ember-data"; const { get, inject: { service } } = Ember; export default DS.JSONAPIAdapter.extend({ namespace: 'api', drupalMapper: service(), pathForType(modelName) { let drupalMapper = get(this, 'drupalMapper'), entity = drupalMapper.entityFor(modelName), bundle = drupalMapper.bundleFor(modelName); return entity + '/' + bundle; }, buildQuery(snapshot) { let query = this._super(...arguments); query._format = 'api_json'; return query; }, query(store, type, query) { let drupalQuery = { filter: {} }, queryFields = Object.keys(query), mapper = get(this, 'drupalMapper'); queryFields.forEach((field) => { let fieldName = mapper.fieldName(type.modelName, field); drupalQuery.filter[fieldName] = drupalQuery.filter[fieldName] || {}; drupalQuery.filter[fieldName]['value'] = query[field]; }); var url = this.buildURL(type.modelName, null, null, 'query', drupalQuery); if (this.sortQueryParams) { query = this.sortQueryParams(drupalQuery); } return this.ajax(url, 'GET', { data: query }); }, });
Add support for observing attributes.
// Complete rewrite of adampietrasiak/jquery.initialize // @link https://github.com/adampietrasiak/jquery.initialize // @link https://github.com/dbezborodovrp/jquery.initialize ;(function($) { var MutationSelectorObserver = function(selector, callback) { this.selector = selector; this.callback = callback; } var msobservers = []; msobservers.observe = function(selector, callback) { this.push(new MutationSelectorObserver(selector, callback)); }; msobservers.initialize = function(selector, callback) { $(selector).each(callback); this.observe(selector, callback); }; var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { for (var j = 0; j < msobservers.length; j++) { if (mutation.type == 'childList') { $(mutation.addedNodes).find(msobservers[j].selector).addBack(msobservers[j].selector).each(msobservers[j].callback); } if (mutation.type == 'attributes') { $(mutation.target).filter(msobservers[j].selector).each(msobservers[j].callback); } } }); }); observer.observe(document.documentElement, {childList: true, subtree: true, attributes: true}); $.fn.initialize = function(callback) { msobservers.initialize(this.selector, callback); }; })(jQuery);
// Complete rewrite of adampietrasiak/jquery.initialize // @link https://github.com/adampietrasiak/jquery.initialize // @link https://github.com/dbezborodovrp/jquery.initialize ;(function($) { var MutationSelectorObserver = function(selector, callback) { this.selector = selector; this.callback = callback; } var msobservers = []; msobservers.observe = function(selector, callback) { this.push(new MutationSelectorObserver(selector, callback)); }; msobservers.initialize = function(selector, callback) { $(selector).each(callback); this.observe(selector, callback); }; var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { for (var j = 0; j < msobservers.length; j++) { $(mutation.addedNodes).find(msobservers[j].selector).addBack(msobservers[j].selector).each(msobservers[j].callback); } }); }); observer.observe(document.documentElement, {childList: true, subtree: true}); $.fn.initialize = function(callback) { msobservers.initialize(this.selector, callback); }; })(jQuery);
Make sure AVAILABLE_LAYOUTS is a tuple The .keys() function is a generator in Python 3.
import inspect from .random import random from .circular import circular from .force_directed import fruchterman_reingold _layout_map = { 'random': random, 'circular': circular, 'force_directed': fruchterman_reingold, 'spring_layout': fruchterman_reingold } AVAILABLE_LAYOUTS = tuple(_layout_map.keys()) def get_layout(name, *args, **kwargs): """ Retrieve a graph layout Some graph layouts accept extra options. Please refer to their documentation for more information. Parameters ---------- name : string The name of the layout. The variable `AVAILABLE_LAYOUTS` contains all available layouts. *args Positional arguments which are passed to the layout. **kwargs Keyword arguments which are passed to the layout. Returns ------- layout : callable The callable generator which will calculate the graph layout """ if name not in _layout_map: raise KeyError( "Graph layout '{}' not found. Should be one of {}".format( name, ", ".join(AVAILABLE_LAYOUTS) ) ) layout = _layout_map[name] if inspect.isclass(layout): layout = layout(*args, **kwargs) return layout
import inspect from .random import random from .circular import circular from .force_directed import fruchterman_reingold _layout_map = { 'random': random, 'circular': circular, 'force_directed': fruchterman_reingold, 'spring_layout': fruchterman_reingold } AVAILABLE_LAYOUTS = _layout_map.keys() def get_layout(name, *args, **kwargs): """ Retrieve a graph layout Some graph layouts accept extra options. Please refer to their documentation for more information. Parameters ---------- name : string The name of the layout. The variable `AVAILABLE_LAYOUTS` contains all available layouts. *args Positional arguments which are passed to the layout. **kwargs Keyword arguments which are passed to the layout. Returns ------- layout : callable The callable generator which will calculate the graph layout """ if name not in _layout_map: raise KeyError( "Graph layout '{}' not found. Should be one of {}".format( name, ", ".join(AVAILABLE_LAYOUTS) ) ) layout = _layout_map[name] if inspect.isclass(layout): layout = layout(*args, **kwargs) return layout
Speed up the InputStream interface on Galago's cached stream class.
// BSD License (http://www.galagosearch.org/license) package org.lemurproject.galago.utility.buffer; import java.io.DataInput; import java.io.IOException; import java.io.InputStream; /** * * @author trevor */ public abstract class DataStream extends InputStream implements DataInput { public abstract DataStream subStream(long start, long length) throws IOException; public abstract long getPosition(); public abstract boolean isDone(); public abstract long length(); @Override public int read() throws IOException { if(isDone()) { return -1; } return readUnsignedByte(); } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { int read; for(read=0; read<len && !isDone(); read++) { b[off+read] = (byte) readUnsignedByte(); } return read; } /** * Seeks forward into the stream to a particular byte offset (reverse * seeks are not allowed). The offset is relative to the start position of * this data stream, not the beginning of the file. */ public abstract void seek(long offset); }
// BSD License (http://www.galagosearch.org/license) package org.lemurproject.galago.utility.buffer; import java.io.DataInput; import java.io.IOException; import java.io.InputStream; /** * * @author trevor */ public abstract class DataStream extends InputStream implements DataInput { public abstract DataStream subStream(long start, long length) throws IOException; public abstract long getPosition(); public abstract boolean isDone(); public abstract long length(); @Override public int read() throws IOException { if(isDone()) { return -1; } return readUnsignedByte(); } /** * Seeks forward into the stream to a particular byte offset (reverse * seeks are not allowed). The offset is relative to the start position of * this data stream, not the beginning of the file. */ public abstract void seek(long offset); }
Refactor order of replace in escape
(function() { function escape(text) { return text .replace(/&/g, "&#x26;") .replace(/</g, "&#x3c;") .replace(/>/g, "&#x3e;") .replace(/&#x3c;!--/g, "<!--") .replace(/--&#x3e;/g, "-->") .replace(/&#x3c;&#x3c;/g, "<<") .replace(/&#x3e;&#x3e;/g, ">>") .replace(/&#x3e;\|/g, ">|") .replace(/\|&#x3c;/g, "|<") .replace(/>\|([\d\D]*?)\|</g, function(_, pre) { var escaped = pre .replace(/<</g, "&#x3c;&#x3c;") .replace(/>>/g, "&#x3e;&#x3e;") ; return ['>|', escaped, '|<'].join(''); }) ; } document.getElementById("escape").addEventListener("click", function() { var src = document.getElementById("source").value; var dst = escape(src); document.getElementById("destination").value = dst; }); })();
(function() { function escape(text) { return text .replace(/&/g, "&#x26;") .replace(/>/g, "&#x3e;") .replace(/--&#x3e;/g, "-->") .replace(/&#x3e;&#x3e;/g, ">>") .replace(/&#x3e;\|/g, ">|") .replace(/</g, "&#x3c;") .replace(/&#x3c;!--/g, "<!--") .replace(/&#x3c;&#x3c;/g, "<<") .replace(/\|&#x3c;/g, "|<") .replace(/>\|([\d\D]*?)\|</g, function(_, pre) { var escaped = pre .replace(/>>/g, "&#x3e;&#x3e;") .replace(/<</g, "&#x3c;&#x3c;") ; return ['>|', escaped, '|<'].join(''); }) ; } document.getElementById("escape").addEventListener("click", function() { var src = document.getElementById("source").value; var dst = escape(src); document.getElementById("destination").value = dst; }); })();
Use the correct function to trigger autoload I think this must be pedantic because there is no way you could know it is actually an interface before loading the file.
<?php /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\CoreBundle\Serializer; if (!interface_exists(\Sonata\Serializer\SerializerHandlerInterface::class, false)) { @trigger_error( 'The '.__NAMESPACE__.'\SerializerHandlerInterface class is deprecated since version 3.x and will be removed in 4.0.' .' Use Sonata\Serializer\SerializerHandlerInterface instead.', E_USER_DEPRECATED ); } class_alias( \Sonata\Serializer\SerializerHandlerInterface::class, __NAMESPACE__.'\SerializerHandlerInterface' ); if (false) { /** * @deprecated Since version 3.x, to be removed in 4.0. */ interface SerializerHandlerInterface extends \Sonata\Serializer\SerializerHandlerInterface { /** * @return string */ public static function getType(); } }
<?php /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\CoreBundle\Serializer; if (!class_exists(\Sonata\Serializer\SerializerHandlerInterface::class, false)) { @trigger_error( 'The '.__NAMESPACE__.'\SerializerHandlerInterface class is deprecated since version 3.x and will be removed in 4.0.' .' Use Sonata\Serializer\SerializerHandlerInterface instead.', E_USER_DEPRECATED ); } class_alias( \Sonata\Serializer\SerializerHandlerInterface::class, __NAMESPACE__.'\SerializerHandlerInterface' ); if (false) { /** * @deprecated Since version 3.x, to be removed in 4.0. */ interface SerializerHandlerInterface extends \Sonata\Serializer\SerializerHandlerInterface { /** * @return string */ public static function getType(); } }
Fix to keep build-chain Python 2.6 compatible
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: vraj@reciprocitylabs.com # Maintained By: vraj@reciprocitylabs.com class Cache: """ Tracks modified objects in the session distinguished by type of modification: new, dirty and deleted. """ def __init__(self): self.clear() def update(self, session): self.new.update(session.new) self.deleted.update(session.deleted) modified = set(o for o in session.dirty if session.is_modified(o)) # When intermediate flushes happen, new and dirty may overlap self.dirty.update(modified - self.new - self.deleted) def clear(self): self.new = set() self.dirty = set() self.deleted = set() def copy(self): copied_cache = Cache() copied_cache.new = set(self.new) copied_cache.dirty = set(self.dirty) copied_cache.deleted = set(self.deleted) return copied_cache
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: vraj@reciprocitylabs.com # Maintained By: vraj@reciprocitylabs.com class Cache: """ Tracks modified objects in the session distinguished by type of modification: new, dirty and deleted. """ def __init__(self): self.clear() def update(self, session): self.new.update(session.new) self.deleted.update(session.deleted) modified = {o for o in session.dirty if session.is_modified(o)} # When intermediate flushes happen, new and dirty may overlap self.dirty.update(modified - self.new - self.deleted) def clear(self): self.new = set() self.dirty = set() self.deleted = set() def copy(self): copied_cache = Cache() copied_cache.new = set(self.new) copied_cache.dirty = set(self.dirty) copied_cache.deleted = set(self.deleted) return copied_cache
Align master, 9.0.x and 8.5.x
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.ant; import org.apache.tools.ant.BuildException; /** * Ant task that implements the <code>/serverinfo</code> command * supported by the Tomcat manager application. * * @author Vivek Chopra */ public class ServerinfoTask extends AbstractCatalinaTask { // Public Methods /** * Execute the requested operation. * * @exception BuildException if an error occurs */ @Override public void execute() throws BuildException { super.execute(); execute("/serverinfo"); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.ant; import org.apache.tools.ant.BuildException; /** * Ant task that implements the <code>/serverinfo</code> command * supported by the Tomcat manager application. * * @author Vivek Chopra */ public class ServerinfoTask extends AbstractCatalinaTask { // Public Methods /** * Execute the requested operation. * * @exception BuildException if an error occurs */ @Override public void execute() throws BuildException { super.execute(); execute("/serverinfo"); } }
Return error if we can't inspect a container
package containers import ( "github.com/fsouza/go-dockerclient" ) type DockerRuntime struct { Client *docker.Client } func (r DockerRuntime) isRelated(volume string, container *docker.Container) bool { for _, mount := range container.Mounts { if mount.Name == volume && mount.Driver == "dvol" { return true } } return false } func (runtime DockerRuntime) Related(volume string) ([]string, error) { containers, _ := runtime.Client.ListContainers(docker.ListContainersOptions{}) relatedContainers := make([]string, 0) for _, c := range containers { container, err := runtime.Client.InspectContainer(c.ID) if err != nil { return relatedContainers, err } if runtime.isRelated(volume, container) && container.State.Running { relatedContainers = append(relatedContainers, container.Name) } } return relatedContainers, nil } func (runtime DockerRuntime) Start(volume string) error { return nil } func (runtime DockerRuntime) Stop(volume string) error { return nil } func (runtime DockerRuntime) Remove(volume string) error { return nil }
package containers import ( "github.com/fsouza/go-dockerclient" ) type DockerRuntime struct { Client *docker.Client } func (r DockerRuntime) isRelated(volume string, container *docker.Container) bool { for _, mount := range container.Mounts { if mount.Name == volume && mount.Driver == "dvol" { return true } } return false } func (runtime DockerRuntime) Related(volume string) ([]string, error) { containers, _ := runtime.Client.ListContainers(docker.ListContainersOptions{}) relatedContainers := make([]string, 0) for _, c := range containers { container, _ := runtime.Client.InspectContainer(c.ID) if runtime.isRelated(volume, container) && container.State.Running { relatedContainers = append(relatedContainers, container.Name) } } return relatedContainers, nil } func (runtime DockerRuntime) Start(volume string) error { return nil } func (runtime DockerRuntime) Stop(volume string) error { return nil } func (runtime DockerRuntime) Remove(volume string) error { return nil }
Add debug to behat feature
<?php use Behat\Behat\Context\SnippetAcceptingContext; use Behat\Behat\Hook\Scope\BeforeScenarioScope; use Bex\Behat\Context\TestRunnerContext; class FeatureContext implements SnippetAcceptingContext { /** @var TestRunnerContext $testRunnerContext */ private $testRunnerContext; /** * @BeforeScenario */ public function gatherContexts(BeforeScenarioScope $scope) { $environment = $scope->getEnvironment(); $this->testRunnerContext = $environment->getContext('Bex\Behat\Context\TestRunnerContext'); } /** * @Given I should see the message :message */ public function iShouldSeeTheMessage($message) { $output = $this->testRunnerContext->getStandardOutputMessage() . $this->testRunnerContext->getStandardErrorMessage(); $this->assertOutputContainsMessage($output, $message); } /** * @param $message */ private function assertOutputContainsMessage($output, $message) { if (mb_strpos($output, $message) === false) { throw new RuntimeException('Behat output did not contain the given message. Output: ' . PHP_EOL . $output); } } }
<?php use Behat\Behat\Context\SnippetAcceptingContext; use Behat\Behat\Hook\Scope\BeforeScenarioScope; use Bex\Behat\Context\TestRunnerContext; class FeatureContext implements SnippetAcceptingContext { /** @var TestRunnerContext $testRunnerContext */ private $testRunnerContext; /** * @BeforeScenario */ public function gatherContexts(BeforeScenarioScope $scope) { $environment = $scope->getEnvironment(); $this->testRunnerContext = $environment->getContext('Bex\Behat\Context\TestRunnerContext'); } /** * @Given I should see the message :message */ public function iShouldSeeTheMessage($message) { $output = $this->testRunnerContext->getStandardOutputMessage() . $this->testRunnerContext->getStandardErrorMessage(); $this->assertOutputContainsMessage($output, $message); } /** * @param $message */ private function assertOutputContainsMessage($output, $message) { if (mb_strpos($output, $message) === false) { throw new RuntimeException('Behat output did not contain the given message.'); } } }
Fix Spanish noun_chunks failure caused by typo
# coding: utf8 from __future__ import unicode_literals from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .tag_map import TAG_MAP from .stop_words import STOP_WORDS from .lemmatizer import LOOKUP from .syntax_iterators import SYNTAX_ITERATORS from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class SpanishDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: 'es' lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) tag_map = TAG_MAP stop_words = STOP_WORDS syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP class Spanish(Language): lang = 'es' Defaults = SpanishDefaults __all__ = ['Spanish']
# coding: utf8 from __future__ import unicode_literals from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .tag_map import TAG_MAP from .stop_words import STOP_WORDS from .lemmatizer import LOOKUP from .syntax_iterators import SYNTAX_ITERATORS from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class SpanishDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: 'es' lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) tag_map = TAG_MAP stop_words = STOP_WORDS sytax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP class Spanish(Language): lang = 'es' Defaults = SpanishDefaults __all__ = ['Spanish']
Set up Brackets so it loads its own src code by default (if outside of appshell, it still uses hardcoded dummy data instead).
/* * Copyright 2011 Adobe Systems Incorporated. All Rights Reserved. */ // Define core brackets namespace brackets = window.brackets || {}; brackets.inBrowser = !brackets.hasOwnProperty("file"); $(document).ready(function() { var myCodeMirror = CodeMirror($('#editor').get(0), { value: 'var myResponse="Yes, it will be!"\n' }); // Load a default project into the tree if (brackets.inBrowser) { // In browser: dummy folder tree (hardcoded in ProjectManager) ProjectManager.loadProject("DummyProject"); } else { // In app shell: load Brackets itself var loadedPath = window.location.pathname; var bracketsSrc = loadedPath.substr(0, loadedPath.lastIndexOf("/")); ProjectManager.loadProject(bracketsSrc); } $("#btn-open-project").click(function() { ProjectManager.openProject(); }); // Temporary button to test file directory traversal $("#menu-file-open").click(function(){ if (!brackets.inBrowser) { window.NativeFileSystem.showOpenDialog(false, true, "Choose a folder", null, null, showOpenDialogCallback); } }); function showOpenDialogCallback( files ) { var folderName = files instanceof Array ? files[0] : files; } });
/* * Copyright 2011 Adobe Systems Incorporated. All Rights Reserved. */ // Define core brackets namespace brackets = window.brackets || {}; brackets.inBrowser = !brackets.hasOwnProperty("file"); $(document).ready(function() { var myCodeMirror = CodeMirror($('#editor').get(0), { value: 'var myResponse="Yes, it will be!"\n' }); if (brackets.inBrowser) { ProjectManager.loadProject("DummyProject"); } else { // TODO: what is default project when in app shell ?? } $("#btn-open-project").click(function() { ProjectManager.openProject(); }); // Temporary button to test file directory traversal $("#menu-file-open").click(function(){ if (!brackets.inBrowser) { window.NativeFileSystem.showOpenDialog(false, true, "Choose a folder", null, null, showOpenDialogCallback); } }); function showOpenDialogCallback( files ) { var folderName = files instanceof Array ? files[0] : files; } });
Add ignoreCache option and http option
// Includes var http = require('./http.js').func; var getVerification = require('./getVerification.js').func; var promise = require('./promise.js'); // Args exports.required = ['url', 'events']; exports.optional = ['http', 'ignoreCache', 'getBody', 'jar']; function general (jar, url, inputs, events, customOpt, body) { return function (resolve, reject) { for (var input in events) { inputs[input] = events[input]; } var httpOpt = { url: url, options: { resolveWithFullResponse: true, method: 'POST', form: inputs, jar: jar } }; if (customOpt) { if (customOpt.url) { delete customOpt.url; } Object.assign(httpOpt.options, customOpt); } http(httpOpt).then(function (res) { resolve({ res: res, body: body }); }); }; } exports.func = function (args) { var jar = args.jar; var url = args.url; var custom = args.http; return getVerification({url: custom ? (custom.url || url) : url, jar: jar, ignoreCache: args.ignoreCache, getBody: args.getBody}) .then(function (response) { return promise(general(jar, url, response.inputs, args.events, args.http, response.body)); }); };
// Includes var http = require('./http.js').func; var getVerification = require('./getVerification.js').func; var promise = require('./promise.js'); // Args exports.required = ['url', 'events']; exports.optional = ['customOpt', 'getBody', 'jar']; function general (jar, url, inputs, events, customOpt, body) { return function (resolve, reject) { for (var input in events) { inputs[input] = events[input]; } var httpOpt = { url: url, options: { resolveWithFullResponse: true, method: 'POST', form: inputs, jar: jar } }; if (customOpt) { Object.assign(httpOpt.options, customOpt); } http(httpOpt).then(function (res) { resolve({ res: res, body: body }); }); }; } exports.func = function (args) { var jar = args.jar; var url = args.url; return getVerification({url: url, jar: jar, getBody: args.getBody}) .then(function (response) { return promise(general(jar, url, response.inputs, args.events, args.http, response.body)); }); };
Set default server address to localhost Was 127.0.1.1 before
package devopsdistilled.operp.client; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import devopsdistilled.operp.client.context.AppContext; import devopsdistilled.operp.client.main.MainWindow; public class ClientApp { public static void main(String[] args) { try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { System.err .println("Nimbus Look and Feel not available.\nReverting to default"); } if (args.length > 0) System.setProperty("server.rmi.host.address", args[0]); else System.setProperty("server.rmi.host.address", "localhost"); ApplicationContext context = new AnnotationConfigApplicationContext( AppContext.class); MainWindow window = context.getBean(MainWindow.class); window.init(); System.out.println(context); } }
package devopsdistilled.operp.client; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import devopsdistilled.operp.client.context.AppContext; import devopsdistilled.operp.client.main.MainWindow; public class ClientApp { public static void main(String[] args) { try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { System.err .println("Nimbus Look and Feel not available.\nReverting to default"); } if (args.length > 0) System.setProperty("server.rmi.host.address", args[0]); else System.setProperty("server.rmi.host.address", "127.0.1.1"); ApplicationContext context = new AnnotationConfigApplicationContext( AppContext.class); MainWindow window = context.getBean(MainWindow.class); window.init(); System.out.println(context); } }
Set service query method to cache data requests.
/* global angular */ var wizardServices = angular.module('wizardServices', ['ngResource']); wizardServices.factory('Transaction', ['$resource', function ($resource) { return $resource('transactionData.json', null, { 'query': { method: 'GET', isArray: true, cache: true } }); }]); wizardServices.factory('Item', ['$resource', function ($resource) { return $resource('itemData.json', null, { 'query': { method: 'GET', isArray: true, cache: true } }); }]); wizardServices.factory('Customer', ['$resource', function ($resource) { return $resource('appData.json', null, { 'query': { method: 'GET', isArray: true, cache: true } }); }]); wizardServices.factory('State', function () { var _state = 'index'; return { get: function () { return _state; }, set: function (state) { if (state) { _state = state; } return _state; } }; });
/* global angular */ var wizardServices = angular.module('wizardServices', ['ngResource']); wizardServices.factory('Transaction', ['$resource', function ($resource) { return $resource('transactionData.json'); }]); wizardServices.factory('Item', ['$resource', function ($resource) { return $resource('itemData.json'); }]); wizardServices.factory('Customer', ['$resource', function ($resource) { return $resource('appData.json'); }]); wizardServices.factory('State', function () { var _state = 'index'; return { get: function () { return _state; }, set: function (state) { if (state) { _state = state; } return _state; } }; });
Change test circle to Castle Rock
// Initalizes map var mymap = L.map('mapid').setView([51.505, -0.09], 13); // Sets the default view of the map mymap.setView(new L.LatLng(38.1711269, -97.5383369), 5); // Sets the tile layer from Mapbox L.tileLayer('https://api.mapbox.com/styles/v1/brandonyates/cj5tvlwng020z2qr7ws0ylg1o/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoiYnJhbmRvbnlhdGVzIiwiYSI6ImNpcTl3a3AzbDAxbmhmeW0xaGYwbmIwNmQifQ.ItJcFDmazEMy-2spCUZrrA', { attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>', maxZoom: 10, id: 'mapbox.streets' }).addTo(mymap); var circle = L.circle([39.376089, -104.853487], { color: 'red', fillColor: '#f03', fillOpacity: 0.5, radius: 500 }).addTo(mymap);
// Initalizes map var mymap = L.map('mapid').setView([51.505, -0.09], 13); // Sets the default view of the map mymap.setView(new L.LatLng(38.1711269, -97.5383369), 5); // Sets the tile layer from Mapbox L.tileLayer('https://api.mapbox.com/styles/v1/brandonyates/cj5tvlwng020z2qr7ws0ylg1o/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoiYnJhbmRvbnlhdGVzIiwiYSI6ImNpcTl3a3AzbDAxbmhmeW0xaGYwbmIwNmQifQ.ItJcFDmazEMy-2spCUZrrA', { attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>', maxZoom: 10, id: 'mapbox.streets' }).addTo(mymap); var circle = L.circle([51.508, -0.11], { color: 'red', fillColor: '#f03', fillOpacity: 0.5, radius: 500 }).addTo(mymap);
ALH: Add better error interface and remove excess lines
package main import ( "fmt" "io" "log" "os" "os/exec" ) func main() { SetTmuxStatusColor("yellow") args := os.Args[1:] if len(args) == 0 { log.Fatalln("Not enough arguments") } cmd := exec.Command(args[0], args[1:]...) stdout, err := cmd.StdoutPipe() ExitIfErr(err) stderr, err := cmd.StderrPipe() ExitIfErr(err) err = cmd.Start() go io.Copy(os.Stdout, stdout) go io.Copy(os.Stderr, stderr) cmd.Wait() if cmd.ProcessState.Success() { SetTmuxStatusColor("green") } else { SetTmuxStatusColor("red") } } func SetTmuxStatusColor(color string) error { cmd := exec.Command("tmux", "set", "status-bg", color) return cmd.Run() } func ExitIfErr(err error) { if err != nil { Exit(err) } } func Exit(message interface{}) { fmt.Fprint(os.Stderr, message) os.Exit(1) }
package main import ( "fmt" "io" "log" "os" "os/exec" ) func main() { SetTmuxStatusColor("yellow") args := os.Args[1:] if len(args) == 0 { log.Fatalln("Not enough arguments") } cmd := exec.Command(args[0], args[1:]...) stdout, err := cmd.StdoutPipe() if err != nil { log.Fatalln(err) } stderr, err := cmd.StderrPipe() if err != nil { log.Fatalln(err) } err = cmd.Start() go io.Copy(os.Stdout, stdout) go io.Copy(os.Stderr, stderr) cmd.Wait() if cmd.ProcessState.Success() { fmt.Println("It finished bro") SetTmuxStatusColor("green") } else { fmt.Println("naw you didn't success it") SetTmuxStatusColor("red") } } func SetTmuxStatusColor(color string) error { cmd := exec.Command("tmux", "set", "status-bg", color) return cmd.Run() }
Fix error when saving pages.
<?php namespace VotingApp\Models; use Cviebrock\EloquentSluggable\SluggableInterface; use Cviebrock\EloquentSluggable\SluggableTrait; use Illuminate\Database\Eloquent\Model; use Parsedown; class Page extends Model implements SluggableInterface { use SluggableTrait; /** * The attributes which may be mass-assigned. * * @var array */ protected $fillable = [ 'title', 'content' ]; /** * Configuration for generating slug with Eloquent-Sluggable. * * @var array */ protected $sluggable = [ 'build_from' => 'title', 'save_to' => 'slug' ]; public function setContentAttribute($content) { $this->attributes['content'] = $content; $this->attributes['content_html'] = Parsedown::instance()->text($content); } }
<?php namespace VotingApp\Models; use Cviebrock\EloquentSluggable\SluggableInterface; use Cviebrock\EloquentSluggable\SluggableTrait; use Illuminate\Database\Eloquent\Model; class Page extends Model implements SluggableInterface { use SluggableTrait; /** * The attributes which may be mass-assigned. * * @var array */ protected $fillable = [ 'title', 'content' ]; /** * Configuration for generating slug with Eloquent-Sluggable. * * @var array */ protected $sluggable = [ 'build_from' => 'title', 'save_to' => 'slug' ]; public function setContentAttribute($content) { $this->attributes['content'] = $content; $this->attributes['content_html'] = Parsedown::instance()->text($content); } }
Add reminder to myself to to importlib fallback.
from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
Add failing test for Conn.Query
package pqx import ( "testing" ) func TestConnect(t *testing.T) { conn, err := Connect(map[string]string{"socket": "/private/tmp/.s.PGSQL.5432"}) if err != nil { t.Fatal("Unable to establish connection") } if _, present := conn.runtimeParams["server_version"]; !present { t.Error("Runtime parameters not stored") } if conn.pid == 0 { t.Error("Backend PID not stored") } if conn.secretKey == 0 { t.Error("Backend secret key not stored") } err = conn.Close() if err != nil { t.Fatal("Unable to close connection") } } func TestQuery(t *testing.T) { conn, err := Connect(map[string]string{"socket": "/private/tmp/.s.PGSQL.5432"}) if err != nil { t.Fatal("Unable to establish connection") } var rows []map[string]string rows, err = conn.Query("select 'Jack' as name") if err != nil { t.Fatal("Query failed") } if len(rows) != 1 { t.Fatal("Received wrong number of rows") } if rows[0]["name"] != "Jack" { t.Fatal("Received incorrect name") } err = conn.Close() if err != nil { t.Fatal("Unable to close connection") } }
package pqx import ( "testing" ) func TestConnect(t *testing.T) { conn, err := Connect(map[string]string{"socket": "/private/tmp/.s.PGSQL.5432"}) if err != nil { t.Fatal("Unable to establish connection") } if _, present := conn.runtimeParams["server_version"]; !present { t.Error("Runtime parameters not stored") } if conn.pid == 0 { t.Error("Backend PID not stored") } if conn.secretKey == 0 { t.Error("Backend secret key not stored") } err = conn.Close() if err != nil { t.Fatal("Unable to close connection") } } func TestQuery(t *testing.T) { conn, err := Connect(map[string]string{"socket": "/private/tmp/.s.PGSQL.5432"}) if err != nil { t.Fatal("Unable to establish connection") } // var rows []map[string]string _, err = conn.Query("SELECT * FROM people") if err != nil { t.Fatal("Query failed") } err = conn.Close() if err != nil { t.Fatal("Unable to close connection") } }
Make queenling.destroy non-writable, non-enumerable, non-configurable
if (typeof define !== 'function') { var define = require('amdefine')(module); } define(['./deferred', './tools'], function(Deferred, tools) { return { asVal: asVal, create: create }; function create(wyrmhole, mimetype, args) { var send = Deferred.fn(wyrmhole, 'sendMessage'); return send(['New', mimetype, args]).then(function(spawnId) { return tools.wrapAlienWyrmling(wyrmhole, spawnId, 0); }).then(function(queenling) { Object.defineProperty(queenling, 'destroy', { value: function() { return send(['Destroy', queenling.spawnId]); } }); return queenling; }, function(error) { console.log("CREATE ERROR:", error); return Deferred.reject(error); }); } function asVal(obj) { if (tools.isPrimitive(obj)) { return obj; } return { $type: 'json', data: obj }; } });
if (typeof define !== 'function') { var define = require('amdefine')(module); } define(['./deferred', './tools'], function(Deferred, tools) { return { asVal: asVal, create: create }; function create(wyrmhole, mimetype, args) { var send = Deferred.fn(wyrmhole, 'sendMessage'); return send(['New', mimetype, args]).then(function(spawnId) { return tools.wrapAlienWyrmling(wyrmhole, spawnId, 0); }).then(function(queenling) { queenling.destroy = function() { return send(['Destroy', queenling.spawnId]); }; return queenling; }, function(error) { console.log("CREATE ERROR:", error); return Deferred.reject(error); }); } function asVal(obj) { if (tools.isPrimitive(obj)) { return obj; } return { $type: 'json', data: obj }; } });
Fix PicoException response code bug
"""picoCTF API v1 app.""" from flask import Blueprint, jsonify from flask_restplus import Api from api.common import PicoException from .achievements import ns as achievements_ns from .problems import ns as problems_ns from .shell_servers import ns as shell_servers_ns from .exceptions import ns as exceptions_ns from .settings import ns as settings_ns from .bundles import ns as bundles_ns from .submissions import ns as submissions_ns from .feedback import ns as feedback_ns blueprint = Blueprint('v1_api', __name__) api = Api( app=blueprint, title='picoCTF API', version='1.0', ) api.add_namespace(achievements_ns) api.add_namespace(problems_ns) api.add_namespace(shell_servers_ns) api.add_namespace(exceptions_ns) api.add_namespace(settings_ns) api.add_namespace(bundles_ns) api.add_namespace(submissions_ns) api.add_namespace(feedback_ns) @api.errorhandler(PicoException) def handle_pico_exception(e): """Handle exceptions.""" response = jsonify(e.to_dict()) response.status_code = e.status_code return response
"""picoCTF API v1 app.""" from flask import Blueprint, jsonify from flask_restplus import Api from api.common import PicoException from .achievements import ns as achievements_ns from .problems import ns as problems_ns from .shell_servers import ns as shell_servers_ns from .exceptions import ns as exceptions_ns from .settings import ns as settings_ns from .bundles import ns as bundles_ns from .submissions import ns as submissions_ns from .feedback import ns as feedback_ns blueprint = Blueprint('v1_api', __name__) api = Api( app=blueprint, title='picoCTF API', version='1.0', ) api.add_namespace(achievements_ns) api.add_namespace(problems_ns) api.add_namespace(shell_servers_ns) api.add_namespace(exceptions_ns) api.add_namespace(settings_ns) api.add_namespace(bundles_ns) api.add_namespace(submissions_ns) api.add_namespace(feedback_ns) @api.errorhandler(PicoException) def handle_pico_exception(e): """Handle exceptions.""" response = jsonify(e.to_dict()) response.status_code = 203 return response
Add some fixtures for project size
<?php namespace Gitonomy\Bundle\CoreBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Gitonomy\Bundle\CoreBundle\Entity\Project; /** * Loads the fixtures for project object. * * @author Julien DIDIER <julien@jdidier.net> */ class LoadProjectData extends AbstractFixture implements OrderedFixtureInterface { /** * @inheritdoc */ public function load($manager) { $foobar = new Project(); $foobar->setName('Foobar'); $foobar->setSlug('foobar'); $foobar->setRepositorySize(256); $manager->persist($foobar); $this->setReference('project-foobar', $foobar); $barbaz = new Project(); $barbaz->setName('Barbaz'); $barbaz->setSlug('barbaz'); $barbaz->setRepositorySize(352); $manager->persist($barbaz); $this->setReference('project-barbaz', $barbaz); $manager->flush(); } /** * @inheritdoc */ public function getOrder() { return 100; } }
<?php namespace Gitonomy\Bundle\CoreBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Gitonomy\Bundle\CoreBundle\Entity\Project; /** * Loads the fixtures for project object. * * @author Julien DIDIER <julien@jdidier.net> */ class LoadProjectData extends AbstractFixture implements OrderedFixtureInterface { /** * @inheritdoc */ public function load($manager) { $foobar = new Project(); $foobar->setName('Foobar'); $foobar->setSlug('foobar'); $manager->persist($foobar); $this->setReference('project-foobar', $foobar); $barbaz = new Project(); $barbaz->setName('Barbaz'); $barbaz->setSlug('barbaz'); $manager->persist($barbaz); $this->setReference('project-barbaz', $barbaz); $manager->flush(); } /** * @inheritdoc */ public function getOrder() { return 100; } }
Add javadoc to source dao.
package edu.northwestern.bioinformatics.studycalendar.dao; import edu.northwestern.bioinformatics.studycalendar.domain.Source; import java.util.List; public class SourceDao extends StudyCalendarMutableDomainObjectDao<Source> { public Class<Source> domainClass() { return Source.class; } /** * Finds all the activity sources available * * @return a list of all the available activity sources */ public List<Source> getAll() { return getHibernateTemplate().find("from Source order by name"); } /** * Finds all the actiivty sources for the given activity source name * * @param name the name of the activity source to search for * @return the source that was found for the given activity source name */ public Source getByName(String name) { List<Source> sources = getHibernateTemplate().find("from Source where name = ?", name); if (!sources.isEmpty()) { return sources.get(0); } return null; } }
package edu.northwestern.bioinformatics.studycalendar.dao; import edu.northwestern.bioinformatics.studycalendar.domain.Source; import java.util.List; public class SourceDao extends StudyCalendarMutableDomainObjectDao<Source> { public Class<Source> domainClass() { return Source.class; } public List<Source> getAll() { return getHibernateTemplate().find("from Source order by name"); } public Source getByName(String name) { List<Source> sources = getHibernateTemplate().find("from Source where name = ?", name); if (!sources.isEmpty()) { return sources.get(0); } return null; } }
Use lazyFunctionRequire for improved import performance.
import { lazyFunctionRequire } from 'roc'; const lazyRequire = lazyFunctionRequire(require); export default { description: ` # roc-plugin-typescript A roc plugin for compiling typescript (*.ts and *.tsx) files. It uses [ts-loader](https://github.com/TypeStrong/ts-loader) for to let webpack compile typescript files and adds source maps via [source-map-loader](https://github.com/webpack/source-map-loader). ## How to use? Add the plugin as a dev dependency of your [roc](http://www.getroc.org) application: \`\`\` npm install --save-dev roc-plugin-typescript \`\`\` The plugin will automatically hook into webpacks build process and add a loader for *.ts and *.tsx files. The compiler will look for a \`tsconfig.json\` file in the root of you roc project, which you can use for configuration. `, actions: [{ hook: 'build-webpack', description: 'Adds typescript support to Webpack.', action: lazyRequire('../webpack'), }], required: { 'roc-package-webpack': '^1.0.0-beta.1', }, };
import webpack from '../webpack'; export default { description: ` # roc-plugin-typescript A roc plugin for compiling typescript (*.ts and *.tsx) files. It uses [ts-loader](https://github.com/TypeStrong/ts-loader) for to let webpack compile typescript files and adds source maps via [source-map-loader](https://github.com/webpack/source-map-loader). ## How to use? Add the plugin as a dev dependency of your [roc](http://www.getroc.org) application: \`\`\` npm install --save-dev roc-plugin-typescript \`\`\` The plugin will automatically hook into webpacks build process and add a loader for *.ts and *.tsx files. The compiler will look for a \`tsconfig.json\` file in the root of you roc project, which you can use for configuration. `, actions: [{ hook: 'build-webpack', description: 'Adds typescript support to Webpack.', action: webpack, }], required: { 'roc-package-webpack': '^1.0.0-beta.1', }, };
Change getColumnIndex method to be private
/* * Copyright 2016 Martin Kamp Jensen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.mkjensen.dml.test; import static org.junit.Assert.assertFalse; import android.database.Cursor; /** * Helper methods for working with {@link Cursor}. */ public final class CursorUtils { private CursorUtils() { } /** * Delegates to {@link Cursor#getString(int)}, using {@link #getColumnIndex(Cursor, String)} to * get the column index for the specified column name. */ public static String getString(Cursor cursor, String columnName) { int columnIndex = getColumnIndex(cursor, columnName); return cursor.getString(columnIndex); } private static int getColumnIndex(Cursor cursor, String columnName) { int columnIndex = cursor.getColumnIndex(columnName); assertFalse(columnIndex == -1); return columnIndex; } }
/* * Copyright 2016 Martin Kamp Jensen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.mkjensen.dml.test; import static org.junit.Assert.assertFalse; import android.database.Cursor; /** * Helper methods for working with {@link Cursor}. */ public final class CursorUtils { private CursorUtils() { } /** * Delegates to {@link Cursor#getColumnIndex(String)}. Also asserts that the returned index is not * {@code -1}. */ public static int getColumnIndex(Cursor cursor, String columnName) { int columnIndex = cursor.getColumnIndex(columnName); assertFalse(columnIndex == -1); return columnIndex; } /** * Delegates to {@link Cursor#getString(int)}, using {@link #getColumnIndex(Cursor, String)} to * get the column index for the specified column name. */ public static String getString(Cursor cursor, String columnName) { int columnIndex = getColumnIndex(cursor, columnName); return cursor.getString(columnIndex); } }
Add method to get admin users.
module.exports = function(r) { 'use strict'; return { allByProject: allByProject, adminUsers: adminUsers, }; function allByProject() { return r.table('access').run().then(function(allAccess) { let byProject = {}; allAccess.forEach(function(a) { if (!(a.project_id in byProject)) { byProject[a.project_id] = []; } byProject[a.project_id].push(a); }); return byProject; }); } function adminUsers() { return r.table('users').filter({admin: true}).run(); } };
module.exports = function(r) { 'use strict'; return { allByProject: allByProject }; function allByProject() { return r.table('access').run().then(function(allAccess) { let byProject = {}; allAccess.forEach(function(a) { if (!(a.project_id in byProject)) { byProject[a.project_id] = []; } byProject[a.project_id].push(a); }); return byProject; }); } };
Update some information for pypi package
from setuptools import setup files = ["journal_files/*"] readme = open('README.md','r') README_TEXT = readme.read() readme.close() setup( name="journalabbrev", version="0.1.1", packages=["journalabbrev"], scripts=["bin/journalabbrev"], long_description = README_TEXT, install_requires=["bibtexparser"], data_files=[ ("/opt/journalabbreviation/", ["static/db_abbrev.json"]) ], licencse="GPL-3.0", description="Abbreviates journal names inside in a given bibtex file", author="Bruno Messias", author_email="contato@brunomessias.com", download_url="https://github.com/devmessias/journalabbrev/archive/0.1.1.tar.gz", keywords=["bibtex", "abbreviate", "science","scientific-journals"], classifiers=[ 'Intended Audience :: Science/Research', 'Programming Language :: Python', 'Topic :: Text Processing :: Markup :: LaTeX', ], url="https://github.com/devmessias/journalabbrev" )
from setuptools import setup files = ["journal_files/*"] readme = open('README.md','r') README_TEXT = readme.read() readme.close() setup( name="journalabbrev", version="0.1.1", packages=["journalabbrev"], scripts=["bin/journalabbrev"], long_description = README_TEXT, install_requires=["bibtexparser"], data_files=[ ("/opt/journalabbreviation/", ["static/db_abbrev.json"]) ], licencse="GPL-3.0", description="Abbreviates journal names inside in a given bibtex file", author="Bruno Messias", author_email="contato@brunomessias.com", download_url="https://github.com/devmessias/journalabbrev/archive/0.1.tar.gz", keywords=["bibtex", "abbreviate", "science","scientific-journals"], classifiers=[ 'Intended Audience :: Science/Research', 'Programming Language :: Python', 'Topic :: Text Processing :: Markup :: LaTeX', ], url="https://github.com/devmessias/journalabbrev" )
Add documentation for the hash function.
'''Module to solve the algoritm question: Given a string S, how to count how many permutations of S is in a longer string L, assuming, of course, that permutations of S must be in contagious blocks in L. I will solve it in O(len(L)) time. For demonstration purpose, let's assume the characters are ASCII lowercase letters only. ''' # Q: given a character, how to convert it into its # ASCII value? A: using ord() and chr() SHIFT = ord('a') def char_to_int(char): '''convert char in a-z to 0-25 ''' # TODO: range check return ord(char) - SHIFT def int_to_char(num): '''convert num in 0-25 to a-z ''' # TODO: range check return chr(num + SHIFT) def string_permu_hash(in_str): '''hash a string based on the numbers of each char in the string. So 2 permutations of a string give the same hash. You can decompose this hash to get back the number of each char. ''' base = len(in_str) + 1 hash_result = 0 for c in in_str: hash_result += base ** char_to_int(c) return hash_result
'''Module to solve the algoritm question: Given a string S, how to count how many permutations of S is in a longer string L, assuming, of course, that permutations of S must be in contagious blocks in L. I will solve it in O(len(L)) time. For demonstration purpose, let's assume the characters are ASCII lowercase letters only. ''' # Q: given a character, how to convert it into its # ASCII value? A: using ord() and chr() SHIFT = ord('a') def char_to_int(char): '''convert char in a-z to 0-25 ''' # TODO: range check return ord(char) - SHIFT def int_to_char(num): '''convert num in 0-25 to a-z ''' # TODO: range check return chr(num + SHIFT) def string_permu_hash(in_str): base = len(in_str) + 1 hash_result = 0 for c in in_str: hash_result += base ** char_to_int(c) return hash_result
Add imports for type hints
<?php /* * This file is part of the Silex framework. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Silex\Provider\Routing; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Matcher\RequestMatcherInterface; use Symfony\Component\Routing\Matcher\UrlMatcherInterface; /** * Implements a lazy UrlMatcher. * * @author Igor Wiedler <igor@wiedler.ch> * @author Jérôme Tamarelle <jerome@tamarelle.net> */ class LazyRequestMatcher implements RequestMatcherInterface { private $factory; public function __construct(\Closure $factory) { $this->factory = $factory; } /** * Returns the corresponding RequestMatcherInterface instance. * * @return UrlMatcherInterface */ public function getRequestMatcher() { $matcher = call_user_func($this->factory); if (!$matcher instanceof RequestMatcherInterface) { throw new \LogicException("Factory supplied to LazyRequestMatcher must return implementation of Symfony\Component\Routing\RequestMatcherInterface."); } return $matcher; } /** * {@inheritdoc} */ public function matchRequest(Request $request) { return $this->getRequestMatcher()->matchRequest($request); } }
<?php /* * This file is part of the Silex framework. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Silex\Provider\Routing; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Matcher\RequestMatcherInterface; /** * Implements a lazy UrlMatcher. * * @author Igor Wiedler <igor@wiedler.ch> * @author Jérôme Tamarelle <jerome@tamarelle.net> */ class LazyRequestMatcher implements RequestMatcherInterface { private $factory; public function __construct(\Closure $factory) { $this->factory = $factory; } /** * Returns the corresponding RequestMatcherInterface instance. * * @return UrlMatcherInterface */ public function getRequestMatcher() { $matcher = call_user_func($this->factory); if (!$matcher instanceof RequestMatcherInterface) { throw new \LogicException("Factory supplied to LazyRequestMatcher must return implementation of Symfony\Component\Routing\RequestMatcherInterface."); } return $matcher; } /** * {@inheritdoc} */ public function matchRequest(Request $request) { return $this->getRequestMatcher()->matchRequest($request); } }
Set return_url when logging in users
define(function () { var App = Ember.Application.create() , isDev = /localhost/.test(document.location.href) , tokenRegexp = /authentication_token=([a-zA-Z0-9]+)/; /* Resolve authentication. Removes authentication token from URL to put it in a cookie. */ if (tokenRegexp.test(document.location.href)) { var token = document.location.href.match(tokenRegexp) , cookie; cookie = 'authentication_token=' + token[1]; cookie += '; expires=' + new Date(2100, 0).toUTCString(); document.cookie = cookie; document.location.href = document.location.href.replace(tokenRegexp, ''); return; } else if(tokenRegexp.test(document.cookie)) { App.AUTH_TOKEN = document.cookie.match(tokenRegexp)[1]; } /* Calculate host based on current URL. If the URL includes a `localhost` substring, then we're in a development environment. */ if (isDev) { App.API_HOST = 'http://localhost:5000'; } else { App.API_HOST = 'http://t2api.herokuapp.com'; } App.API_BASE_URL = App.API_HOST + '/api/v1'; App.SIGN_IN_URL = App.API_HOST + '/sign_in?return_url=' + escape(location.href); App.NAVBAR_URL = App.API_HOST + '/navbar'; window.App = App; return App; });
define(function () { var App = Ember.Application.create() , isDev = /localhost/.test(document.location.href) , tokenRegexp = /authentication_token=([a-zA-Z0-9]+)/; /* Resolve authentication. Removes authentication token from URL to put it in a cookie. */ if (tokenRegexp.test(document.location.href)) { var token = document.location.href.match(tokenRegexp) , cookie; cookie = 'authentication_token=' + token[1]; cookie += '; expires=' + new Date(2100, 0).toUTCString(); document.cookie = cookie; document.location.href = document.location.href.replace(tokenRegexp, ''); return; } else if(tokenRegexp.test(document.cookie)) { App.AUTH_TOKEN = document.cookie.match(tokenRegexp)[1]; } /* Calculate host based on current URL. If the URL includes a `localhost` substring, then we're in a development environment. */ if (isDev) { App.API_HOST = 'http://localhost:5000'; } else { App.API_HOST = 'http://t2api.herokuapp.com'; } App.API_BASE_URL = App.API_HOST + '/api/v1'; App.SIGN_IN_URL = App.API_HOST + '/sign_in'; App.NAVBAR_URL = App.API_HOST + '/navbar'; window.App = App; return App; });
Set modelId data attribute for feeds
var HTML = { createFeed: function(data) { var $clone = $('.template.feed').clone(true); $clone.data('modelId', data.id); $clone.removeClass('template'); $clone.find('.title').text(data.title); $clone.find('.url').attr('href', data.url).text(data.url); return $clone; }, createEntry: function(data) { var $clone = $('.template.news').clone(true); $clone.removeClass('template'); $clone.find('.title').text(data.title); $clone.find('.url').attr('href', data.url).text(data.url); return $clone; }, createTag: function(data) { var $clone = $('.template.tag').clone(true); $clone.removeClass('template'); $clone.find('.title').text(data.title); $clone.find('.badge').text(data.entry_count); return $clone; } };
var HTML = { createFeed: function(data) { var $clone = $('.template.feed').clone(true); $clone.removeClass('template'); $clone.find('.title').text(data.title); $clone.find('.url').attr('href', data.url).text(data.url); return $clone; }, createEntry: function(data) { var $clone = $('.template.news').clone(true); $clone.removeClass('template'); $clone.find('.title').text(data.title); $clone.find('.url').attr('href', data.url).text(data.url); return $clone; }, createTag: function(data) { var $clone = $('.template.tag').clone(true); $clone.removeClass('template'); $clone.find('.title').text(data.title); $clone.find('.badge').text(data.entry_count); return $clone; } };
Add country to admin layers filtering This was missing, which would cause countries to get all admin layers.
/* Look up which admin fields should be populated for a record in a given layer. * * The logic is: look up eveything above in the WOF heirarchy, ignoring things like * 'dependency' * * Note: this filtering really only matters for geonames currently, since OSM and OA * consist entirely of venue and address records, which should have all fields * looked up. WOF documents use the actual WOF heirarchy to fill in admin values, * so they also won't be affected by this. */ function getAdminLayers(layer) { switch (layer) { case 'country': return ['country']; case 'region': return ['country', 'macroregion', 'region']; case 'county': return ['country', 'macroregion', 'region', 'macrocounty', 'county']; case 'locality': return ['country', 'macroregion', 'region', 'macrocounty', 'county', 'locality']; default: return undefined;//undefined means use all layers as normal } } module.exports = getAdminLayers;
/* Look up which admin fields should be populated for a record in a given layer. * * The logic is: look up eveything above in the WOF heirarchy, ignoring things like * 'dependency' * * Note: this filtering really only matters for geonames currently, since OSM and OA * consist entirely of venue and address records, which should have all fields * looked up. WOF documents use the actual WOF heirarchy to fill in admin values, * so they also won't be affected by this. */ function getAdminLayers(layer) { switch (layer) { case 'region': return ['country', 'macroregion', 'region']; case 'county': return ['country', 'macroregion', 'region', 'macrocounty', 'county']; case 'locality': return ['country', 'macroregion', 'region', 'macrocounty', 'county', 'locality']; default: return undefined;//undefined means use all layers as normal } } module.exports = getAdminLayers;
Add Migrations Plugin to bootrap_cli.php Ref: https://github.com/cakephp/app/issues/452 Note: 2 PRs cause quick via GH. While I like it to be optional, should it be outside the try block instead?
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 3.0.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ use Cake\Core\Configure; use Cake\Core\Exception\MissingPluginException; use Cake\Core\Plugin; /** * Additional bootstrapping and configuration for CLI environments should * be put here. */ // Set the fullBaseUrl to allow URLs to be generated in shell tasks. // This is useful when sending email from shells. //Configure::write('App.fullBaseUrl', php_uname('n')); // Set logs to different files so they don't have permission conflicts. Configure::write('Log.debug.file', 'cli-debug'); Configure::write('Log.error.file', 'cli-error'); try { Plugin::load('Migrations'); Plugin::load('Bake'); } catch (MissingPluginException $e) { // Do not halt if the plugin is missing }
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 3.0.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ use Cake\Core\Configure; use Cake\Core\Exception\MissingPluginException; use Cake\Core\Plugin; /** * Additional bootstrapping and configuration for CLI environments should * be put here. */ // Set the fullBaseUrl to allow URLs to be generated in shell tasks. // This is useful when sending email from shells. //Configure::write('App.fullBaseUrl', php_uname('n')); // Set logs to different files so they don't have permission conflicts. Configure::write('Log.debug.file', 'cli-debug'); Configure::write('Log.error.file', 'cli-error'); try { Plugin::load('Bake'); } catch (MissingPluginException $e) { // Do not halt if the plugin is missing }
Fix for incorrect project url
from distutils.core import setup from dyn import __version__ with open('README.rst') as f: readme = f.read() with open('HISTORY.rst') as f: history = f.read() setup( name='dyn', version=__version__, keywords=['dyn', 'api', 'dns', 'email', 'dyndns', 'dynemail'], long_description='\n\n'.join([readme, history]), description='Dyn REST API wrapper', author='Jonathan Nappi, Cole Tuininga', author_email='jnappi@dyn.com', url='https://github.com/moogar0880/dyn-python', packages=['dyn', 'dyn/tm', 'dyn/mm', 'dyn/tm/services'], classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Internet :: Name Service (DNS)', 'Topic :: Software Development :: Libraries', ], )
from distutils.core import setup from dyn import __version__ with open('README.rst') as f: readme = f.read() with open('HISTORY.rst') as f: history = f.read() setup( name='dyn', version=__version__, keywords=['dyn', 'api', 'dns', 'email', 'dyndns', 'dynemail'], long_description='\n\n'.join([readme, history]), description='Dyn REST API wrapper', author='Jonathan Nappi, Cole Tuininga', author_email='jnappi@dyn.com', url='https://github.com/dyninc/Dynect-API-Python-Library', packages=['dyn', 'dyn/tm', 'dyn/mm', 'dyn/tm/services'], classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Internet :: Name Service (DNS)', 'Topic :: Software Development :: Libraries', ], )
Make routedViewListMixin smarter, use pop routes rather than goBack
var { State, Navigation } = require('react-router'); var RouteHandler = require('react-router/modules/mixins/RouteHandler'); // mixin for viewlists // works with react-router and gives some helper functions // to manage viewLists module.exports = { mixins: [ State, RouteHandler, Navigation, ], routedViewListProps() { return { scrollToStep: this.scrollToStep(), onViewEntered: this._handleViewEntered }; }, scrollToStep() { return this.numActiveRoutes() - this.getRouteDepth(); }, routedSubRoute() { return this.hasChildRoute() && ( this.getRouteHandler(Object.assign(this.props, { key: this.subRouteKey() })) ); }, // todo: debug why this is called more than it should be _handleViewEntered(i) { if (i === 0 && this.numActiveRoutes() > this.getRouteDepth()) { var r = this.getRoutes().reverse(); r.shift(); this.transitionTo(r[0].path); } }, numActiveRoutes() { return this.getRoutes().length; }, hasChildRoute() { return this.numActiveRoutes() > this.getRouteDepth(); }, subRouteKey() { return this.getRoutes().reverse()[0].name + this.getParams().id; } };
var { State, Navigation } = require('react-router'); var RouteHandler = require('react-router/modules/mixins/RouteHandler'); // mixin for viewlists // works with react-router and gives some helper functions // to manage viewLists module.exports = { mixins: [ State, RouteHandler, Navigation, ], routedViewListProps() { return { scrollToStep: this.scrollToStep(), onViewEntered: this._handleViewEntered }; }, scrollToStep() { return this.numActiveRoutes() - this.getRouteDepth(); }, routedSubRoute() { return this.hasChildRoute() && ( this.getRouteHandler(Object.assign(this.props, { key: this.subRouteKey() })) ); }, // todo: debug why this is called more than it should be _handleViewEntered(i) { if (i === 0 && this.numActiveRoutes() > this.getRouteDepth()) setTimeout(this.goBack, 1); }, numActiveRoutes() { return this.getRoutes().length; }, hasChildRoute() { return this.numActiveRoutes() > this.getRouteDepth(); }, subRouteKey() { return this.getRoutes().reverse()[0].name + this.getParams().id; } };
Move to 100% of Testing Code Coverage for Isbn::CheckDigit
<?php class CheckDigitTest extends PHPUnit_Framework_TestCase { public function testIsbn10() { $this->assertEquals('8', Isbn\CheckDigit::make10('888183718')); $this->assertEquals('8', Isbn\CheckDigit::make10('8881837188')); } public function testIsbn13() { $this->assertEquals('1', Isbn\CheckDigit::make13('978888952719')); $this->assertEquals('1', Isbn\CheckDigit::make13('9788889527191')); } public function testIsbn() { $this->assertEquals('8', Isbn\CheckDigit::make('888183718')); $this->assertEquals('1', Isbn\CheckDigit::make('978888952719')); $this->assertFalse(Isbn\CheckDigit::make('97888895271921')); } }
<?php class CheckDigitTest extends PHPUnit_Framework_TestCase { public function testIsbn10() { $this->assertEquals('8', Isbn\CheckDigit::make10('888183718')); $this->assertEquals('8', Isbn\CheckDigit::make10('8881837188')); } public function testIsbn13() { $this->assertEquals('1', Isbn\CheckDigit::make13('978888952719')); $this->assertEquals('1', Isbn\CheckDigit::make13('9788889527191')); } public function testIsbn() { $this->assertEquals('8', Isbn\CheckDigit::make('888183718')); $this->assertEquals('1', Isbn\CheckDigit::make('978888952719')); } }
Fix columns not to be converted into str
from .parts import Column def BETWEEN(expr1, expr2, expr3): return Column('%s BETWEEN %s AND %s' % (_actual_n(expr1), _actual_n(expr2), _actual_n(expr3))) def CAST(type1, type2): return Column('CAST(%s AS %s)' % (type1, type2)) def CONCAT(*args): arg = [_actual_n(a) for a in args] arg = ', '.join(arg) return Column('CONCAT(%s)' % arg) def CONTAINS(exp, search_str): return Column('%s CONTAINS %s' % (_actual_n(exp), _actual_n(search_str))) def IN(search_expr, *expr): return Column('%s IN(%s)' % (_actual_n(search_expr), ', '.join(_actual_n(x) for x in expr))) def IS_NULL(expr): return Column('%s IS NULL' % _actual_n(expr)) def _fn_factory(name): def _fn(*col): return Column('{0}({1})'.format(name, ','.join(_actual_n(x) for x in col))) return _fn def _actual_n(col): if isinstance(col, str): return "'%s'" % col elif isinstance(col, Column): return str(col.real_name) else: return str(col)
from .parts import Column def BETWEEN(expr1, expr2, expr3): return Column('%s BETWEEN %s AND %s' % (_actual_n(expr1), _actual_n(expr2), _actual_n(expr3))) def CAST(type1, type2): return Column('CAST(%s AS %s)' % (type1, type2)) def CONCAT(*args): arg = [_actual_n(a) for a in args] arg = ', '.join(arg) return Column('CONCAT(%s)' % arg) def CONTAINS(exp, search_str): return Column('%s CONTAINS %s' % (_actual_n(exp), _actual_n(search_str))) def IN(search_expr, *expr): return Column('%s IN(%s)' % (_actual_n(search_expr), ', '.join(_actual_n(x) for x in expr))) def IS_NULL(expr): return Column('%s IS NULL' % _actual_n(expr)) def _fn_factory(name): def _fn(*col): return Column('{0}({1})'.format(name, ','.join(_actual_n(x) for x in col))) return _fn def _actual_n(col): if isinstance(col, str): return "'%s'" % col elif isinstance(col, Column): return col.real_name else: return str(col)
Use argv0 instead of node (for Travis CI)
const path = require("path"); const rootDir = path.normalize(path.join(__dirname, "..")); const tester = path.join(rootDir, "node_modules", "vscode", "bin", "test"); const cp = require("child_process"); let tests = process.argv.slice(2); let failed = 0; tests.forEach((test) => { let [ testName, wsName ] = test.split("@", 2); if (wsName == null) { wsName = testName; } let testRoot = path.join(rootDir, "out", "test", testName); let workspace = path.join(rootDir, "test", "workspace", wsName); console.log("#".repeat(100)); console.log(`# [${test}] Started at ${new Date().toString()}`); console.log(""); let result = cp.spawnSync(process.argv0, [tester], { env: { CODE_TESTS_PATH: testRoot, CODE_TESTS_WORKSPACE: workspace }, stdio: "inherit" }); console.log(`# [${test}] Finished at ${new Date().toString()} (result=${result.status})`); if (result.status !== 0) { console.error(`# ${result.error}`); ++failed; } console.log(""); }); if (failed > 0) { process.exitCode = 1; }
const path = require("path"); const rootDir = path.normalize(path.join(__dirname, "..")); const tester = path.join(rootDir, "node_modules", "vscode", "bin", "test"); const cp = require("child_process"); let tests = process.argv.slice(2); let failed = 0; tests.forEach((test) => { let [ testName, wsName ] = test.split("@", 2); if (wsName == null) { wsName = testName; } let testRoot = path.join(rootDir, "out", "test", testName); let workspace = path.join(rootDir, "test", "workspace", wsName); console.log("#".repeat(100)); console.log(`# [${test}] Started at ${new Date().toString()}`); console.log(""); let result = cp.spawnSync("node", [tester], { env: { CODE_TESTS_PATH: testRoot, CODE_TESTS_WORKSPACE: workspace }, stdio: "inherit" }); console.log(`# [${test}] Finished at ${new Date().toString()} (result=${result.status})`); if (result.status !== 0) { console.error(`${result.error}`); ++failed; } console.log(""); }); if (failed > 0) { process.exitCode = 1; }
Replace hardcoded packages by find_packages
# -*- encoding: utf-8 -*- from setuptools import find_packages, setup description = """ Simple, powerfull and nonobstructive django email middleware. """ setup( name="djmail", url="https://github.com/niwibe/djmail", author="Andrey Antukh", author_email="niwi@niwi.be", version="0.8", packages=find_packages(include=['djmail*']), description=description.strip(), zip_safe=False, include_package_data=True, package_data={ "": ["*.html"], }, classifiers=[ # "Development Status :: 5 - Production/Stable", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Environment :: Web Environment", "Framework :: Django", "License :: OSI Approved :: BSD License", "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Topic :: Software Development :: Libraries", "Topic :: Utilities", ], )
# -*- encoding: utf-8 -*- from setuptools import setup description = """ Simple, powerfull and nonobstructive django email middleware. """ setup( name="djmail", url="https://github.com/niwibe/djmail", author="Andrey Antukh", author_email="niwi@niwi.be", version="0.8", packages=[ "djmail", "djmail.backends", "djmail.management", "djmail.management.commands", ], description=description.strip(), zip_safe=False, include_package_data=True, package_data={ "": ["*.html"], }, classifiers=[ # "Development Status :: 5 - Production/Stable", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Environment :: Web Environment", "Framework :: Django", "License :: OSI Approved :: BSD License", "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Topic :: Software Development :: Libraries", "Topic :: Utilities", ], )
Install the data files correctly too.
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup import glob from spec_cleaner import __version__ test_requires = [ 'mock', 'nose', ] setup( name='spec_cleaner', description = 'RPM .spec files cleaner', long_description = 'Command-line tool for cleaning various formatting' + 'errors in RPM .spec files', url = 'https://github.com/openSUSE/spec-cleaner', download_url = 'https://github.com/openSUSE/spec-cleaner', version = __version__, author = 'Tomáš Chvátal', author_email = 'tchvatal@suse.cz', maintainer = 'Tomáš Chvátal', maintainer_email = 'tchvatal@suse.cz', license = 'License :: OSI Approved :: BSD License', platforms = ['Linux'], keywords = ['SUSE', 'RPM', '.spec', 'cleaner'], tests_require=test_requires, test_suite="nose.collector", packages = ['spec_cleaner'], data_files=[('/usr/libexec/obs/service/', glob.glob('obs/*')), ('/usr/share/spec-cleaner/', glob.glob('data/*')), ], entry_points = { 'console_scripts': ['spec-cleaner = spec_cleaner.main:main']}, )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup import glob from spec_cleaner import __version__ test_requires = [ 'mock', 'nose', ] setup( name='spec_cleaner', description = 'RPM .spec files cleaner', long_description = 'Command-line tool for cleaning various formatting' + 'errors in RPM .spec files', url = 'https://github.com/openSUSE/spec-cleaner', download_url = 'https://github.com/openSUSE/spec-cleaner', version = __version__, author = 'Tomáš Chvátal', author_email = 'tchvatal@suse.cz', maintainer = 'Tomáš Chvátal', maintainer_email = 'tchvatal@suse.cz', license = 'License :: OSI Approved :: BSD License', platforms = ['Linux'], keywords = ['SUSE', 'RPM', '.spec', 'cleaner'], tests_require=test_requires, test_suite="nose.collector", packages = ['spec_cleaner'], package_data = {'spec_cleaner' : [ "data/*.txt" ]}, data_files=[('/usr/libexec/obs/service/', glob.glob('obs/*'))], entry_points = { 'console_scripts': ['spec-cleaner = spec_cleaner.main:main']}, )
Add declare strict type in interface where string typehint is used
<?php declare(strict_types=1); namespace Smartbox\Integration\FrameworkBundle\Components\Queues\Drivers; use Smartbox\Integration\FrameworkBundle\Components\Queues\QueueMessageInterface; interface SyncQueueDriverInterface extends QueueDriverInterface { /** * Returns true if a subscription already exists, false otherwise. * * @return bool */ public function isSubscribed(); /** * Creates a subscription to the given $queue, allowing to receive messages from it. * * @param string $queue Queue to subscribe */ public function subscribe(string $queue); /** * Destroys the created subscription with a queue. */ public function unSubscribe(); /** * Returns One Serializable object from the queue. * * It requires to subscribe previously to a specific queue * * @return QueueMessageInterface|null */ public function receive(); /** * Clean all the opened resources, must be called just before terminating the current request. */ public function destroy(); }
<?php namespace Smartbox\Integration\FrameworkBundle\Components\Queues\Drivers; use Smartbox\Integration\FrameworkBundle\Components\Queues\QueueMessageInterface; interface SyncQueueDriverInterface extends QueueDriverInterface { /** * Returns true if a subscription already exists, false otherwise. * * @return bool */ public function isSubscribed(); /** * Creates a subscription to the given $queue, allowing to receive messages from it. * * @param string $queue Queue to subscribe */ public function subscribe(string $queue); /** * Destroys the created subscription with a queue. */ public function unSubscribe(); /** * Returns One Serializable object from the queue. * * It requires to subscribe previously to a specific queue * * @return QueueMessageInterface|null * * @throws \Exception */ public function receive(); /** * Clean all the opened resources, must be called just before terminating the current request. */ public function destroy(); }
Add missing arg test to Systemd Provider Get
package systemd_test import ( "fmt" "github.com/mistifyio/mistify/acomm" "github.com/mistifyio/mistify/providers/systemd" ) func (s *sd) TestGet() { tests := []struct { name string err string }{ {"", "missing arg: name"}, {"doesnotexist.service", "unit not found"}, {"dbus.service", ""}, } for _, test := range tests { args := &systemd.GetArgs{test.name} argsS := fmt.Sprintf("%+v", test) req, err := acomm.NewRequest("zfs-exists", "unix:///tmp/foobar", "", args, nil, nil) s.Require().NoError(err, argsS) res, streamURL, err := s.systemd.Get(req) s.Nil(streamURL, argsS) if test.err == "" { if !s.NoError(err, argsS) { continue } result, ok := res.(*systemd.GetResult) if !s.True(ok, argsS) { continue } if !s.NotNil(result.Unit, argsS) { continue } s.Equal(test.name, result.Unit.Name, argsS) } else { s.EqualError(err, test.err, argsS) } } }
package systemd_test import ( "fmt" "github.com/mistifyio/mistify/acomm" "github.com/mistifyio/mistify/providers/systemd" ) func (s *sd) TestGet() { tests := []struct { name string err string }{ {"dbus.service", ""}, {"doesnotexist.service", "unit not found"}, } for _, test := range tests { args := &systemd.GetArgs{test.name} argsS := fmt.Sprintf("%+v", test) req, err := acomm.NewRequest("zfs-exists", "unix:///tmp/foobar", "", args, nil, nil) s.Require().NoError(err, argsS) res, streamURL, err := s.systemd.Get(req) s.Nil(streamURL, argsS) if test.err == "" { if !s.NoError(err, argsS) { continue } result, ok := res.(*systemd.GetResult) if !s.True(ok, argsS) { continue } if !s.NotNil(result.Unit, argsS) { continue } s.Equal(test.name, result.Unit.Name, argsS) } else { s.EqualError(err, test.err, argsS) } } }
Refactor parse args db options
import os import argparse def default_db(): return os.path.join(os.path.expanduser("~"), "~/.pysswords") def parse_args(args): parser = argparse.ArgumentParser(prog="Pysswords") group_db = parser.add_argument_group("Databse options") group_db.add_argument("-I", "--init", action="store_true") group_db.add_argument("-D", "--database", default=default_db()) group_cred = parser.add_argument_group("Credential options") group_cred.add_argument("-a", "--add", action="store_true") group_cred.add_argument("-g", "--get") group_cred.add_argument("-u", "--update") group_cred.add_argument("-r", "--remove") group_cred.add_argument("-s", "--search") return parser.parse_args(args)
import os import argparse def default_db(): return os.path.join(os.path.expanduser("~"), "~/.pysswords") def parse_args(args): parser = argparse.ArgumentParser(prog="Pysswords") group_init = parser.add_argument_group("Init options") group_init.add_argument("-I", "--init", action="store_true") group_init.add_argument("-D", "--database", default=default_db()) group_cred = parser.add_argument_group("Credential options") group_cred.add_argument("-a", "--add", action="store_true") group_cred.add_argument("-g", "--get") group_cred.add_argument("-u", "--update") group_cred.add_argument("-r", "--remove") group_cred.add_argument("-s", "--search") return parser.parse_args(args)
Move database to its own folder.
const Datastore = require('nedb') const path = require('path') const databasePath = path.join(require('os').homedir(), '.zazu/databases/track.nedb') const database = new Datastore({ filename: databasePath, autoload: true, }) let clickedResults = [] database.find({}).exec((err, docs) => { if (!err) { clickedResults = docs } }) class ResultSorter { constructor (results) { this.results = results } sort () { return this.results.map((result) => { result.score = clickedResults.reduce((memo, clickedResult) => { if (clickedResult.id === result.id) memo++ return memo }, 0) return result }).sort((a, b) => { if (a.score < b.score) return 1 if (a.score > b.score) return -1 return 0 }) } static trackClick (doc) { const clickedResult = Object.assign({}, { createdAt: new Date(), }, doc) window.newrelic.addPageAction('clickedResult', { pluginName: doc.pluginName, }) clickedResults.push(clickedResult) return new Promise((resolve, reject) => { database.insert(clickedResult, (err) => { err ? reject(err) : resolve() }) }) } } module.exports = ResultSorter
const Datastore = require('nedb') const path = require('path') const databasePath = path.join(require('os').homedir(), '.zazu/track.nedb') const database = new Datastore({ filename: databasePath, autoload: true, }) let clickedResults = [] database.find({}).exec((err, docs) => { if (!err) { clickedResults = docs } }) class ResultSorter { constructor (results) { this.results = results } sort () { return this.results.map((result) => { result.score = clickedResults.reduce((memo, clickedResult) => { if (clickedResult.id === result.id) memo++ return memo }, 0) return result }).sort((a, b) => { if (a.score < b.score) return 1 if (a.score > b.score) return -1 return 0 }) } static trackClick (doc) { const clickedResult = Object.assign({}, { createdAt: new Date(), }, doc) window.newrelic.addPageAction('clickedResult', { pluginName: doc.pluginName, }) clickedResults.push(clickedResult) return new Promise((resolve, reject) => { database.insert(clickedResult, (err) => { err ? reject(err) : resolve() }) }) } } module.exports = ResultSorter
Add missing select_related to badgify_badges
# -*- coding: utf-8 -*- from django import template from ..models import Badge, Award from ..compat import get_user_model register = template.Library() @register.assignment_tag def badgify_badges(**kwargs): """ Returns all badges or only awarded badges for the given user. """ User = get_user_model() user = kwargs.get('user', None) username = kwargs.get('username', None) if username: try: user = User.objects.get(username=username) except User.DoesNotExist: pass if user: awards = Award.objects.filter(user=user).select_related('badge') badges = [award.badge for award in awards] return badges return Badge.objects.all()
# -*- coding: utf-8 -*- from django import template from ..models import Badge, Award from ..compat import get_user_model register = template.Library() @register.assignment_tag def badgify_badges(**kwargs): """ Returns all badges or only awarded badges for the given user. """ User = get_user_model() user = kwargs.get('user', None) username = kwargs.get('username', None) if username: try: user = User.objects.get(username=username) except User.DoesNotExist: pass if user: awards = Award.objects.filter(user=user) badges = [award.badge for award in awards] return badges return Badge.objects.all()
Move arguments to sub parsers
import argparse from . import commands def create_options(): "Add options to tornado" parser = argparse.ArgumentParser( 'Staitrator - Static multilingual site and blog generator') sub_parsers = parser.add_subparsers(help='Sub Commands help') init = sub_parsers.add_parser('init', help='Initiate a new site') init.add_argument('directory', help='Target directory') init.add_argument('-n', '--name', default='Default site', help='Site name and title [default: %(default)s]') init.add_argument('-c', '--site_class', default='statirator.site.Html5Site', help='The base class for the site [default: %(default)s]') init.add_argument('-s', '--source', default='source', help="Site's source directory [default: %(default)s]") init.add_argument('-b', '--build', default='build', help="Site's build directory [default: %(default)s]") cmpl = sub_parsers.add_parser('compile', help='Compile the new site') serve = sub_parsers.add_parser('serve', help='Serve the site, listening ' 'on a local port') return parser def main(): parser = create_options() args = parser.parse_args() cmd = getattr(commands, args[0]) cmd(args) if __name__ == '__main__': main()
import argparse from . import commands VALID_ARGS = ('init', 'compile', 'serve') def create_options(): "Add options to tornado" parser = argparse.ArgumentParser( 'Staitrator - Static multilingual site and blog generator') parser.add_argument('command', choices=VALID_ARGS) init = parser.add_argument_group('Init Options') init.add_argument('-n', '--name', default='Default site', help='Site name and title') init.add_argument('-c', '--site_class', default='statirator.site.Html5Site', help='The base class for the site') init.add_argument('-s', '--source', default='source', help="Site's source directory") init.add_argument('-b', '--build', default='build', help="Site's build directory") return parser def main(): parser = create_options() args = parser.parse_args() cmd = getattr(commands, args[0]) cmd(args) if __name__ == '__main__': main()
Remove reference to nonexistent migration to fix tests
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('continents', '0001_initial'), ('currencies', '0001_initial'), ] operations = [ migrations.CreateModel( name='ExtraCountry', fields=[ ('code', models.CharField(serialize=False, primary_key=True, max_length=3)), ('country', models.OneToOneField(to='cities.Country')), ('extra_continent', models.ForeignKey(to='continents.Continent', null=True)), ('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)), ], ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('continents', '0001_initial'), ('currencies', '0001_initial'), ('cities', '0002_auto_20151112_1857'), ] operations = [ migrations.CreateModel( name='ExtraCountry', fields=[ ('code', models.CharField(serialize=False, primary_key=True, max_length=3)), ('country', models.OneToOneField(to='cities.Country')), ('extra_continent', models.ForeignKey(to='continents.Continent', null=True)), ('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)), ], ), ]
Use a generic key instead of PublicKey
package org.rmatil.sync.persistence.core.dht; import net.tomp2p.peers.Number160; import net.tomp2p.utils.Utils; import org.rmatil.sync.persistence.api.IPathElement; import java.security.Key; /** * A path element representing data in the DHT */ public class DhtPathElement implements IPathElement { /** * The content key of the path element which should be used */ protected String contentKey; /** * The domain protection key which should be used */ protected Number160 domainProtectionKey; /** * @param contentKey A string which gets used as content key in the DHT * @param domainProtectionKey A public key which is used to access the path in the DHT */ public DhtPathElement(String contentKey, Key domainProtectionKey) { this.contentKey = contentKey; this.domainProtectionKey = Utils.makeSHAHash(domainProtectionKey.getEncoded()); } /** * Returns the content key * * @return A string representing the path of the element */ @Override public String getPath() { return this.contentKey; } /** * Returns the domain protection key which is used * to access the content in the DHT * * @return The domain protection key */ public Number160 getDomainProtectionKey() { return domainProtectionKey; } }
package org.rmatil.sync.persistence.core.dht; import net.tomp2p.peers.Number160; import net.tomp2p.utils.Utils; import org.rmatil.sync.persistence.api.IPathElement; import java.security.PublicKey; /** * A path element representing data in the DHT */ public class DhtPathElement implements IPathElement { /** * The content key of the path element which should be used */ protected String contentKey; /** * The domain protection key which should be used */ protected Number160 domainProtectionKey; /** * @param contentKey A string which gets used as content key in the DHT * @param domainProtectionKey A public key which is used for to access and/or modify the path in the DHT */ public DhtPathElement(String contentKey, PublicKey domainProtectionKey) { this.contentKey = contentKey; this.domainProtectionKey = Utils.makeSHAHash(domainProtectionKey.getEncoded()); } /** * Returns the content key * * @return A string representing the path of the element */ @Override public String getPath() { return this.contentKey; } /** * Returns the domain protection key which is used * to access and/or modify the content in the DHT * * @return The domain protection key */ public Number160 getDomainProtectionKey() { return domainProtectionKey; } }
Change preferred templateName to helper methods name
var extend = require('extend') var fs = require('fs') var Handlebars = require('handlebars') module.exports = plugin function plugin (options) { options = extend({ directory: 'helpers' }, options || {}) return function (files, metalsmith, done) { fs.readdir(metalsmith.path(options.directory), function (err, files) { if (err) throw err files.forEach(function (file) { var helperContents var path var templateName path = metalsmith.path(options.directory, file) helperContents = require(path) switch (typeof helperContents) { case 'function': templateName = helperContents.name || file.split('.').shift() Handlebars.registerHelper(templateName, helperContents) break case 'object': Handlebars.registerHelper(helperContents) break } }) done() }) } }
var extend = require('extend') var fs = require('fs') var Handlebars = require('handlebars') module.exports = plugin function plugin (options) { options = extend({ directory: 'helpers' }, options || {}) return function (files, metalsmith, done) { fs.readdir(metalsmith.path(options.directory), function (err, files) { if (err) throw err files.forEach(function (file) { var helperContents var path var templateName path = metalsmith.path(options.directory, file) helperContents = require(path) switch (typeof helperContents) { case 'function': templateName = file.split('.').shift() Handlebars.registerHelper(templateName, helperContents) break case 'object': Handlebars.registerHelper(helperContents) break } }) done() }) } }
Remove login code from the logout function
var helpers = require('./../../helpers.js') const { client } = require('nightwatch-cucumber') const { defineSupportCode } = require('cucumber') defineSupportCode(({ Given, Then, When }) => { Given(/^I open Drift\'s website$/, () => { return client .url('https://app.drift.com/') .waitForElementVisible('body', 1000); }) Given(/^I log into Drift$/, () => { helpers.login(client); return client; }) Given(/^I log out of Drift$/, () => { return client .click('div.AgentStatusButton---1zsEk') .pause(1000) .useXpath() .click('//span[text()="Sign Out"]') .useCss(); }) Then(/^active tab is "(.*?)"$/, (text) => { return client .useXpath() .assert.cssClassPresent('//a[contains(@href, "/' + text + '")]', 'active') .useCss(); }) When(/^I click tab "(.*?)"$/, (text) => { return client .useXpath() .click('//a[contains(@href, "/' + text + '")]') .useCss; }) })
var helpers = require('./../../helpers.js') const { client } = require('nightwatch-cucumber') const { defineSupportCode } = require('cucumber') defineSupportCode(({ Given, Then, When }) => { Given(/^I open Drift\'s website$/, () => { return client .url('https://app.drift.com/') .waitForElementVisible('body', 1000); }) Given(/^I log into Drift$/, () => { helpers.login(client); return client; }) Given(/^I log out of Drift$/, () => { helpers.login(client) return client .click('div.AgentStatusButton---1zsEk') .pause(1000) .useXpath() .click('//span[text()="Sign Out"]') .useCss(); }) Then(/^active tab is "(.*?)"$/, (text) => { return client .useXpath() .assert.cssClassPresent('//a[contains(@href, "/' + text + '")]', 'active') .useCss(); }) When(/^I click tab "(.*?)"$/, (text) => { return client .useXpath() .click('//a[contains(@href, "/' + text + '")]') .useCss; }) })
Use exact default values from needle docs for clarity
"use strict"; var cacheManager = require("cache-manager"); module.exports = { // cache system (see https://github.com/BryanDonovan/node-cache-manager) Cache: cacheManager.caching({ store: "memory", max: 5000, ttl: 60 * 60 }), // default request timeout values DefaultOpenTimeout: 10000, // 10 seconds; timeout in milliseconds DefaultReadTimeout: 0, // 0 seconds; timeout in milliseconds // socks proxy url to use ProxyURL: null, // e.g. "socks://127.0.0.1:1080" // default Park Settings DefaultParkName: "Default Park", DefaultParkTimezone: "Europe/London", DefaultParkTimeFormat: null, // cache settings (in seconds) DefaultCacheWaitTimesLength: 60 * 5, // 5 minutes DefaultCacheOpeningTimesLength: 60 * 60, // 1 hour // default time return format DefaultTimeFormat: "YYYY-MM-DDTHH:mm:ssZ", // default date return format DefaultDateFormat: "YYYY-MM-DD", };
"use strict"; var cacheManager = require("cache-manager"); module.exports = { // cache system (see https://github.com/BryanDonovan/node-cache-manager) Cache: cacheManager.caching({ store: "memory", max: 5000, ttl: 60 * 60 }), // default request timeout values DefaultOpenTimeout: 10 * 1000, // 10 seconds; timeout in milliseconds DefaultReadTimeout: 0 * 1000, // 0 seconds; timeout in milliseconds // socks proxy url to use ProxyURL: null, // e.g. "socks://127.0.0.1:1080" // default Park Settings DefaultParkName: "Default Park", DefaultParkTimezone: "Europe/London", DefaultParkTimeFormat: null, // cache settings (in seconds) DefaultCacheWaitTimesLength: 60 * 5, // 5 minutes DefaultCacheOpeningTimesLength: 60 * 60, // 1 hour // default time return format DefaultTimeFormat: "YYYY-MM-DDTHH:mm:ssZ", // default date return format DefaultDateFormat: "YYYY-MM-DD", };
Stop resolving paths to the static files. Fixed #33
import json from builtins import super from django import forms class JSONEditorWidget(forms.Widget): class Media: css = {'all': ('dist/jsoneditor.min.css', )} js = ('dist/jsoneditor.min.js',) template_name = 'django_json_widget.html' def __init__(self, attrs=None, mode='code', options=None, width=None, height=None): default_options = { 'modes': ['text', 'code', 'tree', 'form', 'view'], 'mode': mode, 'search': True, } if options: default_options.update(options) self.options = default_options self.width = width self.height = height super(JSONEditorWidget, self).__init__(attrs=attrs) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context['widget']['options'] = json.dumps(self.options) context['widget']['width'] = self.width context['widget']['height'] = self.height return context
import json from builtins import super from django import forms from django.templatetags.static import static class JSONEditorWidget(forms.Widget): class Media: css = {'all': (static('dist/jsoneditor.min.css'), )} js = (static('dist/jsoneditor.min.js'),) template_name = 'django_json_widget.html' def __init__(self, attrs=None, mode='code', options=None, width=None, height=None): default_options = { 'modes': ['text', 'code', 'tree', 'form', 'view'], 'mode': mode, 'search': True, } if options: default_options.update(options) self.options = default_options self.width = width self.height = height super(JSONEditorWidget, self).__init__(attrs=attrs) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context['widget']['options'] = json.dumps(self.options) context['widget']['width'] = self.width context['widget']['height'] = self.height return context
Remove length assertion, since leading zeroes are not encoded.
package shadowfax import ( "crypto/rand" "io" "gopkg.in/basen.v1" "gopkg.in/errgo.v1" ) // Nonce is a 24-byte number that should be used once per message. type Nonce [24]byte // DecodeNonce decodes a nonce from its Base58 string representation. func DecodeNonce(s string) (*Nonce, error) { var nonce Nonce buf, err := basen.Base58.DecodeString(s) if err != nil { return nil, err } copy(nonce[:], buf) return &nonce, nil } // Encode encodes the nonce to a Base58 string representation. func (n Nonce) Encode() string { return basen.Base58.EncodeToString(n[:]) } // NewNonce returns a new random nonce. func NewNonce() (*Nonce, error) { n := new(Nonce) _, err := io.ReadFull(rand.Reader, n[:]) if err != nil { return nil, errgo.Mask(err) } return n, nil }
package shadowfax import ( "crypto/rand" "io" "gopkg.in/basen.v1" "gopkg.in/errgo.v1" ) // Nonce is a 24-byte number that should be used once per message. type Nonce [24]byte // DecodeNonce decodes a nonce from its Base58 string representation. func DecodeNonce(s string) (*Nonce, error) { var nonce Nonce buf, err := basen.Base58.DecodeString(s) if err != nil { return nil, err } if len(buf) != 24 { return nil, errgo.Newf("invalid nonce length %q", buf) } copy(nonce[:], buf) return &nonce, nil } // Encode encodes the nonce to a Base58 string representation. func (n Nonce) Encode() string { return basen.Base58.EncodeToString(n[:]) } // NewNonce returns a new random nonce. func NewNonce() (*Nonce, error) { n := new(Nonce) _, err := io.ReadFull(rand.Reader, n[:]) if err != nil { return nil, errgo.Mask(err) } return n, nil }
Add state.go to saveNote and deleteNote functions. Remove unnecessary resetForm function
(function() { 'use strict'; angular .module('meganote.notes') .controller('NotesFormController', NotesFormController); NotesFormController.$inject = ['notesService', '$state']; function NotesFormController(notesService, $state) { var vm = this; vm.note = notesService.find($state.params.noteId); vm.saveNote = saveNote; vm.deleteNote = deleteNote; ///////////////// function saveNote() { notesService.saveNote(vm.note).then(function(res) { vm.note = angular.copy(res.data.note); $state.go('notes.form', { noteId: vm.note._id }); }); } function deleteNote(note) { notesService.deleteNote(note); $state.go('notes.form', { noteId: undefined }); } } })();
(function() { 'use strict'; angular .module('meganote.notes') .controller('NotesFormController', NotesFormController); NotesFormController.$inject = ['notesService', '$state']; function NotesFormController(notesService, $state) { var vm = this; vm.note = notesService.find($state.params.noteId); vm.saveNote = saveNote; vm.deleteNote = deleteNote; vm.resetForm = resetForm; ///////////////// function saveNote() { notesService.saveNote(vm.note).then(function(res) { vm.note = angular.copy(res.data.note); }); } function deleteNote(note) { notesService.deleteNote(note); resetForm(); } function resetForm() { vm.note = new notesService.Note(); } } })();
Fix thumb image on small devices
<?php /** * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Module / Note / Inc / Class / Design */ namespace PH7; use PH7\Framework\Mvc\Router\Uri; class NoteDesign extends WriteDesignCoreModel { /** * @param object $oNoteModel * @return void Output the URL of the thumbnail. */ public static function thumb($oNoteModel) { echo '<p>'; if (!empty($oNoteModel->thumb)) echo '<a href="', Uri::get('note','main','read', $oNoteModel->username . ',' . $oNoteModel->postId), '" class="pic thumb" data-load="ajax"><img src="', PH7_URL_DATA_SYS_MOD, 'note/', PH7_IMG, $oNoteModel->username, PH7_SH, $oNoteModel->thumb, '" alt="', $oNoteModel->pageTitle, '" title="', $oNoteModel->pageTitle, '" /></a>'; else (new AvatarDesignCore)->get($oNoteModel->username, $oNoteModel->firstName, $oNoteModel->sex, 100); echo '</p>'; } }
<?php /** * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Module / Note / Inc / Class / Design */ namespace PH7; use PH7\Framework\Mvc\Router\Uri; class NoteDesign extends WriteDesignCoreModel { /** * @param object $oNoteModel * @return void Output the URL of the thumbnail. */ public static function thumb($oNoteModel) { echo '<div class="pic thumb">'; if (!empty($oNoteModel->thumb)) echo '<a href="', Uri::get('note','main','read', $oNoteModel->username . ',' . $oNoteModel->postId), '"><img src="', PH7_URL_DATA_SYS_MOD, 'note/', PH7_IMG, $oNoteModel->username, PH7_SH, $oNoteModel->thumb, '" alt="', $oNoteModel->pageTitle, '" title="', $oNoteModel->pageTitle, '" /></a>'; else (new AvatarDesignCore)->get($oNoteModel->username, $oNoteModel->firstName, $oNoteModel->sex, 100); echo '</div>'; } }
Fix tests for updated TinyDB/Tinyrecord
from pypinfo import db CREDS_FILE = '/path/to/creds_file.json' def test_get_credentials(tmp_path): # Arrange db.DB_FILE = str(tmp_path / 'db.json') # Mock # Assert assert db.get_credentials() is None def test_set_credentials(tmp_path): # Arrange db.DB_FILE = str(tmp_path / 'db.json') # Mock # Act db.set_credentials(CREDS_FILE) def test_set_credentials_twice(tmp_path): # Arrange db.DB_FILE = str(tmp_path / 'db.json') # Mock # Act db.set_credentials(CREDS_FILE) db.set_credentials(CREDS_FILE) def test_round_trip(tmp_path): # Arrange db.DB_FILE = str(tmp_path / 'db.json') # Mock # Act db.set_credentials(CREDS_FILE) # Assert assert db.get_credentials() == CREDS_FILE def test_get_credentials_table(tmp_path): db.DB_FILE = str(tmp_path / 'db.json') with db.get_credentials_table() as table: assert not table._storage._handle.closed with db.get_credentials_table(table) as table2: assert table2 is table assert not table._storage._handle.closed assert table._storage._handle.closed
from pypinfo import db CREDS_FILE = '/path/to/creds_file.json' def test_get_credentials(tmp_path): # Arrange db.DB_FILE = str(tmp_path / 'db.json') # Mock # Assert assert db.get_credentials() is None def test_set_credentials(tmp_path): # Arrange db.DB_FILE = str(tmp_path / 'db.json') # Mock # Act db.set_credentials(CREDS_FILE) def test_set_credentials_twice(tmp_path): # Arrange db.DB_FILE = str(tmp_path / 'db.json') # Mock # Act db.set_credentials(CREDS_FILE) db.set_credentials(CREDS_FILE) def test_round_trip(tmp_path): # Arrange db.DB_FILE = str(tmp_path / 'db.json') # Mock # Act db.set_credentials(CREDS_FILE) # Assert assert db.get_credentials() == CREDS_FILE def test_get_credentials_table(tmp_path): db.DB_FILE = str(tmp_path / 'db.json') with db.get_credentials_table() as table: assert not table._storage._storage._handle.closed with db.get_credentials_table(table) as table2: assert table2 is table assert not table._storage._storage._handle.closed assert table._storage._storage._handle.closed
Add whitelisted pages which require google login.
// These URL paths will be transformed to CN mirrors. var mirrors = { "//developers.google.com" : "//developers.google.cn", "//firebase.google.com" : "//firebase.google.cn", "//developer.android.com" : "//developer.android.google.cn", "//angular.io" : "//angular.cn", } // These URL paths are not available on CN mirrors, therefore won't be transformed. var whitelist = [ "//developers.google.com/groups", "//developers.google.com/events", "//firebase.google.com/support/contact/", ] function mirrorUrl(url) { // Check for whitelisting. for (var key in whitelist) { if (url.includes(whitelist[key])) { return url; } } // Check for mapping. for (var key in mirrors) { if (url.includes(key)) { url = url.replace(key, mirrors[key]); break; } } return url; }
// These URL paths will be transformed to CN mirrors. var mirrors = { "//developers.google.com" : "//developers.google.cn", "//firebase.google.com" : "//firebase.google.cn", "//developer.android.com" : "//developer.android.google.cn", "//angular.io" : "//angular.cn", } // These URL paths are not available on CN mirrors, therefore won't be transformed. var whitelist = [ "//developers.google.com/groups", "//developers.google.com/events", ] function mirrorUrl(url) { // Check for whitelisting. for (var key in whitelist) { if (url.includes(whitelist[key])) { return url; } } // Check for mapping. for (var key in mirrors) { if (url.includes(key)) { url = url.replace(key, mirrors[key]); break; } } return url; }
Make database preseeding sensitive to custom build options.
import os import shutil import tempfile temphome = tempfile.mkdtemp() os.environ["KOLIBRI_HOME"] = temphome from kolibri.main import initialize # noqa E402 from kolibri.deployment.default.sqlite_db_names import ( # noqa E402 ADDITIONAL_SQLITE_DATABASES, ) from django.conf import settings # noqa E402 from django.core.management import call_command # noqa E402 move_to = os.path.join(os.path.dirname(__file__), "..", "kolibri", "dist", "home") shutil.rmtree(move_to, ignore_errors=True) os.mkdir(move_to) print("Generating preseeded home data in {}".format(temphome)) initialize() call_command( "deprovision", "--destroy-all-user-data", "--permanent-irrevocable-data-loss" ) for db_config in settings.DATABASES.values(): if db_config["ENGINE"] == "django.db.backends.sqlite3": shutil.move(os.path.join(temphome, db_config["NAME"]), move_to) print("Moved all preseeded home data to {}".format(move_to)) shutil.rmtree(temphome)
import os import shutil import tempfile temphome = tempfile.mkdtemp() os.environ["KOLIBRI_HOME"] = temphome from kolibri.main import initialize # noqa E402 from kolibri.deployment.default.sqlite_db_names import ( # noqa E402 ADDITIONAL_SQLITE_DATABASES, ) from django.core.management import call_command # noqa E402 move_to = os.path.join(os.path.dirname(__file__), "..", "kolibri", "dist", "home") shutil.rmtree(move_to, ignore_errors=True) os.mkdir(move_to) print("Generating preseeded home data in {}".format(temphome)) initialize() call_command( "deprovision", "--destroy-all-user-data", "--permanent-irrevocable-data-loss" ) shutil.move(os.path.join(temphome, "db.sqlite3"), move_to) for db_name in ADDITIONAL_SQLITE_DATABASES: shutil.move(os.path.join(temphome, "{}.sqlite3".format(db_name)), move_to) print("Moved all preseeded home data to {}".format(move_to)) shutil.rmtree(temphome)
Use debug option instead of verbose already used by main executable
#!/usr/bin/env node /** * Module dependencies. */ const program = require('commander'); const fs = require('extfs'); const caller = require('./docsmith/utils/caller'); const templates = require('./docsmith/init/templates'); const init = require('./docsmith/init'); let template; program .arguments('[template]') .option('-f, --force', 'Initialise whether the current directory is empty or not.') .option('--defaults', 'Accepts defaults prompts and skips confirmation.') .option('-l, --link', 'For development purposes. Link local packages.') .option('--debug', 'Display npm log.') .action(function(templ) { template = templ; }) .parse(process.argv); // check if this is an empty folder. fs.isEmpty('.', function(empty) { if (empty || program.force) { if (caller.original()) { // initialises from a built-in template templates.init(template); } else { // called from a content as code instance, initialise from the instance configuration init.run({ template, config: caller.path(true), link: program.link, defaults: program.defaults, verbose: program.debug }); } } else { console.warn('This directory is not empty. Aborting init. Use --force to ignore current content.'); } });
#!/usr/bin/env node /** * Module dependencies. */ const program = require('commander'); const fs = require('extfs'); const caller = require('./docsmith/utils/caller'); const templates = require('./docsmith/init/templates'); const init = require('./docsmith/init'); let template; program .arguments('[template]') .option('-f, --force', 'Initialise whether the current directory is empty or not.') .option('--defaults', 'Accepts defaults prompts and skips confirmation.') .option('-l, --link', 'For development purposes. Link local packages.') .option('--verbose', 'Display npm log.') .action(function(templ) { template = templ; }) .parse(process.argv); // check if this is an empty folder. fs.isEmpty('.', function(empty) { if (empty || program.force) { if (caller.original()) { // initialises from a built-in template templates.init(template); } else { // called from a content as code instance, initialise from the instance configuration init.run({ template, config: caller.path(true), link: program.link, defaults: program.defaults, verbose: program.verbose }); } } else { console.warn('This directory is not empty. Aborting init. Use --force to ignore current content.'); } });
fix(util-load): Add module path based on module name if path does not exist.
function loadModule (newModule) { let name = newModule.name ? newModule.name : 'app' let module = { name, controllers: [], views: [], models: [], data: [] } let files = newModule.files Object.keys(files).forEach(file => { let path = file.match(/([a-zA-Z0-9_]+)/gi) let componentType = path.shift() path.pop() let componentName = path.join('/') if (module[componentType]) { let component = files[file] if (!component.name) { let path = file.match(/([a-zA-Z0-9_]+)/gi) path.pop() path.shift() component.name = path.join('-') } if (componentType === 'models' && !component.path) { component.path = '/' + component.name.replace('-', '/') } module[componentType].push(component) } }) module.data = module.data[0] return module } export default loadModule
function loadModule (newModule) { let name = newModule.name ? newModule.name : 'app' let module = { name, controllers: [], views: [], models: [], data: [] } let files = newModule.files Object.keys(files).forEach(file => { let path = file.match(/([a-zA-Z0-9_]+)/gi) let componentType = path.shift() path.pop() let componentName = path.join('/') if (module[componentType]) { let component = files[file] if (!component.name) { let path = file.match(/([a-zA-Z0-9_]+)/gi) path.pop() path.shift() component.name = path.join('-') } module[componentType].push(component) } }) module.data = module.data[0] return module } export default loadModule
[UPDATE] Fix return acc when not push a state
'use strict' const _ = require('lodash') const hasLoop = (flow) => { if (Array.isArray(flow)) { return _validate(flow) } else if (flow.states) { return _validate(flow.states) } return { status: "error", message: "Flow not found!" } } const _validate = (states) => { const paths = states.reduce((acc, state) => { if (state.automatic) { acc.push({ from: state.name, to: state.transitions[0].to }) } return acc }, []) while (paths.length > 0) { if (validatePath(paths.pop(), paths)) { return { status: ERROR, message: "LOOP" } } } return { status: SUCCESS, message: "OK" } } const validatePath = (root, path, stack = []) => { stack.push(root) if (_.find(stack, { from: root.to })) { return true } const next = _.find(path, { from: root.to }) const newPath = _.remove(path, { from: root.to }) if (!next) { return false } return validatePath(next, newPath, stack) } const ERROR = "error" const SUCCESS = "sucess" module.exports = { hasLoop, ERROR, SUCCESS }
'use strict' const _ = require('lodash') const hasLoop = (flow) => { if (Array.isArray(flow)) { return _validate(flow) } else if (flow.states) { return _validate(flow.states) } return { status: "error", message: "Flow not found!" } } const _validate = (states) => { const paths = states.reduce((acc, state) => { if (state.automatic) { acc.push({ from: state.name, to: state.transitions[0].to }) return acc } }, []) while (paths.length > 0) { if (validatePath(paths.pop(), paths)) { return { status: ERROR, message: "LOOP" } } } return { status: SUCCESS, message: "OK" } } const validatePath = (root, path, stack = []) => { stack.push(root) if (_.find(stack, { from: root.to })) { return true } const next = _.find(path, { from: root.to }) const newPath = _.remove(path, { from: root.to }) if (!next) { return false } return validatePath(next, newPath, stack) } const ERROR = "error" const SUCCESS = "sucess" module.exports = { hasLoop, ERROR, SUCCESS }
Fix apps path for experiment
package org.moonlightcontroller.main; import java.io.IOException; import org.moonlightcontroller.controller.MoonlightController; import org.moonlightcontroller.registry.ApplicationRegistry; import org.moonlightcontroller.registry.IApplicationRegistry; import org.moonlightcontroller.topology.ITopologyManager; import org.moonlightcontroller.topology.TopologyManager; public class Main { public static void main(String[] args) throws IOException { int server_port = 0; if (args.length > 0){ try { server_port = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Argument" + args[0] + " must be a vaild port number."); System.exit(1); } } IApplicationRegistry reg = new ApplicationRegistry(); reg.loadFromPath("./apps"); ITopologyManager topology = TopologyManager.getInstance(); MoonlightController mc = new MoonlightController(reg, topology, server_port); mc.start(); return; } }
package org.moonlightcontroller.main; import java.io.IOException; import org.moonlightcontroller.controller.MoonlightController; import org.moonlightcontroller.registry.ApplicationRegistry; import org.moonlightcontroller.registry.IApplicationRegistry; import org.moonlightcontroller.topology.ITopologyManager; import org.moonlightcontroller.topology.TopologyManager; public class Main { public static void main(String[] args) throws IOException { int server_port = 0; if (args.length > 0){ try { server_port = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Argument" + args[0] + " must be a vaild port number."); System.exit(1); } } IApplicationRegistry reg = new ApplicationRegistry(); reg.loadFromPath("/home/tilon/Workspace/Moonlight/ml-temp/src/main/resources/apps"); ITopologyManager topology = TopologyManager.getInstance(); MoonlightController mc = new MoonlightController(reg, topology, server_port); mc.start(); return; } }
Remove NotEmpty filter from Process.system.
import os import tee class Process(object): """Process related functions using the tee module (mostly).""" def __init__(self, quiet=False, env=None): self.quiet = quiet self.env = env def popen(self, cmd, echo=True, echo2=True): if self.quiet: echo = echo2 = False return tee.popen(cmd, echo, echo2, env=self.env) def pipe(self, cmd): rc, lines = self.popen(cmd, echo=False) if rc == 0 and lines: return lines[0] return '' def system(self, cmd): rc, lines = self.popen(cmd) return rc def os_system(self, cmd): if self.quiet: cmd = cmd + ' >%s 2>&1' % os.devnull if self.env: cmd = ''.join('%s=%s ' % (k, v) for k, v in self.env.items()) + cmd return os.system(cmd)
import os import tee class Process(object): """Process related functions using the tee module (mostly).""" def __init__(self, quiet=False, env=None): self.quiet = quiet self.env = env def popen(self, cmd, echo=True, echo2=True): if self.quiet: echo = echo2 = False return tee.popen(cmd, echo, echo2, env=self.env) def pipe(self, cmd): rc, lines = self.popen(cmd, echo=False) if rc == 0 and lines: return lines[0] return '' def system(self, cmd): rc, lines = self.popen(cmd, echo=tee.NotEmpty()) return rc def os_system(self, cmd): if self.quiet: cmd = cmd + ' >%s 2>&1' % os.devnull if self.env: cmd = ''.join('%s=%s ' % (k, v) for k, v in self.env.items()) + cmd return os.system(cmd)
Add 3rd argument to addEventListener
'use strict'; function FormNapper(formId) { this.htmlForm = document.getElementById(formId); } FormNapper.prototype.hijack = function (onsubmit) { function handler(event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } onsubmit(event); } if (global.addEventListener != null) { this.htmlForm.addEventListener('submit', handler, false); } else if (global.attachEvent != null) { this.htmlForm.attachEvent('onsubmit', handler); } else { this.htmlForm.onsubmit = handler; } }; FormNapper.prototype.inject = function (name, value) { var input = this.htmlForm.querySelector('input[name="' + name + '"]'); if (input == null) { input = document.createElement('input'); input.type = 'hidden'; input.name = name; this.htmlForm.appendChild(input); } input.value = value; }; FormNapper.prototype.submit = function () { HTMLFormElement.prototype.submit.call(this.htmlForm); }; module.exports = FormNapper;
'use strict'; function FormNapper(formId) { this.htmlForm = document.getElementById(formId); } FormNapper.prototype.hijack = function (onsubmit) { function handler(event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } onsubmit(event); } if (global.addEventListener != null) { this.htmlForm.addEventListener('submit', handler); } else if (global.attachEvent != null) { this.htmlForm.attachEvent('onsubmit', handler); } else { this.htmlForm.onsubmit = handler; } }; FormNapper.prototype.inject = function (name, value) { var input = this.htmlForm.querySelector('input[name="' + name + '"]'); if (input == null) { input = document.createElement('input'); input.type = 'hidden'; input.name = name; this.htmlForm.appendChild(input); } input.value = value; }; FormNapper.prototype.submit = function () { HTMLFormElement.prototype.submit.call(this.htmlForm); }; module.exports = FormNapper;
Send full target URL as scenario description
var ACCEPTANCE_TESTS_ENDPOINT = 'http://localhost:9000/api/acceptance-tests', ACCEPTANCE_TESTS_GUI_URL = 'http://localhost:9000/tests/'; function createTest() { var formattedResults = Object.keys(window.lastResult).map(function(key) { return { code: key, expectedValue: window.lastResult[key] } }); var form = document.getElementsByTagName('form')[0]; var data = { expectedResults: formattedResults, scenario: form.action + '?' + serialize(form) } var request = new XMLHttpRequest(); request.open('POST', ACCEPTANCE_TESTS_ENDPOINT); request.onload = function() { if (request.status >= 300) throw request; var data = JSON.parse(request.responseText); document.location = [ ACCEPTANCE_TESTS_GUI_URL, data._id, 'edit' ].join('/'); }; request.onerror = function() { throw request; } request.setRequestHeader('Content-Type', 'application/json'); request.send(JSON.stringify(data)); }
var ACCEPTANCE_TESTS_ENDPOINT = 'http://localhost:9000/api/acceptance-tests', ACCEPTANCE_TESTS_GUI_URL = 'http://localhost:9000/tests/'; function createTest() { var formattedResults = Object.keys(window.lastResult).map(function(key) { return { code: key, expectedValue: window.lastResult[key] } }); var data = { expectedResults: formattedResults, scenario: serialize(document.getElementsByTagName('form')[0]) } var request = new XMLHttpRequest(); request.open('POST', ACCEPTANCE_TESTS_ENDPOINT); request.onload = function() { if (request.status >= 300) throw request; var data = JSON.parse(request.responseText); document.location = [ ACCEPTANCE_TESTS_GUI_URL, data._id, 'edit' ].join('/'); }; request.onerror = function() { throw request; } request.setRequestHeader('Content-Type', 'application/json'); request.send(JSON.stringify(data)); }
Add support GridLayoutManager for itemSpace
package com.omega_r.libs.omegarecyclerview.item_decoration; import android.graphics.Rect; import com.omega_r.libs.omegarecyclerview.item_decoration.decoration_helpers.DividerDecorationHelper; import androidx.annotation.NonNull; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class SpaceItemDecoration extends BaseItemDecoration { private final int space; public SpaceItemDecoration(int showDivider, int space) { super(showDivider); this.space = space; } @Override void getItemOffset(@NonNull Rect outRect, @NonNull RecyclerView parent, @NonNull DividerDecorationHelper helper, int position, int itemCount) { int countBeginEndPositions = getCountBeginEndPositions(parent); if (isShowBeginDivider() || countBeginEndPositions <= position) helper.setStart(outRect, space); if (isShowEndDivider() && position == itemCount - countBeginEndPositions) helper.setEnd(outRect, space); } private int getCountBeginEndPositions(RecyclerView recyclerView) { RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { return ((GridLayoutManager) layoutManager).getSpanCount(); } else return 1; } }
package com.omega_r.libs.omegarecyclerview.item_decoration; import android.graphics.Rect; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.omega_r.libs.omegarecyclerview.item_decoration.decoration_helpers.DividerDecorationHelper; public class SpaceItemDecoration extends BaseItemDecoration { private final int space; public SpaceItemDecoration(int showDivider, int space) { super(showDivider); this.space = space; } @Override void getItemOffset(@NonNull Rect outRect, @NonNull RecyclerView parent, @NonNull DividerDecorationHelper helper, int position, int itemCount) { if (isShowBeginDivider() && position < 1 || position >= 1) helper.setStart(outRect, space); if (isShowEndDivider() && position == itemCount - 1) helper.setEnd(outRect, space); } }
Fix test to use changed retvals
package gocipher import ( "fmt" "testing" ) func TestVigenere(t *testing.T) { text := "TKSYMWRJGHKBPTEIKCYRWXIELQUPSUTLLGYFIKYIAVFNRLQFKVVSMBMJOCZGILSEAPZRGCVVHTVQYKXJSHARVIPCOGHXGZCGLQNEEXLPDQVXWBLVKCTRSVXYWUORPNEJKVYBROGIQRABKZEGZAAJSMQRANLAGZCGLKVATZSUMEAFQICYSXLNPUSJLVORWIQVMULEMVXVJHHPIGIKGPLVWAITMTLJLQPVLJLBXPIIHGYZMBWVSXLFHZSGHKUTEKSDHCYVWWRTZCYGQICJMINRWBXYSVAJSXVFYTHZWPEMWUPZMTEIXGHGYZIJSNAUSCKYGPLUEAKRHKUTWMGLJKALLWPVKYOVPMXYWQAUIZHFWUUGEVIOHGYVIVGVVEYLTBSXJCWUIZGRFVLYPBLVVKMSIZIEUGZBGIRRLJPRJ" key := VigenereCrack(text, 8) v := NewVigenere(key) plain := v.Decrypt(text) fmt.Printf("key: %v\nplaintext: %s\n", key, plain) cipher := v.Encrypt(plain) if cipher != text { t.Errorf("roundtrip not equal: %s", cipher) } }
package gocipher import ( "fmt" "testing" ) func TestVigenere(t *testing.T) { text := "TKSYMWRJGHKBPTEIKCYRWXIELQUPSUTLLGYFIKYIAVFNRLQFKVVSMBMJOCZGILSEAPZRGCVVHTVQYKXJSHARVIPCOGHXGZCGLQNEEXLPDQVXWBLVKCTRSVXYWUORPNEJKVYBROGIQRABKZEGZAAJSMQRANLAGZCGLKVATZSUMEAFQICYSXLNPUSJLVORWIQVMULEMVXVJHHPIGIKGPLVWAITMTLJLQPVLJLBXPIIHGYZMBWVSXLFHZSGHKUTEKSDHCYVWWRTZCYGQICJMINRWBXYSVAJSXVFYTHZWPEMWUPZMTEIXGHGYZIJSNAUSCKYGPLUEAKRHKUTWMGLJKALLWPVKYOVPMXYWQAUIZHFWUUGEVIOHGYVIVGVVEYLTBSXJCWUIZGRFVLYPBLVVKMSIZIEUGZBGIRRLJPRJ" key, err := VigenereCrack(text, 8) if err != nil { t.Fatal(err) } v := NewVigenere(key) plain := v.Decrypt(text) fmt.Printf("key: %v\nplaintext: %s\n", key, plain) cipher := v.Encrypt(plain) if cipher != text { t.Errorf("roundtrip not equal: %s", cipher) } }
Make it into a simple library
var mt = require('mersenne-twister') function getRange(from, to) { var range = [] for (;from <= to; from++) { range.push(from) } return range } function getAsciiCodes() { return [].concat( getRange(97,122), [32,33,44,46] ) } function getCharacterGenerator(seed) { var prng = new mt(seed) var codes = getAsciiCodes() return (function* randomCharacterGen() { while(true) { var index = Math.floor(prng.random() * codes.length) yield String.fromCharCode(codes[index]) } })() } module.exports = getCharacterGenerator
var mt = require('mersenne-twister') var prng var codes var generator main() function main() { seed = process.argv[2] setup(seed) console.log(getBuffer(10000)) } function setup(seed) { if (!seed) { console.log('no seed provided - using default seed') seed = 123 } prng = new mt(seed) codes = getCommonCodes() charGen = randomCharacterGen() } function getBuffer(size) { var buffer = '' var i = 0 while (i++ < size) { buffer += charGen.next().value } return buffer } function getRange(from, to) { var range = [] for (;from <= to; from++) { range.push(from) } return range } function getCommonCodes() { var codes = getRange(97, 122) codes.push(32) codes.push(33) codes.push(44) codes.push(46) return codes } function* randomCharacterGen() { while(true) { var index = Math.floor(prng.random() * codes.length) var code = codes[index] yield String.fromCharCode(code) } }
Fix the thing that @quis broke.
import re class Presenters(object): def __init__(self): return None def present(self, value, question_content): if "type" in question_content: field_type = question_content["type"] else: return value if hasattr(self, "_" + field_type): return getattr(self, "_" + field_type)(value) else: return value def _service_id(self, value): if re.findall("[a-zA-Z]", str(value)): return [value] else: return re.findall("....", str(value)) def _upload(self, value): return { "url": value or "", "filename": value.split("/")[-1] or "" }
import re class Presenters(object): def __init__(self): return None def present(self, value, question_content): if "type" in question_content: field_type = question_content["type"] else: return value if hasattr(self, "_" + field_type): return getattr(self, "_" + field_type)(value) else: return value def _service_id(self, value): if re.findall("[a-zA-Z]", value): return [value] else: return re.findall("....", str(value)) def _upload(self, value): return { "url": value or "", "filename": value.split("/")[-1] or "" }
Rename test_file to make nosetest happy
import os import re import sys import unittest from functools import partial class TestExamples(unittest.TestCase): pass def _test_file(filename): # Ignore the output saved = sys.stdout with open('/dev/null', 'w') as stdout: sys.stdout = stdout try: with open(filename) as f: code = compile(f.read(), filename, 'exec') exec(code) finally: sys.stdout = saved def add_tests(): # Filter out all *.py files from the examples directory examples = 'examples' regex = re.compile(r'.py$', re.I) example_filesnames = filter(regex.search, os.listdir(examples)) # Add new test functions to the TestExamples class for f in example_filesnames: testname = 'test_' + f[:-3] testfunc = partial(_test_file, examples + '/' + f) # Get rid of partial() __doc__ testfunc.__doc__ = None setattr(TestExamples, testname, testfunc) add_tests() if __name__ == '__main__': unittest.main()
import os import re import sys import unittest from functools import partial class TestExamples(unittest.TestCase): pass def test_file(filename): # Ignore the output saved = sys.stdout with open('/dev/null', 'w') as stdout: sys.stdout = stdout try: with open(filename) as f: code = compile(f.read(), filename, 'exec') exec(code) finally: sys.stdout = saved def add_tests(): # Filter out all *.py files from the examples directory examples = 'examples' regex = re.compile(r'.py$', re.I) example_filesnames = filter(regex.search, os.listdir(examples)) # Add new test functions to the TestExamples class for f in example_filesnames: testname = 'test_' + f[:-3] testfunc = partial(test_file, examples + '/' + f) # Get rid of partial() __doc__ testfunc.__doc__ = None setattr(TestExamples, testname, testfunc) add_tests() if __name__ == '__main__': unittest.main()
Add scenario where successor is null
<?php namespace UghAuthentication\Authentication\Adapter; use Zend\Authentication\Adapter\AdapterInterface; use Zend\Authentication\Result; abstract class Adapter implements AdapterInterface { /** @var AdapterInterface */ private $successor; /** * * @return Result */ public function authenticate() { $result = $this->doAuthentication(); if (!$result->isValid() && !is_null($this->successor)) { return $this->successor->authenticate(); } return $result; } /** * * @param AdapterInterface $successor */ public function setSuccessor(AdapterInterface $successor) { $this->successor = $successor; } /** * @return Result */ abstract protected function doAuthentication(); }
<?php namespace UghAuthentication\Authentication\Adapter; use Zend\Authentication\Adapter\AdapterInterface; use Zend\Authentication\Result; abstract class Adapter implements AdapterInterface { /** @var AdapterInterface */ private $successor; /** * * @return Result */ public function authenticate() { $result = $this->doAuthentication(); if (!$result->isValid()) { return $this->successor->authenticate(); } return $result; } /** * * @param AdapterInterface $successor */ public function setSuccessor(AdapterInterface $successor) { $this->successor = $successor; } /** * @return Result */ abstract protected function doAuthentication(); }
Apply changelog versioning fix from 1.14.3.1. Had thought this looked wrong, but didn't want to alter behavior.
<?php class SomethingDigital_EnterpriseIndexPerf_Model_Changelog extends Enterprise_Index_Model_Changelog { /** * Load changelog ids by metadata. * * This differs from the parent by adding a DISTINCT. * * @param null|int $currentVersion Version id to stop at. * @return int[] */ public function loadByMetadata($currentVersion = null) { $select = $this->_connection->select() ->from(array('changelog' => $this->_metadata->getChangelogName()), array()) ->where('version_id > ?', $this->_metadata->getVersionId()) ->columns(array($this->_metadata->getKeyColumn())) ->distinct(); if ($currentVersion) { $select->where('version_id <= ?', $currentVersion); } return $this->_connection->fetchCol($select); } }
<?php class SomethingDigital_EnterpriseIndexPerf_Model_Changelog extends Enterprise_Index_Model_Changelog { /** * Load changelog ids by metadata. * * This differs from the parent by adding a DISTINCT. * * @param null|int $currentVersion Version id to stop at. * @return int[] */ public function loadByMetadata($currentVersion = null) { $select = $this->_connection->select() ->from(array('changelog' => $this->_metadata->getChangelogName()), array()) ->where('version_id >= ?', $this->_metadata->getVersionId()) ->columns(array($this->_metadata->getKeyColumn())) ->distinct(); if ($currentVersion) { $select->where('version_id < ?', $currentVersion); } return $this->_connection->fetchCol($select); } }
Add protected routes and 404 route
import React, { Component } from 'react'; import { Router, Route, Switch } from 'react-router-dom'; import { hot } from 'react-hot-loader'; import PrivateRoute from './PrivateRoute'; import GuestRoute from './GuestRoute'; import AdminRoute from './AdminRoute'; import SignUpPage from './SignUp/SignUpPage'; import LoginPage from './Login/LoginPage'; import IndexPage from './Index'; import NotFound from './NotFound'; import Books from './Books'; import User from './User'; import Admin from './Admin'; class App extends Component { render() { return ( <Router history = { this.props.history }> <Switch> <GuestRoute exact path = '/signup' component = { SignUpPage } /> <GuestRoute exact path = '/login' component = { LoginPage } /> <Route exact path = '/' component = { IndexPage } /> <Route path = '/books' component = { Books } /> <PrivateRoute path = '/users' component = { User } /> <AdminRoute path = '/admin' component = { Admin } /> <Route component = { NotFound } /> </Switch> </Router> ); } } export default hot(module)(App);
import React, { Component } from 'react'; import { Router, Route, Switch } from 'react-router-dom'; import { hot } from 'react-hot-loader'; import SignUpPage from './SignUp/SignUpPage'; import LoginPage from './Login/LoginPage'; import IndexPage from './Index'; import Books from './Books'; import User from './User'; import Admin from './Admin'; class App extends Component { render() { return ( <Router history = { this.props.history }> <Switch> <Route exact path = '/signup' component = { SignUpPage } /> <Route exact path = '/login' component = { LoginPage } /> <Route exact path = '/' component = { IndexPage } /> <Route path = '/books' component = { Books } /> <Route path = '/users' component = { User } /> <Route path = '/admin' component = { Admin } /> </Switch> </Router> ); } } export default hot(module)(App);
Add accept only for false, check result statusCode Technically the request is not sent with the `accept` option when you do want to accept the user. Not sure if this behavior is really important to match but people have been having problems with this function.
// Includes var http = require('../util/http.js').func; var getGeneralToken = require('../util/getGeneralToken.js').func; // Args exports.required = ['group', 'requestId', 'accept']; exports.optional = ['jar']; // Define function handleJoinRequestId (jar, token, accept, requestId) { var httpOpt = { url: '//www.roblox.com/group/handle-join-request', options: { method: 'POST', jar: jar, form: { groupJoinRequestId: requestId }, headers: { 'X-CSRF-TOKEN': token }, resolveWithFullResponse: true } }; if (!accept) { httpOpt.options.form.accept = false; } return http(httpOpt) .then(function (res) { if (res.statusCode === 200) { if (!JSON.parse(res.body).success) { throw new Error('Invalid permissions, make sure the user is in the group and is allowed to handle join requests'); } } else { throw new Error('Invalid status: ' + res.statusCode + ' ' + res.statusMessage); } }); } exports.func = function (args) { var jar = args.jar; var requestId = args.requestId; return getGeneralToken({jar: jar}) .then(function (xcsrf) { return handleJoinRequestId(jar, xcsrf, args.accept, requestId); }); };
// Includes var http = require('../util/http.js').func; var getGeneralToken = require('../util/getGeneralToken.js').func; // Args exports.required = ['group', 'requestId', 'accept']; exports.optional = ['jar']; // Define function handleJoinRequestId (jar, token, accept, requestId) { var httpOpt = { url: '//www.roblox.com/group/handle-join-request', options: { method: 'POST', jar: jar, form: { groupJoinRequestId: requestId, accept: accept }, headers: { 'X-CSRF-TOKEN': token } } }; return http(httpOpt) .then(function (body) { if (!JSON.parse(body).success) { throw new Error('Invalid permissions, make sure the user is in the group and is allowed to handle join requests'); } }); } exports.func = function (args) { var jar = args.jar; var requestId = args.requestId; return getGeneralToken({jar: jar}) .then(function (xcsrf) { return handleJoinRequestId(jar, xcsrf, args.accept, requestId); }); };
Clean up imports in smolder tests
#!/usr/bin/env python2 import smolder import json import os from nose.tools import assert_raises from imp import reload THIS_DIR = os.path.dirname(os.path.realpath(__file__)) def test_noop_test(): assert smolder.noop_test() def test_github_status(): myfile = open(THIS_DIR + '/github_status.json') test_json = json.load(myfile) for test in test_json['tests']: smolder.http_test(test, 'status.github.com', False) reload(smolder) assert smolder.failed_tests == 0 def test_github_status_response_time_expect_fail(): myfile = open(THIS_DIR + '/harsh_github_status.json') test_json = json.load(myfile) for test in test_json['tests']: smolder.http_test(test, 'status.github.com', False) reload(smolder) assert smolder.failed_tests > 0 def test_tcp_test(): smolder.tcp_test('127.0.0.1', 22) #Are you running an ssh server? def test_fail_tcp_test(): assert_raises(Exception, smolder.tcp_test, '127.0.0.1', 4242)
#!/usr/bin/env python2 import smolder import nose import json import os from nose.tools import assert_raises from imp import reload THIS_DIR = os.path.dirname(os.path.realpath(__file__)) def test_noop_test(): assert smolder.noop_test() def test_github_status(): myfile = open(THIS_DIR + '/github_status.json') test_json = json.load(myfile) for test in test_json['tests']: smolder.http_test(test, 'status.github.com', False) reload(smolder) assert smolder.failed_tests == 0 def test_github_status_response_time_expect_fail(): myfile = open(THIS_DIR + '/harsh_github_status.json') test_json = json.load(myfile) for test in test_json['tests']: smolder.http_test(test, 'status.github.com', False) reload(smolder) assert smolder.failed_tests > 0 def test_tcp_test(): smolder.tcp_test('127.0.0.1', 22) #Are you running an ssh server? def test_fail_tcp_test(): assert_raises(Exception, smolder.tcp_test, '127.0.0.1', 4242)
Improve description of dronekit on PyPi
from setuptools import setup, Extension import platform version = '2.1.0' setup(name='dronekit', zip_safe=True, version=version, description='Developer Tools for Drones.', long_description='Python API for communication and control of drones over MAVLink.', url='https://github.com/dronekit/dronekit-python', author='3D Robotics', install_requires=[ 'pymavlink>=1.1.62', 'requests>=2.5.0,<=2.99999', ], author_email='tim@3drobotics.com, kevinh@geeksville.com', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering', ], license='apache', packages=[ 'dronekit', 'dronekit.cloud', 'dronekit.test' ], ext_modules=[])
from setuptools import setup, Extension import platform version = '2.1.0' setup(name='dronekit', zip_safe=True, version=version, description='Python language bindings for the DroneApi', long_description='Python language bindings for the DroneApi', url='https://github.com/dronekit/dronekit-python', author='3D Robotics', install_requires=[ 'pymavlink>=1.1.62', 'requests>=2.5.0,<=2.99999', ], author_email='tim@3drobotics.com, kevinh@geeksville.com', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering', ], license='apache', packages=[ 'dronekit', 'dronekit.cloud', 'dronekit.test' ], ext_modules=[])
Fix template loading when installed with easy_install If you install a package using `easy_install` or `setup.py install`, it will default to installing as a zipped egg. Django is by default unable to find templates inside zipped archives and even with an egg template loader enabled it's very slow as it involves unpacking the archive when the template is needed. Setting `zip_safe=False` forces `setuptools` to always install the package uncompressed.
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import materializecssform setup( name='django-materializecss-form', version=materializecssform.__version__, packages=find_packages(), author="Florent CLAPIÉ", author_email="clapie.florent@gmail.com", description="A simple Django form template tag to work with Materializecss", long_description=open('README.rst').read(), # install_requires= , include_package_data=True, url='https://github.com/florent1933/django-materializecss-form', classifiers=[ "Programming Language :: Python", "Development Status :: 3 - Alpha", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 2.7", "Topic :: Documentation :: Sphinx", ], license="MIT", zip_safe=False )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import materializecssform setup( name='django-materializecss-form', version=materializecssform.__version__, packages=find_packages(), author="Florent CLAPIÉ", author_email="clapie.florent@gmail.com", description="A simple Django form template tag to work with Materializecss", long_description=open('README.rst').read(), # install_requires= , include_package_data=True, url='https://github.com/florent1933/django-materializecss-form', classifiers=[ "Programming Language :: Python", "Development Status :: 3 - Alpha", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 2.7", "Topic :: Documentation :: Sphinx", ], license="MIT", )
Fix formatting in byte validator
<?php /** * Byte values validator * @file Byte.php * * PHP version 5.3.9+ * * @author Alexander Yancharuk <alex@itvault.info> * @date Вск Фев 17 10:48:43 2013 * @copyright The BSD 3-Clause License. */ namespace Veles\Validators; /** * Class Byte * @author Alexander Yancharuk <alex@itvault.info> */ class Byte implements iValidator { /** * Check byte values * @param mixed $size Size in bytes * @return bool */ final public function check($size) { return is_numeric($size); } /** * Convert byte values to human readable format * @param int $size Size in bytes * @param int $precision Precision of returned values * @return string */ final public static function format($size, $precision = 2) { $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); $size = max($size, 0); $pow = floor(($size ? log($size) : 0) / log(1024)); $pow = min($pow, count($units) - 1); $size /= (1 << (10 * $pow)); return number_format($size, $precision) . ' ' . $units[$pow]; } }
<?php /** * Byte values validator * @file Byte.php * * PHP version 5.3.9+ * * @author Alexander Yancharuk <alex@itvault.info> * @date Вск Фев 17 10:48:43 2013 * @copyright The BSD 3-Clause License. */ namespace Veles\Validators; /** * Class Byte * @author Alexander Yancharuk <alex@itvault.info> */ class Byte implements iValidator { /** * Check byte values * @param mixed $size Size in bytes * @return bool */ final public function check($size) { return is_numeric($size); } /** * Convert byte values to human readable format * @param int $size Size in bytes * @param int $precision Precision of returned values * @return string */ final public static function format($size, $precision = 2) { $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); $size = max($size, 0); $pow = floor(($size ? log($size) : 0) / log(1024)); $pow = min($pow, count($units) - 1); $size /= (1 << (10 * $pow)); return round($size, $precision) . ' ' . $units[$pow]; } }
Add support for item tab icon suppliers.
package net.darkhax.bookshelf.api.item; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.EnchantmentCategory; import net.minecraft.world.level.ItemLike; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; public interface ICreativeTabBuilder<BT extends ICreativeTabBuilder<BT>> { default BT setIcon(ItemLike icon) { return this.setIcon(new ItemStack(icon)); } default BT setIcon(ItemStack icon) { return setIcon(() -> icon); } default BT setIconItem(Supplier<ItemLike> iconSupplier) { return this.setIcon(() -> new ItemStack(iconSupplier.get())); } BT setIcon(Supplier<ItemStack> iconSupplier); BT setEnchantmentCategories(EnchantmentCategory... categories); default BT setTabContents(List<ItemStack> items) { return setTabContents(tabContents -> tabContents.addAll(items)); } BT setTabContents(Consumer<List<ItemStack>> contentSupplier); CreativeModeTab build(); ResourceLocation getTabId(); }
package net.darkhax.bookshelf.api.item; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.EnchantmentCategory; import net.minecraft.world.level.ItemLike; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; public interface ICreativeTabBuilder<BT extends ICreativeTabBuilder<BT>> { default BT setIcon(ItemLike icon) { return this.setIcon(new ItemStack(icon)); } default BT setIcon(ItemStack icon) { return setIcon(() -> icon); } BT setIcon(Supplier<ItemStack> iconSupplier); BT setEnchantmentCategories(EnchantmentCategory... categories); default BT setTabContents(List<ItemStack> items) { return setTabContents(tabContents -> tabContents.addAll(items)); } BT setTabContents(Consumer<List<ItemStack>> contentSupplier); CreativeModeTab build(); ResourceLocation getTabId(); }
Add class method decorator demo.
import functools def logParams(function): @functools.wraps(function) # use this to prevent loss of function attributes def wrapper(*args, **kwargs): print("function: {}, args: {}, kwargs: {}".format(function.__name__, args, kwargs)) return function(*args, **kwargs) return wrapper def add(a, b): return a + b @logParams def mul(a, b): return a * b add(1, 1) mul(2, 2) def memo(function): function.cache = dict() @functools.wraps(function) def wrapper(*args): if args not in function.cache: function.cache[args] = function(*args) return function.cache[args] return wrapper @memo def fib(n): if n < 2: return n else: return fib(n - 1) + fib(n - 2) for i in range(1, 10): print("fib{}:{}".format(i, fib(i))) def trace(func): @functools.wraps(func) def _trace(self, *args): print("Invoking {} - {}".format(self, args)) func(self, *args) return _trace class FooBar: @trace def dummy(self, s): print(s) fb = FooBar() fb.dummy("Hello")
import functools def logParams(function): @functools.wraps(function) # use this to prevent loss of function attributes def wrapper(*args, **kwargs): print("function: {}, args: {}, kwargs: {}".format(function.__name__, args, kwargs)) return function(*args, **kwargs) return wrapper def add(a, b): return a + b @logParams def mul(a, b): return a * b add(1, 1) mul(2, 2) def memo(function): function.cache = dict() @functools.wraps(function) def wrapper(*args): if args not in function.cache: function.cache[args] = function(*args) return function.cache[args] return wrapper @memo def fib(n): if n < 2: return n else: return fib(n - 1) + fib(n - 2) for i in range(1, 10): print("fib{}:{}".format(i, fib(i)))
Set service properties 'clustertype' and 'index'. - 'clustername' is already set correctly in AbstractService.
package com.yahoo.vespa.model.admin.metricsproxy; import com.yahoo.config.model.api.container.ContainerServiceType; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.vespa.model.container.Container; import static com.yahoo.config.model.api.container.ContainerServiceType.METRICS_PROXY_CONTAINER; /** * Container running a metrics proxy. * * @author gjoranv */ public class MetricsProxyContainer extends Container { public MetricsProxyContainer(AbstractConfigProducer parent, int index) { super(parent, "" + index, index); setProp("clustertype", "admin"); setProp("index", String.valueOf(index)); } @Override protected ContainerServiceType myServiceType() { return METRICS_PROXY_CONTAINER; } @Override public int getWantedPort() { return 19092; // TODO: current metrics-proxy uses 19091 as rpc port, will now get 19093. } @Override public boolean requiresWantedPort() { return true; } @Override public int getPortCount() { return super.getPortCount() + 1; } @Override protected void tagServers() { super.tagServers(); portsMeta.on(numHttpServerPorts).tag("rpc").tag("metrics"); } }
package com.yahoo.vespa.model.admin.metricsproxy; import com.yahoo.config.model.api.container.ContainerServiceType; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.vespa.model.container.Container; import static com.yahoo.config.model.api.container.ContainerServiceType.METRICS_PROXY_CONTAINER; /** * Container running a metrics proxy. * * @author gjoranv */ public class MetricsProxyContainer extends Container { public MetricsProxyContainer(AbstractConfigProducer parent, int index) { super(parent, "" + index, index); } @Override protected ContainerServiceType myServiceType() { return METRICS_PROXY_CONTAINER; } @Override public int getWantedPort() { return 19092; // TODO: current metrics-proxy uses 19091 as rpc port, will now get 19093. } @Override public boolean requiresWantedPort() { return true; } @Override public int getPortCount() { return super.getPortCount() + 1; } @Override protected void tagServers() { super.tagServers(); portsMeta.on(numHttpServerPorts).tag("rpc").tag("metrics"); } }
Correct FAQ link on footer
export const siteMapData = [ { title: 'Tools', links: [ { title: 'Country Profiles', href: '/countries' }, { title: 'NDCs', href: '/ndcs-content' }, { title: 'NDC-SDG Linkages', href: '/ndcs-sdg' }, { title: 'Historical GHG Emissions', href: '/ghg-emissions' }, { title: 'Pathways', href: '/pathways' } ] }, { title: 'Data', links: [ { title: 'Explore Datasets', href: '/data-explorer' }, { title: 'My Climate Watch', href: '/my-climate-watch' } ] }, { title: 'Country Platforms', links: [ // { title: 'India', href: '/' }, // { title: 'Indonesia', href: '/' }, { title: 'South Africa', href: 'http://southafricaclimateexplorer.org/' } ] }, { title: 'About', links: [ { title: 'About Climate Watch', href: '/about' }, { title: 'Climate Watch Partners', href: '/about/partners' }, { title: 'Contact Us & Feedback', href: '/about/contact' }, { title: 'Permissions & Licensing', href: '/about/permissions' }, { title: 'FAQ', href: '/about/faq/general_questions' } ] } ];
export const siteMapData = [ { title: 'Tools', links: [ { title: 'Country Profiles', href: '/countries' }, { title: 'NDCs', href: '/ndcs-content' }, { title: 'NDC-SDG Linkages', href: '/ndcs-sdg' }, { title: 'Historical GHG Emissions', href: '/ghg-emissions' }, { title: 'Pathways', href: '/pathways' } ] }, { title: 'Data', links: [ { title: 'Explore Datasets', href: '/data-explorer' }, { title: 'My Climate Watch', href: '/my-climate-watch' } ] }, { title: 'Country Platforms', links: [ // { title: 'India', href: '/' }, // { title: 'Indonesia', href: '/' }, { title: 'South Africa', href: 'http://southafricaclimateexplorer.org/' } ] }, { title: 'About', links: [ { title: 'About Climate Watch', href: '/about' }, { title: 'Climate Watch Partners', href: '/about/partners' }, { title: 'Contact Us & Feedback', href: '/about/contact' }, { title: 'Permissions & Licensing', href: '/about/permissions' }, { title: 'FAQ', href: '/about/faq' } ] } ];
Switch back to staging API.
'use strict'; define(["angular", "app/services/LoginChecker", "app/services/FileLoader", "app/services/FigureUploader", "app/services/SnippetLoader", "app/services/TagLoader", "app/services/IdLoader"], function() { /* Services */ angular.module('scooter.services', []) .constant('Repo', { owner: "ucam-cl-dtg", name: "rutherford-content" }) .constant('ApiServer', "https://staging.isaacphysics.org/api/any/api") .service('LoginChecker', require("app/services/LoginChecker")) .factory('FileLoader', require("app/services/FileLoader")) .factory('FigureUploader', require("app/services/FigureUploader")) .service('SnippetLoader', require("app/services/SnippetLoader")) .factory('TagLoader', require("app/services/TagLoader")) .factory('IdLoader', require("app/services/IdLoader")) });
'use strict'; define(["angular", "app/services/LoginChecker", "app/services/FileLoader", "app/services/FigureUploader", "app/services/SnippetLoader", "app/services/TagLoader", "app/services/IdLoader"], function() { /* Services */ angular.module('scooter.services', []) .constant('Repo', { owner: "ucam-cl-dtg", name: "rutherford-content" }) .constant('ApiServer', "https://dev.isaacphysics.org/api/docker/api") .service('LoginChecker', require("app/services/LoginChecker")) .factory('FileLoader', require("app/services/FileLoader")) .factory('FigureUploader', require("app/services/FigureUploader")) .service('SnippetLoader', require("app/services/SnippetLoader")) .factory('TagLoader', require("app/services/TagLoader")) .factory('IdLoader', require("app/services/IdLoader")) });
Update PHP parser to add file extension
<?php namespace Nueve\ViewPresenter; /** * PhpParser */ class PhpParser implements ParserInterface { private $templateDirectory; private $fileExt = '.php'; public function __construct($templateDirectory) { $this->templateDirectory = rtrim($templateDirectory, DIRECTORY_SEPARATOR); } private function getTemplatePathname($template) { if (strpos($template, $this->fileExt) === false) { $template = $template . $this->fileExt; } return $this->templateDirectory . DIRECTORY_SEPARATOR . ltrim($template, DIRECTORY_SEPARATOR); } public function render($template, array $data = []) { $templateFile = $this->getTemplatePathname($template); extract($data); ob_start(); require $templateFile; return ob_get_clean(); } }
<?php namespace Nueve\ViewPresenter; /** * PhpParser */ class PhpParser implements ParserInterface { private $templateDirectory; private $fileExt = '.php'; public function __construct($templateDirectory) { $this->templateDirectory = rtrim($templateDirectory, DIRECTORY_SEPARATOR); } private function getTemplatePathname($template) { if (strpos($template, $this->fileExt) !== false) { $template = $template . $this->fileExt; } return $this->templateDirectory . DIRECTORY_SEPARATOR . ltrim($template, DIRECTORY_SEPARATOR); } public function render($template, array $data = []) { $templateFile = $this->getTemplatePathname($template); extract($data); ob_start(); require $templateFile; return ob_get_clean(); } }