text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix null Charset encoding that was breaking tests :) | package org.ocpsoft.rewrite.transform.minify;
import java.nio.charset.Charset;
import org.ocpsoft.rewrite.transform.Transformer;
/**
* A {@link Transformer} implementation that can perform various minification tasks.
*
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*/
public abstract class Minify implements Transformer
{
private Charset charset = Charset.forName("UTF-8");
/**
* Specify the {@link Charset} to be used during minification.
*
* @param charset the {@link Charset} to be used.
*/
public Minify usingCharset(Charset charset)
{
this.charset = charset;
return this;
}
public static JsMinify js()
{
return new JsMinify();
}
public static CssMinify css()
{
return new CssMinify();
}
/**
* Get the {@link Charset} to be used during minification.
*/
protected Charset getCharset()
{
return charset;
}
}
| package org.ocpsoft.rewrite.transform.minify;
import java.nio.charset.Charset;
import org.ocpsoft.rewrite.transform.Transformer;
/**
* A {@link Transformer} implementation that can perform various minification tasks.
*
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*/
public abstract class Minify implements Transformer
{
private Charset charset;
/**
* Specify the {@link Charset} to be used during minification.
*
* @param charset the {@link Charset} to be used.
*/
public Minify usingCharset(Charset charset)
{
this.charset = charset;
return this;
}
public static JsMinify js()
{
return new JsMinify();
}
public static CssMinify css()
{
return new CssMinify();
}
/**
* Get the {@link Charset} to be used during minification.
*/
protected Charset getCharset()
{
return charset;
}
}
|
Revert "remove beautifulsoup4 from requirements"
This reverts commit e096c4d50a1fcc81a4f63b24d82f8f1dba9c493d.
Turns out we were actually using Beautiful Soup somewhere. Oops. | from setuptools import setup, find_packages
setup(
name = 'openarticlegauge',
version = '0.0.1',
packages = find_packages(),
install_requires = [
"Flask==0.9",
"Jinja2==2.6",
"Werkzeug==0.8.3",
"amqp==1.0.6",
"anyjson==0.3.3",
"argparse==1.2.1",
"billiard==2.7.3.19",
"celery==3.0.13",
"kombu==2.5.4",
"python-dateutil==1.5",
"wsgiref==0.1.2",
"Flask-WTF",
"requests==1.1.0",
"redis",
"lxml",
"beautifulsoup4"
]
)
| from setuptools import setup, find_packages
setup(
name = 'openarticlegauge',
version = '0.0.1',
packages = find_packages(),
install_requires = [
"Flask==0.9",
"Jinja2==2.6",
"Werkzeug==0.8.3",
"amqp==1.0.6",
"anyjson==0.3.3",
"argparse==1.2.1",
"billiard==2.7.3.19",
"celery==3.0.13",
"kombu==2.5.4",
"python-dateutil==1.5",
"wsgiref==0.1.2",
"Flask-WTF",
"requests==1.1.0",
"redis",
"lxml",
]
)
|
Rename email_user method to send_email and fix parameters | import logging
from django.core import mail
from .tasks import task_email_user
logger = logging.getLogger(__name__)
def send_email(user, template, context, attachments=None, delete_attachments_after_send=False,
language_code=None):
'''
Send email to user
:param user: User instance or recipient email addres
:param template: Template to use for email
:param context: Context for email
:param attachments: List of attachments
:param delete_attachments_after_send: If true, delete attachments from storage after sending
:param language_code: Language code for template
:return:
'''
### check if we are using test framework
if hasattr(mail, 'outbox'):
### if yes, do not defer sending email
send_email_f = task_email_user
else:
### otherwise, defer sending email to celery
send_email_f = task_email_user.delay
### send email
send_email_f(
user.pk if user else None,
template,
context,
attachments=attachments,
delete_attachments_after_send=delete_attachments_after_send,
language_code=language_code
)
| import logging
from django.core import mail
from .tasks import task_email_user
logger = logging.getLogger(__name__)
def email_user(user, template, context, attachments=None, delete_attachments_after_send=False, send_to=None,
language_code=None):
'''
Send email to user
:param user: User instance or None if no DB user is used
:param template: Template to use for email
:param context: Context for email
:param attachments: List of attachments
:param delete_attachments_after_send: If true, delete attachments from storage after sending
:param send_to: email address to send (or None, to use user email address)
:param language_code: Language code for template
:return:
'''
### check if we are using test framework
if hasattr(mail, 'outbox'):
### if yes, do not defer sending email
send_email_f = task_email_user
else:
### otherwise, defer sending email to celery
send_email_f = task_email_user.delay
### send email
send_email_f(
user.pk if user else None,
template,
context,
attachments=attachments,
delete_attachments_after_send=delete_attachments_after_send,
send_to=send_to,
language_code=language_code
)
|
Use correct dependencies for tests | Package.describe({
git: 'https://github.com/zimme/meteor-active-route.git',
name: 'zimme:active-route',
summary: 'Active route helpers',
version: '2.1.0'
});
Package.onUse(function(api) {
api.versionsFrom('1.0');
api.use([
'check',
'coffeescript',
'reactive-dict',
'underscore'
]);
api.use([
'meteorhacks:flow-router@1.8.0',
'iron:router@1.0.0',
'templating'
], ['client', 'server'], {weak: true});
api.export('ActiveRoute');
api.addFiles('lib/activeroute.coffee');
api.addFiles('client/helpers.coffee', 'client');
});
Package.onTest(function(api) {
api.versionsFrom('1.0');
api.use([
'check',
'coffeescript',
'mike:mocha-package@0.5.7',
'practicalmeteor:chai@1.9.2_3',
'reactive-dict',
'underscore',
'zimme:active-route'
]);
api.addFiles('tests/lib/activeroute.coffee');
api.addFiles('tests/client/helpers.coffee', 'client');
});
| Package.describe({
git: 'https://github.com/zimme/meteor-active-route.git',
name: 'zimme:active-route',
summary: 'Active route helpers',
version: '2.1.0'
});
Package.onUse(function(api) {
api.versionsFrom('1.0');
api.use([
'check',
'coffeescript',
'reactive-dict',
'underscore'
]);
api.use([
'meteorhacks:flow-router@1.8.0',
'iron:router@1.0.0',
'templating'
], ['client', 'server'], {weak: true});
api.export('ActiveRoute');
api.addFiles('lib/activeroute.coffee');
api.addFiles('client/helpers.coffee', 'client');
});
Package.onTest(function(api) {
api.versionsFrom('1.0');
api.use([
'coffeescript',
'mike:mocha-package@0.5.7',
'practicalmeteor:chai@1.9.2_3',
'zimme:active-route'
]);
api.addFiles('tests/lib/activeroute.coffee');
api.addFiles('tests/client/helpers.coffee', 'client');
});
|
Add more tests for CodeCell | import React from 'react';
import { shallow, mount } from 'enzyme';
import Immutable from 'immutable';
import {expect} from 'chai';
import CodeCell from '../../../../src/notebook/components/cell/code-cell';
import * as commutable from 'commutable';
import { displayOrder, transforms } from 'transformime-react';
const sharedProps = { displayOrder, transforms };
describe('CodeCell', () => {
it('can be rendered', () => {
const cell = shallow(
<CodeCell cell={commutable.emptyCodeCell} {...sharedProps}
cellStatus={Immutable.Map({'outputHidden': false, 'inputHidden': false})}/>
);
expect(cell).to.not.be.null;
});
it('creates an editor', () => {
const cell = mount(
<CodeCell cell={commutable.emptyCodeCell} {...sharedProps}
cellStatus={Immutable.Map({'outputHidden': false, 'inputHidden': false})}/>
);
expect(cell.find('.input').length).to.be.greaterThan(0);
});
it('creates a pager', () => {
const cell = mount(
<CodeCell cell={commutable.emptyCodeCell} {...sharedProps}
cellStatus={Immutable.Map({'outputHidden': false, 'inputHidden': false})}
pagers={Immutable.Map({'content':
Immutable.Map({'data': Immutable.Map({'text/plain': 'one'})})})}/>
);
expect(cell.find('.pagers').length).to.be.greaterThan(0);
});
});
| import React from 'react';
import { shallow, mount } from 'enzyme';
import Immutable from 'immutable';
import {expect} from 'chai';
import CodeCell from '../../../../src/notebook/components/cell/code-cell';
import * as commutable from 'commutable';
import { displayOrder, transforms } from 'transformime-react';
const sharedProps = { displayOrder, transforms };
describe('CodeCell', () => {
it('can be rendered', () => {
const cell = shallow(
<CodeCell cell={commutable.emptyCodeCell} {...sharedProps}
cellStatus={Immutable.Map({'outputHidden': false, 'inputHidden': false})}/>
);
expect(cell).to.not.be.null;
});
it('creates an editor', () => {
const cell = mount(
<CodeCell cell={commutable.emptyCodeCell} {...sharedProps}
cellStatus={Immutable.Map({'outputHidden': false, 'inputHidden': false})}/>
);
expect(cell.find('.input').length).to.be.greaterThan(0);
});
});
|
Fix typo in renderer test | package renderer_test
import (
"testing"
"github.com/diyan/assimilator/testutil/fixture"
"github.com/stretchr/testify/assert"
)
func TestServerSideRenderer_Get(t *testing.T) {
client, factory := fixture.Setup(t)
defer fixture.TearDown(t)
factory.SaveOrganization(factory.MakeOrganization())
res, bodyStr, errs := client.Get("http://example.com/acme-team/").End()
assert.Nil(t, errs)
assert.Equal(t, 200, res.StatusCode)
assert.Contains(t, res.Header.Get("Content-Type"), "text/html")
assert.Contains(t, bodyStr, "<title>Sentry</title>", "Title should be rendered from sentry/layout.html template")
assert.Contains(t, bodyStr, "Sentry.routes", "React routes should be rendered from sentry/bases/react.html")
assert.InDelta(t, 3000, res.ContentLength, 1000, "server-side rendered page should be ~3KB in size")
}
| package renderer_test
import (
"testing"
"github.com/diyan/assimilator/testutil/fixture"
"github.com/stretchr/testify/assert"
)
func TestServerSideTemplateRenderer_Get(t *testing.T) {
client, factory := fixture.Setup(t)
defer fixture.TearDown(t)
factory.SaveOrganization(factory.MakeOrganization())
res, bodyStr, errs := client.Get("http://example.com//acme-team/").End()
assert.Nil(t, errs)
assert.Equal(t, 200, res.StatusCode)
assert.Contains(t, res.Header.Get("Content-Type"), "text/html")
assert.Contains(t, bodyStr, "<title>Sentry</title>", "Title should be rendered from sentry/layout.html template")
assert.Contains(t, bodyStr, "Sentry.routes", "React routes should be rendered from sentry/bases/react.html")
assert.InDelta(t, 3000, res.ContentLength, 1000, "server-side rendered page should be ~3KB in size")
}
|
Update example for NGINX parser | /*
* Copyright (C) DreamLab Onet.pl Sp. z o. o.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
var uriparser = require('../bin/uriparser'), url = "http://10.177.51.76:1337//example/dir/hi", matches;
for (var i = 0; i < 2000000; i++) {
matches = uriparser.parse(url, uriparser.Uri.PROTOCOL, uriparser.Engines.NGINX);
}
| /*
* Copyright (C) DreamLab Onet.pl Sp. z o. o.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
var uriparser = require('../bin/uriparser'), url = "http://10.177.51.76:1337//example/dir/hi", matches;
for (var i = 0; i < 2000000; i++) {
matches = uriparser.parse(url, uriparser.kAll, uriparser.eNgxParser);
}
|
Change URL of pull request so it's not altered by generator
* Fixes https://github.com/Automattic/underscores.me/issues/39
* Related to #808 | /**
* skip-link-focus-fix.js
*
* Helps with accessibility for keyboard only users.
*
* Learn more: https://git.io/vWdr2
*/
( function() {
var is_webkit = navigator.userAgent.toLowerCase().indexOf( 'webkit' ) > -1,
is_opera = navigator.userAgent.toLowerCase().indexOf( 'opera' ) > -1,
is_ie = navigator.userAgent.toLowerCase().indexOf( 'msie' ) > -1;
if ( ( is_webkit || is_opera || is_ie ) && document.getElementById && window.addEventListener ) {
window.addEventListener( 'hashchange', function() {
var id = location.hash.substring( 1 ),
element;
if ( ! ( /^[A-z0-9_-]+$/.test( id ) ) ) {
return;
}
element = document.getElementById( id );
if ( element ) {
if ( ! ( /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) ) {
element.tabIndex = -1;
}
element.focus();
}
}, false );
}
})();
| /**
* skip-link-focus-fix.js
*
* Helps with accessibility for keyboard only users.
*
* Learn more: https://github.com/Automattic/_s/pull/136
*/
( function() {
var is_webkit = navigator.userAgent.toLowerCase().indexOf( 'webkit' ) > -1,
is_opera = navigator.userAgent.toLowerCase().indexOf( 'opera' ) > -1,
is_ie = navigator.userAgent.toLowerCase().indexOf( 'msie' ) > -1;
if ( ( is_webkit || is_opera || is_ie ) && document.getElementById && window.addEventListener ) {
window.addEventListener( 'hashchange', function() {
var id = location.hash.substring( 1 ),
element;
if ( ! ( /^[A-z0-9_-]+$/.test( id ) ) ) {
return;
}
element = document.getElementById( id );
if ( element ) {
if ( ! ( /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) ) {
element.tabIndex = -1;
}
element.focus();
}
}, false );
}
})();
|
Add Second Shape Test for Layers Util | # Lint as: python3
"""Tests for spectral."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import layers
class LayersTest(tf.test.TestCase):
def test_conv_transpose_shape(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=1
)
outputs = conv_transpose(inputs)
self.assertShapeEqual(inputs, outputs)
def test_conv_transpose_shape_upscale(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=2
)
outputs = conv_transpose(inputs)
self.assertEqual((10, 10, 2), outputs.shape)
if __name__ == '__main__':
os.environ["CUDA_VISIBLE_DEVICES"] = ''
tf.test.main()
| # Lint as: python3
"""Tests for spectral."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import layers
class LayersTest(tf.test.TestCase):
def test_conv_transpose_shape(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=1
)
outputs = conv_transpose(inputs)
self.assertShapeEqual(inputs, outputs)
if __name__ == '__main__':
os.environ["CUDA_VISIBLE_DEVICES"] = ''
tf.test.main()
|
Make windowTint color with more opacity | const colors = {
main: '#023365',
background: '#EEF1F4',
clear: 'rgba(0,0,0,0)',
facebook: '#3b5998',
transparent: 'rgba(0,0,0,0)',
silver: '#F7F7F7',
steel: '#CCCCCC',
error: 'rgba(200, 0, 0, 0.8)',
ricePaper: 'rgba(255,255,255, 0.75)',
frost: '#D8D8D8',
cloud: 'rgba(200,200,200, 0.35)',
windowTint: 'rgba(0, 0, 0, 0.2)',
panther: '#161616',
charcoal: '#595959',
coal: '#2d2d2d',
bloodOrange: '#fb5f26',
snow: 'white',
ember: 'rgba(164, 0, 48, 0.5)',
fire: '#e73536',
drawer: 'rgba(30, 30, 29, 0.95)'
};
export default colors;
| const colors = {
main: '#023365',
background: '#EEF1F4',
clear: 'rgba(0,0,0,0)',
facebook: '#3b5998',
transparent: 'rgba(0,0,0,0)',
silver: '#F7F7F7',
steel: '#CCCCCC',
error: 'rgba(200, 0, 0, 0.8)',
ricePaper: 'rgba(255,255,255, 0.75)',
frost: '#D8D8D8',
cloud: 'rgba(200,200,200, 0.35)',
windowTint: 'rgba(0, 0, 0, 0.4)',
panther: '#161616',
charcoal: '#595959',
coal: '#2d2d2d',
bloodOrange: '#fb5f26',
snow: 'white',
ember: 'rgba(164, 0, 48, 0.5)',
fire: '#e73536',
drawer: 'rgba(30, 30, 29, 0.95)'
};
export default colors;
|
Clear welcome message after login
Note that this can't really be reversed, so once you login, you're stuck. Will fix, but something of note :/ | define([
'jquery',
'backbone',
'marionette',
'appbar/appbar.model',
'appbar/appbar.view',
'welcome/welcome.view'
], function ($, Backbone, Marionette, AppBarModel, AppBarView, WelcomeView) {
'use strict';
var AppView = Marionette.LayoutView.extend({
el: 'body',
regions: {
appbar : '#top',
main : '#primary'
initialize: function () {
this.radio = Backbone.Wreqr.radio.channel('global');
this.showChildView('appbar', new AppBarView({ model: new AppBarModel() }) );
this.renderMainView();
},
render: function () {
return this;
},
renderMainView: function () {
var self = this;
if(this.main && this.main.currentView)
this.getRegion('main').reset();
if(this.model.get('accounts').length === 0) {
this.radio.commands.setHandler('welcome:complete', function () {
self.renderMainView();
});
this.showChildView('main', new WelcomeView({model : this.model}) );
} else {
// TODO
}
},
setDeveloperMode: function () {
this.appbar.currentView.model.set('isDebug', true);
return this;
}
});
return AppView;
}); | define([
'jquery',
'backbone',
'marionette',
'appbar/appbar.model',
'appbar/appbar.view',
'welcome/welcome.view'
], function ($, Backbone, Marionette, AppBarModel, AppBarView, WelcomeView) {
'use strict';
var AppView = Marionette.LayoutView.extend({
el: 'body',
regions: {
appbar : '#top',
main : '#primary'
initialize: function () {
this.radio = Backbone.Wreqr.radio.channel('global');
this.showChildView('appbar', new AppBarView({ model: new AppBarModel() }) );
if(this.model.get('accounts').length === 0) {
this.showChildView('main', new WelcomeView({model : this.model}) );
}
},
render: function () {
return this;
},
setDeveloperMode: function () {
this.appbar.currentView.model.set('isDebug', true);
return this;
}
});
return AppView;
}); |
Set up DocumentCollectionCursor as an array-like object | /**
* @license
* Pipeline version @VERSION
* Copyright (c) 2011 Rob Griffiths (http://bytespider.eu)
* Pipeline is freely distributable under the terms of an MIT-style license.
*/
(function(){
function Pipeline() {}
Pipeline.prototype = {
createCollection: function (collection) {
this[collection] = new DocumentCollection();
return this[collection];
}
};
function DocumentCollection() {}
DocumentCollection.prototype = {
find: function () {},
insert: function () {},
update: function () {},
save: function () {},
remove: function () {},
};
function DocumentCollectionCursor() {}
DocumentCollectionCursor.prototype = [];
var extend = {
constructor: DocumentCollectionCursor,
toString: function () {return Array.prototype.join();},
join: undefined,
push: undefined,
pop: undefined,
concat: undefined,
splice: undefined,
shift: undefined,
unshift: undefined,
reverse: undefined,
every: undefined,
map: undefined,
some: undefined,
reduce: undefined,
reduceRight: undefined
};
for (var i in extend) {
DocumentCollectionCursor.prototype[i] = extend[i];
}
window['Pipeline'] = Pipeline;
})();
| /**
* @license
* Pipeline version @VERSION
* Copyright (c) 2011 Rob Griffiths (http://bytespider.eu)
* Pipeline is freely distributable under the terms of an MIT-style license.
*/
(function(){
function Pipeline() {
}
Pipeline.prototype = {
createCollection: function (collection) {
this[collection] = new DocumentCollection();
return this[collection];
}
};
function DocumentCollection() {}
DocumentCollection.prototype = {
find: function () {},
insert: function () {},
update: function () {},
save: function () {},
remove: function () {},
};
window['Pipeline'] = Pipeline;
})();
function obj() {
}
obj.prototype = [];
var prototype = {
constructor: obj,
toString: function () {return Array.prototype.join();},
join: undefined,
push: undefined,
pop: undefined,
concat: undefined,
splice: undefined,
shift: undefined,
unshift: undefined,
reverse: undefined,
every: undefined,
map: undefined,
some: undefined,
reduce: undefined,
reduceRight: undefined
};
for (var i in prototype) {
obj.prototype[i] = prototype[i];
}
var obj1 = new obj();
console.log(obj1);
|
Fix resize demo to work with updated Scatter plot | import candela from './../../src/candela';
import indexContent from './index.jade';
import 'javascript-detect-element-resize/detect-element-resize';
import './index.styl';
function showPage () {
[...document.getElementsByClassName('page')].forEach(el => {
el.classList.add('hidden');
});
let pageId = 'main';
if (window.location.hash.length > 1) {
pageId = window.location.hash.slice(1);
}
document.getElementById(pageId).classList.remove('hidden');
}
window.addEventListener('load', () => {
document.getElementsByTagName('body')[0].innerHTML = indexContent();
showPage();
window.addEventListener('hashchange', showPage, false);
let data = [];
for (let i = 0; i < 100; i += 1) {
data.push({x: Math.random(), y: Math.random()});
}
[...document.getElementsByClassName('vis-element')].forEach(el => {
let vis = new candela.components.Scatter(
el,
{
data,
x: 'x',
y: 'y'
}
);
vis.render();
window.addResizeListener(el, () => vis.render());
});
window.setInterval(() => {
document.getElementById('containing-table').style.width = (500 + Math.floor(Math.random() * 500)) + 'px';
}, 1000);
});
| import candela from './../../src/candela';
import indexContent from './index.jade';
import 'javascript-detect-element-resize/detect-element-resize';
import './index.styl';
function showPage () {
[...document.getElementsByClassName('page')].forEach(el => {
el.classList.add('hidden');
});
let pageId = 'main';
if (window.location.hash.length > 1) {
pageId = window.location.hash.slice(1);
}
document.getElementById(pageId).classList.remove('hidden');
}
window.addEventListener('load', () => {
document.getElementsByTagName('body')[0].innerHTML = indexContent();
showPage();
window.addEventListener('hashchange', showPage, false);
let data = [];
for (let i = 0; i < 100; i += 1) {
data.push({x: Math.random(), y: Math.random()});
}
[...document.getElementsByClassName('vis-element')].forEach(el => {
let vis = new candela.components.Scatter(
el,
data,
{
x: 'x',
y: 'y'
}
);
vis.render();
window.addResizeListener(el, () => vis.render());
});
window.setInterval(() => {
document.getElementById('containing-table').style.width = (500 + Math.floor(Math.random() * 500)) + 'px';
}, 1000);
});
|
Add option to count components | #!/usr/bin/env python
# -*- coding: utf8 -*-
import sys, os
import argparse
from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo
def main(argv=None):
parser = argparse.ArgumentParser(description='Print count of objects for a given collection.')
parser.add_argument('path', help="Nuxeo path to collection")
parser.add_argument('--pynuxrc', default='~/.pynuxrc-prod', help="rcfile for use with pynux utils")
parser.add_argument('--components', action='store_true', help="show counts for object components")
if argv is None:
argv = parser.parse_args()
dh = DeepHarvestNuxeo(argv.path, '', pynuxrc=argv.pynuxrc)
print "about to fetch objects for path {}".format(dh.path)
objects = dh.fetch_objects()
object_count = len(objects)
print "finished fetching objects. {} found".format(object_count)
if not argv.components:
return
print "about to iterate through objects and get components"
component_count = 0
for obj in objects:
components = dh.fetch_components(obj)
component_count = component_count + len(components)
print "finished fetching components. {} found".format(component_count)
print "Grand Total: {}".format(object_count + component_count)
if __name__ == "__main__":
sys.exit(main())
| #!/usr/bin/env python
# -*- coding: utf8 -*-
import sys, os
import argparse
from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo
def main(argv=None):
parser = argparse.ArgumentParser(description='Print count of objects for a given collection.')
parser.add_argument('path', help="Nuxeo path to collection")
parser.add_argument('--pynuxrc', default='~/.pynuxrc-prod', help="rcfile for use with pynux utils")
if argv is None:
argv = parser.parse_args()
dh = DeepHarvestNuxeo(argv.path, '', pynuxrc=argv.pynuxrc)
print "about to fetch objects for path {}".format(dh.path)
objects = dh.fetch_objects()
object_count = len(objects)
print "finished fetching objects. {} found".format(object_count)
print "about to iterate through objects and get components"
component_count = 0
for obj in objects:
components = dh.fetch_components(obj)
component_count = component_count + len(components)
print "finished fetching components. {} found".format(component_count)
print "Grand Total: {}".format(object_count + component_count)
if __name__ == "__main__":
sys.exit(main())
|
Fix unused import lint error
Change-Id: Ib72b049b4991e48b2ac9ffbc3c5585e676edf781 | // Copyright 2016 Google Inc. All Rights Reserved.
package com.google.copybara.util;
import com.google.devtools.build.lib.shell.AbnormalTerminationException;
import com.google.devtools.build.lib.shell.Command;
import com.google.devtools.build.lib.shell.CommandResult;
/**
* An exception that represents a program that did not exit with 0 exit code.
*
* <p>The reason for this class is that {@link Command#execute} doesn't populate {@link
* CommandResult#stderr} when throwing a {@link com.google.devtools.build.lib.shell.BadExitStatusException}
* exception. This class allows us to collect the error and store in this alternative exception.
*/
public class BadExitStatusWithOutputException extends AbnormalTerminationException {
private final CommandOutputWithStatus output;
BadExitStatusWithOutputException(Command command, CommandResult result, String message,
byte[] stdout, byte[] stderr) {
super(command, result, message);
this.output = new CommandOutputWithStatus(result.getTerminationStatus(), stdout, stderr);
}
public CommandOutputWithStatus getOutput() {
return output;
}
}
| // Copyright 2016 Google Inc. All Rights Reserved.
package com.google.copybara.util;
import com.google.common.base.Preconditions;
import com.google.devtools.build.lib.shell.AbnormalTerminationException;
import com.google.devtools.build.lib.shell.Command;
import com.google.devtools.build.lib.shell.CommandResult;
import java.nio.charset.StandardCharsets;
/**
* An exception that represents a program that did not exit with 0 exit code.
*
* <p>The reason for this class is that {@link Command#execute} doesn't populate {@link
* CommandResult#stderr} when throwing a {@link com.google.devtools.build.lib.shell.BadExitStatusException}
* exception. This class allows us to collect the error and store in this alternative exception.
*/
public class BadExitStatusWithOutputException extends AbnormalTerminationException {
private final CommandOutputWithStatus output;
BadExitStatusWithOutputException(Command command, CommandResult result, String message,
byte[] stdout, byte[] stderr) {
super(command, result, message);
this.output = new CommandOutputWithStatus(result.getTerminationStatus(), stdout, stderr);
}
public CommandOutputWithStatus getOutput() {
return output;
}
}
|
Use Coverage 3.7.1 so it passes on Python 3.2 | import setuptools
setuptools.setup(
name='ChatExchange6',
version='1.0',
url='https://github.com/ByteCommander/ChatExchange6',
packages=[
'chatexchange6'
],
install_requires=[
'beautifulsoup4>=4.3.2',
'requests>=2.2.1',
'websocket-client>=0.13.0',
# only for dev:
'coverage=3.7.1',
'epydoc>=3.0.1',
'httmock>=1.2.2',
'pytest-capturelog>=0.7',
'pytest-timeout>=0.3',
'pytest>=2.7.3',
'py>=1.4.29'
]
)
| import setuptools
setuptools.setup(
name='ChatExchange6',
version='1.0',
url='https://github.com/ByteCommander/ChatExchange6',
packages=[
'chatexchange6'
],
install_requires=[
'beautifulsoup4>=4.3.2',
'requests>=2.2.1',
'websocket-client>=0.13.0',
# only for dev:
'coverage>=3.7.1',
'epydoc>=3.0.1',
'httmock>=1.2.2',
'pytest-capturelog>=0.7',
'pytest-timeout>=0.3',
'pytest>=2.7.3',
'py>=1.4.29'
]
)
|
fix(filter-options): Allow --private to be configured from file | "use strict";
const dedent = require("dedent");
module.exports = filterOptions;
function filterOptions(yargs) {
// Only for 'run', 'exec', 'clean', 'ls', and 'bootstrap' commands
const opts = {
scope: {
describe: "Include only packages with names matching the given glob.",
type: "string",
},
ignore: {
describe: "Exclude packages with names matching the given glob.",
type: "string",
},
private: {
describe: "Include private packages.\nPass --no-private to exclude private packages.",
type: "boolean",
defaultDescription: "true",
},
since: {
describe: dedent`
Only include packages that have been updated since the specified [ref].
If no ref is passed, it defaults to the most-recent tag.
`,
type: "string",
},
"include-filtered-dependents": {
describe: dedent`
Include all transitive dependents when running a command
regardless of --scope, --ignore, or --since.
`,
type: "boolean",
},
"include-filtered-dependencies": {
describe: dedent`
Include all transitive dependencies when running a command
regardless of --scope, --ignore, or --since.
`,
type: "boolean",
},
};
return yargs.options(opts).group(Object.keys(opts), "Filter Options:");
}
| "use strict";
const dedent = require("dedent");
module.exports = filterOptions;
function filterOptions(yargs) {
// Only for 'run', 'exec', 'clean', 'ls', and 'bootstrap' commands
const opts = {
scope: {
describe: "Include only packages with names matching the given glob.",
type: "string",
},
ignore: {
describe: "Exclude packages with names matching the given glob.",
type: "string",
},
private: {
describe: "Include private packages.\nPass --no-private to exclude private packages.",
type: "boolean",
default: true,
},
since: {
describe: dedent`
Only include packages that have been updated since the specified [ref].
If no ref is passed, it defaults to the most-recent tag.
`,
type: "string",
},
"include-filtered-dependents": {
describe: dedent`
Include all transitive dependents when running a command
regardless of --scope, --ignore, or --since.
`,
type: "boolean",
},
"include-filtered-dependencies": {
describe: dedent`
Include all transitive dependencies when running a command
regardless of --scope, --ignore, or --since.
`,
type: "boolean",
},
};
return yargs.options(opts).group(Object.keys(opts), "Filter Options:");
}
|
Add reference to foaf spec. | /*
* JBoss, Home of Professional Open Source
* Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
*/
package org.searchisko.doap.model;
import com.viceversatech.rdfbeans.annotations.RDF;
import com.viceversatech.rdfbeans.annotations.RDFBean;
import com.viceversatech.rdfbeans.annotations.RDFNamespaces;
import java.net.URI;
/**
* FOAF Person model.
* See <a href="http://xmlns.com/foaf/spec/">http://xmlns.com/foaf/spec/</a>.
*
* @author Lukas Vlcek (lvlcek@redhat.com)
*/
@RDFNamespaces({
"foaf = http://xmlns.com/foaf/0.1/"
})
@RDFBean("foaf:Person")
public class Person {
private String name;
private URI mbox;
/**
* See <a href="http://xmlns.com/foaf/spec/#term_name">foaf:name</a>
*
* @return name value
*/
@RDF("foaf:name")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
/**
* See <a href="http://xmlns.com/foaf/spec/#term_mbox">foaf:mbox</a>
*
* @return mbox valueAdd
*/
@RDF("foaf:mbox")
public URI getMbox() {
return this.mbox;
}
public void setMbox(URI mbox) {
this.mbox = mbox;
}
}
| /*
* JBoss, Home of Professional Open Source
* Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
*/
package org.searchisko.doap.model;
import com.viceversatech.rdfbeans.annotations.RDF;
import com.viceversatech.rdfbeans.annotations.RDFBean;
import com.viceversatech.rdfbeans.annotations.RDFNamespaces;
import java.net.URI;
/**
* FOAF Person model.
*
* @author Lukas Vlcek (lvlcek@redhat.com)
*/
@RDFNamespaces({
"foaf = http://xmlns.com/foaf/0.1/"
})
@RDFBean("foaf:Person")
public class Person {
private String name;
private URI mbox;
@RDF("foaf:name")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@RDF("foaf:mbox")
public URI getMbox() {
return this.mbox;
}
public void setMbox(URI mbox) {
this.mbox = mbox;
}
}
|
Refactor routes: use ::match() so that multiple http verbs that points to the same controller only uses one line | <?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::match(['get', 'post'], '/', 'HomeController@getIndex');
Route::match(['get', 'post'], '/earthquakes', 'HomeController@getEarthquakeHistory');
Route::get('/earthquakes/{id}', 'HomeController@getEarthquakeDetails');
Route::match(['get', 'post'], '/earthquake-heatmap', 'HomeController@getHeatmap');
Route::match(['get', 'post'], '/earthquake-graphs-charts', 'HomeController@getGraphCharts');
Route::get('/earthquake-101', 'HomeController@getEarthquake101');
Route::get('/earthquake-hotlines', 'HomeController@getHotlines');
Route::get('/about', 'HomeController@getAbout');
Route::get('/test', 'HomeController@getTest');
Route::prefix('amp')->group(function () {
Route::get('/', 'HomeController@getIndex')
->name('amp-homepage');
});
| <?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'HomeController@getIndex');
Route::post('/', 'HomeController@getIndex');
Route::get('/earthquakes', 'HomeController@getEarthquakeHistory');
Route::post('/earthquakes', 'HomeController@getEarthquakeHistory');
Route::get('/earthquakes/{id}', 'HomeController@getEarthquakeDetails');
Route::get('/earthquake-heatmap', 'HomeController@getHeatmap');
Route::post('/earthquake-heatmap', 'HomeController@getHeatmap');
Route::get('/earthquake-graphs-charts', 'HomeController@getGraphCharts');
Route::post('/earthquake-graphs-charts', 'HomeController@getGraphCharts');
Route::get('/earthquake-101', 'HomeController@getEarthquake101');
Route::get('/earthquake-hotlines', 'HomeController@getHotlines');
Route::get('/about', 'HomeController@getAbout');
Route::get('/test', 'HomeController@getTest');
Route::prefix('amp')->group(function () {
Route::get('/', 'HomeController@getIndex')
->name('amp-homepage');
}); |
Change logspew nora back to 2g of memory
Seems to take longer to respond with only 1g, which sometimes causes a
gateway timeout
Signed-off-by: David Morhovich <1d2e5394c2c3adc275fab845f5e23fc4a9634ec0@pivotal.io> | package wats
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gexec"
"github.com/cloudfoundry-incubator/cf-test-helpers/cf"
"github.com/cloudfoundry-incubator/cf-test-helpers/helpers"
)
var _ = Describe("An application printing a bunch of output", func() {
BeforeEach(func() {
Eventually(pushNoraWithOptions(appName, 1, "2g"), CF_PUSH_TIMEOUT).Should(Succeed())
enableDiego(appName)
Eventually(runCf("start", appName), CF_PUSH_TIMEOUT).Should(Succeed())
})
AfterEach(func() {
Eventually(cf.Cf("logs", appName, "--recent")).Should(Exit())
Eventually(cf.Cf("delete", appName, "-f")).Should(Exit(0))
})
It("doesn't die when printing 32MB", func() {
beforeId := helpers.CurlApp(appName, "/id")
Expect(helpers.CurlAppWithTimeout(appName, "/logspew/32000", DEFAULT_TIMEOUT)).
To(ContainSubstring("Just wrote 32000 kbytes to the log"))
Consistently(func() string {
return helpers.CurlApp(appName, "/id")
}, "10s").Should(Equal(beforeId))
})
})
| package wats
import (
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gexec"
"github.com/cloudfoundry-incubator/cf-test-helpers/cf"
"github.com/cloudfoundry-incubator/cf-test-helpers/helpers"
)
var _ = Describe("An application printing a bunch of output", func() {
BeforeEach(func() {
Eventually(pushNora(appName), CF_PUSH_TIMEOUT).Should(Succeed())
enableDiego(appName)
Eventually(runCf("start", appName), CF_PUSH_TIMEOUT).Should(Succeed())
})
AfterEach(func() {
Eventually(cf.Cf("logs", appName, "--recent")).Should(Exit())
Eventually(cf.Cf("delete", appName, "-f")).Should(Exit(0))
})
It("doesn't die when printing 32MB", func() {
beforeId := helpers.CurlApp(appName, "/id")
loggingTimeout := 2 * time.Minute
Expect(helpers.CurlAppWithTimeout(appName, "/logspew/32000", loggingTimeout)).
To(ContainSubstring("Just wrote 32000 kbytes to the log"))
Consistently(func() string {
return helpers.CurlApp(appName, "/id")
}, "10s").Should(Equal(beforeId))
})
})
|
Update user table seeder to give proper MM/DD/YYYY string. | <?php
class UsersTableSeeder extends Seeder {
public function run()
{
$faker = Faker\Factory::create();
User::truncate();
User::create([
'first_name' => 'Dave',
'email' => 'dfurnes@dosomething.org',
'password' => 'tops3cret',
])->assignRole(1);
User::create([
'first_name' => 'Andrea',
'email' => 'agaither@dosomething.org',
'password' => 'tops3cret',
])->assignRole(1);
foreach(range(1,25) as $index) {
User::create([
'first_name' => $faker->firstName,
'email' => $faker->unique()->safeEmail,
'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
]);
}
foreach(range(1,25) as $index) {
User::create([
'first_name' => $faker->firstName,
'phone' => $faker->unique()->phoneNumber,
'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
]);
}
}
}
| <?php
class UsersTableSeeder extends Seeder {
public function run()
{
$faker = Faker\Factory::create();
User::truncate();
User::create([
'first_name' => 'Dave',
'email' => 'dfurnes@dosomething.org',
'password' => 'tops3cret',
])->assignRole(1);
User::create([
'first_name' => 'Andrea',
'email' => 'agaither@dosomething.org',
'password' => 'tops3cret',
])->assignRole(1);
foreach(range(1,25) as $index) {
User::create([
'first_name' => $faker->firstName,
'email' => $faker->unique()->safeEmail,
'birthdate' => $faker->dateTime('now'),
]);
}
foreach(range(1,25) as $index) {
User::create([
'first_name' => $faker->firstName,
'phone' => $faker->unique()->phoneNumber,
'birthdate' => $faker->dateTime('now'),
]);
}
}
}
|
Fix the keystone app name and brand. | var config = require('./config.json');
var keystone = require('keystone');
keystone.init({
'name': 'dredd',
'brand': 'Dredd - "I am the Law!"',
'favicon': 'public/favicon.ico',
'view engine': 'jade',
'wysiwyg images': true,
'wysiwyg menubar': true,
'wysiwyg additional plugins': 'table',
'mongo' : config.mongo.uri,
// 'auto update': true,
'session': true,
'auth': true,
'user model': 'User',
'cookie secret': '0T=?C|`ed@N&,<!)BQ<Nh/7+e3TeO"$^cl{7Z$7i@mfnybN1{*H.ETQ=(->75^MB'
});
keystone.import('models');
keystone.set('locals', {
// _: require('underscore'),
env: keystone.get('env'),
utils: keystone.utils,
editable: keystone.content.editable
});
keystone.set('routes', require('./routes'));
keystone.set('nav', {
// 'bills': 'bills'
});
keystone.start();
| var config = require('./config.json');
var keystone = require('keystone');
keystone.init({
'name': 'anapi',
'brand': 'anapi',
'favicon': 'public/favicon.ico',
'view engine': 'jade',
'wysiwyg images': true,
'wysiwyg menubar': true,
'wysiwyg additional plugins': 'table',
'mongo' : config.mongo.uri,
// 'auto update': true,
'session': true,
'auth': true,
'user model': 'User',
'cookie secret': '0T=?C|`ed@N&,<!)BQ<Nh/7+e3TeO"$^cl{7Z$7i@mfnybN1{*H.ETQ=(->75^MB'
});
keystone.import('models');
keystone.set('locals', {
// _: require('underscore'),
env: keystone.get('env'),
utils: keystone.utils,
editable: keystone.content.editable
});
keystone.set('routes', require('./routes'));
keystone.set('nav', {
// 'bills': 'bills'
});
keystone.start();
|
Add blank line before namespace declaration | <?php
/**
* @title Import Class
* @desc Generic Importer Class for the pH7CMS.
*
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2017, 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 / Install / Class
* @version 0.1
*/
namespace PH7;
defined('PH7') or exit('Restricted access');
abstract class Import
{
protected $db;
public function __construct()
{
$this->db = Db::getInstance();
}
}
| <?php
/**
* @title Import Class
* @desc Generic Importer Class for the pH7CMS.
*
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2017, 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 / Install / Class
* @version 0.1
*/
namespace PH7;
defined('PH7') or exit('Restricted access');
abstract class Import
{
protected $db;
public function __construct()
{
$this->db = Db::getInstance();
}
}
|
Make server tests work again
Change-Id: Ie0097cef628ef013579067443d4a52be049cf1da | /*
* Copyright 2000-2014 Vaadin Ltd.
*
* 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.vaadin.tests.integration;
import java.io.IOException;
import org.junit.Test;
import com.vaadin.testbench.elements.TableElement;
/**
* Base class for servlet integration tests. Automatically prepends "/demo" to
* the deployment path
*
* @author Vaadin Ltd
*/
public abstract class AbstractServletIntegrationTest extends
AbstractIntegrationTest {
@Test
public void runTest() throws IOException, AssertionError {
openTestURL();
compareScreen("initial");
$(TableElement.class).first().getCell(0, 1).click();
compareScreen("finland");
}
@Override
protected String getDeploymentPath(Class<?> uiClass) {
return "/demo" + super.getDeploymentPath(uiClass);
}
}
| /*
* Copyright 2000-2014 Vaadin Ltd.
*
* 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.vaadin.tests.integration;
import java.io.IOException;
import org.junit.Test;
import com.vaadin.testbench.elements.TableElement;
/**
* Base class for servlet integration tests. Automatically prepends "/demo" to
* the deployment path
*
* @author Vaadin Ltd
*/
public abstract class AbstractServletIntegrationTest extends
AbstractIntegrationTest {
@Test
public void runTest() throws IOException, AssertionError {
openTestURL();
compareScreen("initial");
$(TableElement.class).first().getCell(0, 1).click();
compareScreen("finland");
}
@Override
protected String getDeploymentPath() {
return "/demo" + super.getDeploymentPath();
}
}
|
Add support for label prop | import React, { PropTypes } from 'react';
import cx from 'classnames';
import Background from './background';
import Icon from './icon';
import Mask from './mask';
import { keyFor } from './networks';
import { socialIcon, socialContainer, socialSvg } from './styles';
function getNetworkKey(props) {
return props.network || keyFor(props.url);
}
function SocialIcon(props) {
const { url, network, color, className, label, ...rest } = props;
const networkKey = getNetworkKey({ url, network });
return (
<a {...rest}
href={url}
target="_blank"
rel="noopener"
className={cx('social-icon', className)}
style={{ ...socialIcon, ...props.style }}
aria-label={label}>
<div className="social-container" style={socialContainer} >
<svg className="social-svg" style={socialSvg} viewBox="0 0 64 64">
<Background />
<Icon networkKey={networkKey} />
<Mask networkKey={networkKey} color={color} />
</svg>
</div>
</a>
);
}
SocialIcon.propTypes = {
className: PropTypes.string,
color: PropTypes.string,
label: PropTypes.string,
network: PropTypes.string,
url: PropTypes.string,
};
export default SocialIcon;
| import React, { PropTypes } from 'react';
import cx from 'classnames';
import Background from './background';
import Icon from './icon';
import Mask from './mask';
import { keyFor } from './networks';
import { socialIcon, socialContainer, socialSvg } from './styles';
function getNetworkKey(props) {
return props.network || keyFor(props.url);
}
function SocialIcon(props) {
const { url, network, color, className, ...rest } = props;
const networkKey = getNetworkKey({ url, network });
return (
<a {...rest}
href={url}
target="_blank"
rel="noopener"
className={cx('social-icon', className)}
style={{ ...socialIcon, ...props.style }}>
<div className="social-container" style={socialContainer} >
<svg className="social-svg" style={socialSvg} viewBox="0 0 64 64">
<Background />
<Icon networkKey={networkKey} />
<Mask networkKey={networkKey} color={color} />
</svg>
</div>
</a>
);
}
SocialIcon.propTypes = {
className: PropTypes.string,
color: PropTypes.string,
network: PropTypes.string,
url: PropTypes.string,
};
export default SocialIcon;
|
Fix usage from multiple tabs | var nativePort = null; // Connection with native app
var contentPorts = new Map();
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "webcard");
contentPorts.set(port.sender.tab.id, port);
console.log("Connected from tab: " + port.sender.tab.id);
if (!nativePort)
connectNative();
port.onMessage.addListener(function(msg) {
// Add tab id to the message UID
msg.i = port.sender.tab.id + '.' + msg.i;
console.log("received " + msg + " (tab " + port.sender.tab.id + ")");
nativePort.postMessage(msg);
});
});
function onNativeMessage(msg) {
console.log("Received native message: " + JSON.stringify(msg));
// Extract tab id from identifier and restore the original correlation
// TODO "events are passed to active tab"
console.log(contentPorts);
let destination = msg.i.match(/(\d+)\.(.+)/);
let port = contentPorts.get(parseInt(destination[1]));
msg.i = destination[2];
console.log(port);
port.postMessage(msg);
}
function onDisconnected() {
console.log("Failed to connect: " + chrome.runtime.lastError.message);
nativePort = null;
}
function connectNative() {
var hostName = "org.cardid.webcard.native";
nativePort = chrome.runtime.connectNative(hostName);
console.log("Connected to native messaging host");
nativePort.onMessage.addListener(onNativeMessage);
nativePort.onDisconnect.addListener(onDisconnected);
}
| var tab = null;
var nativePort = null;
var contentPort = null;
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "webcard");
if (!contentPort)
contentPort = port;
console.log("Connected from tab: " + port.sender.tab.id);
connectNative();
port.onMessage.addListener(function(msg) {
console.log("received " + msg + " (tab " + port.sender.tab.id + ")");
nativePort.postMessage(msg);
});
});
function onNativeMessage(message) {
console.log("Received native message: " + JSON.stringify(message));
contentPort.postMessage(message);
}
function onDisconnected() {
console.log("Failed to connect: " + chrome.runtime.lastError.message);
nativePort = null;
}
function connectNative() {
var hostName = "org.cardid.webcard.native";
nativePort = chrome.runtime.connectNative(hostName);
console.log("Connected to native messaging host");
nativePort.onMessage.addListener(onNativeMessage);
nativePort.onDisconnect.addListener(onDisconnected);
}
|
Update headers after sign_out response | import fetch from 'utils/fetch';
import { getSettings } from 'models/settings';
import parseResponse from 'utils/parseResponse';
import { updateHeaders } from 'actions/headers';
export const SIGN_OUT = 'SIGN_OUT';
export const SIGN_OUT_COMPLETE = 'SIGN_OUT_COMPLETE';
export const SIGN_OUT_ERROR = 'SIGN_OUT_ERROR';
function signOutStart() {
return { type: SIGN_OUT };
}
function signOutComplete() {
return { type: SIGN_OUT_COMPLETE };
}
function signOutError(errors) {
return { type: SIGN_OUT_ERROR, errors };
}
export function signOut() {
return (dispatch, getState) => {
const { backend } = getSettings(getState());
dispatch(signOutStart());
if (!backend.signOutPath) {
dispatch(updateHeaders());
dispatch(signOutComplete());
return Promise.resolve();
}
return dispatch(fetch(backend.signOutPath, { method: 'delete' }))
.then(parseResponse)
.then(() => {
dispatch(updateHeaders());
dispatch(signOutComplete());
return Promise.resolve();
})
.catch((er) => {
dispatch(updateHeaders());
dispatch(signOutError(er));
return Promise.reject(er);
});
};
}
| import fetch from 'utils/fetch';
import { getSettings } from 'models/settings';
import parseResponse from 'utils/parseResponse';
import { updateHeaders } from 'actions/headers';
export const SIGN_OUT = 'SIGN_OUT';
export const SIGN_OUT_COMPLETE = 'SIGN_OUT_COMPLETE';
export const SIGN_OUT_ERROR = 'SIGN_OUT_ERROR';
function signOutStart() {
return { type: SIGN_OUT };
}
function signOutComplete() {
return { type: SIGN_OUT_COMPLETE };
}
function signOutError(errors) {
return { type: SIGN_OUT_ERROR, errors };
}
export function signOut() {
return (dispatch, getState) => {
const { backend } = getSettings(getState());
dispatch(signOutStart());
dispatch(updateHeaders());
if (!backend.signOutPath) {
dispatch(signOutComplete());
return Promise.resolve();
}
return dispatch(fetch(backend.signOutPath, { method: 'delete' }))
.then(parseResponse)
.then(() => {
dispatch(signOutComplete());
return Promise.resolve();
})
.catch((er) => {
dispatch(signOutError(er));
return Promise.reject(er);
});
};
}
|
Fix things the linter doesn't like | module.exports = {
commands: {
random: {
help: 'Selects a random choice or number',
command: function (bot, msg) {
if (msg.args.length > 2) {
msg.args.shift()
return msg.args[Math.floor(Math.random() * msg.args.length)]
} else if (msg.args.length === 2) {
var res = Math.floor(Math.random() * Math.floor(msg.args[1]))
if (!isNaN(res)) {
return res
}
}
return 'Usage: (<number>|<choice 1> … <choice n>)'
}
},
coin: {
help: 'Flips a coin',
command: function () {
var faces = ['Heads!', 'Tails!']
return faces[Math.floor(Math.random() * faces.length)]
}
}
}
}
| module.exports = {
commands: {
random: {
help: 'Selects a random choice or number',
command: function (bot, msg) {
if (msg.args.length > 2) {
msg.args.shift()
return msg.args[Math.floor(Math.random() * msg.args.length)]
} else if (msg.args.length === 2) {
var res = Math.floor(Math.random() * Math.floor(msg.args[1]))
if (!isNaN(res)) {
return res
}
}
return 'Usage: (<number>|<choice 1> … <choice n>)'
}
},
coin: {
help: 'Flips a coin',
command: function (bot, msg) {
var faces = ["Heads!", "Tails!"]
return faces[Math.floor(Math.random() * faces.length)]
}
}
}
}
|
Fix typo in loging page causing fatal error
Fix typo in loging page causing fatal error
- Close `?>`
Former-commit-id: 483240697e8b609fed1aaeba50bb140c0505287b | <?php defined('C5_EXECUTE') or die('Access denied.');
$form = Loader::helper('form');
?>
<div class='row'>
<div class='span5'>
<div class='control-group'>
<label class='control-label' for="uName">
<?=USER_REGISTRATION_WITH_EMAIL_ADDRESS?t('Email Address'):t('Username')?>
</label>
<div class='controls'>
<?=$form->text('uName')?>
</div>
</div>
<div class='control-group'>
<label class='control-label' for="uPassword">
<?=t('Password')?>
</label>
<div class='controls'>
<?=$form->password('uPassword')?>
</div>
</div>
</div>
<?=$form->hidden('rcID', $rcID); ?>
<div class='span3 offset1'>
<label class='checkbox'><?=$form->checkbox('uMaintainLogin',1)?> <?=t('Remain logged in to website.')?></label>
<div class="help-block"><a href="<?=View::url('/login', 'concrete', 'forgot_password')?>"><?=t('Forgot Password?')?></a></div>
</div>
</div>
<div class='actions'>
<button class='btn primary'><?=t('Sign In')?></button>
</div>
| <?php defined('C5_EXECUTE') or die('Access denied.');
$form = Loader::helper('form');
?>
<div class='row'>
<div class='span5'>
<div class='control-group'>
<label class='control-label' for="uName">
<?=USER_REGISTRATION_WITH_EMAIL_ADDRESS?t('Email Address'):t('Username')?>
</label>
<div class='controls'>
<?=$form->text('uName')?>
</div>
</div>
<div class='control-group'>
<label class='control-label' for="uPassword">
<?=t('Password')?>
</label>
<div class='controls'>
<?=$form->password('uPassword')?>
</div>
</div>
</div>
<?=$form->hidden('rcID', $rcID); ?>
<div class='span3 offset1'>
<label class='checkbox'><?=$form->checkbox('uMaintainLogin',1)?> <?=t('Remain logged in to website.')?></label>
<div class="help-block"><a href="<?=View::url('/login', 'concrete', 'forgot_password')?>"><?=t('Forgot Password?')?></a></div>
</div>
</div>
<div class='actions'>
<button class='btn primary'><?=t('Sign In')</button>
</div>
|
Fix up missing newlines at eof | /* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.payments;
/**
* Exception thrown when something went wrong with in-app billing.
* An IabException has an associated IabResult (an error).
* To get the IAB result that caused this exception to be thrown,
* call {@link #getResult()}.
*/
public class IabException extends Exception {
IabResult mResult;
public IabException(IabResult r) {
this(r, null);
}
public IabException(int response, String message) {
this(new IabResult(response, message));
}
public IabException(IabResult r, Exception cause) {
super(r.getMessage(), cause);
mResult = r;
}
public IabException(int response, String message, Exception cause) {
this(new IabResult(response, message), cause);
}
/** Returns the IAB result (error) that this exception signals. */
public IabResult getResult() { return mResult; }
}
| /* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.payments;
/**
* Exception thrown when something went wrong with in-app billing.
* An IabException has an associated IabResult (an error).
* To get the IAB result that caused this exception to be thrown,
* call {@link #getResult()}.
*/
public class IabException extends Exception {
IabResult mResult;
public IabException(IabResult r) {
this(r, null);
}
public IabException(int response, String message) {
this(new IabResult(response, message));
}
public IabException(IabResult r, Exception cause) {
super(r.getMessage(), cause);
mResult = r;
}
public IabException(int response, String message, Exception cause) {
this(new IabResult(response, message), cause);
}
/** Returns the IAB result (error) that this exception signals. */
public IabResult getResult() { return mResult; }
} |
Fix `migrate:reset` args as it doesn't accept --step | <?php
declare(strict_types=1);
namespace Rinvex\Tags\Console\Commands;
use Illuminate\Console\Command;
class RollbackCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'rinvex:rollback:tags {--force : Force the operation to run when in production.}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Rollback Rinvex Tags Tables.';
/**
* Execute the console command.
*
* @return void
*/
public function handle(): void
{
$this->alert($this->description);
if (file_exists($path = 'database/migrations/rinvex/laravel-tags')) {
$this->call('migrate:reset', [
'--path' => $path,
'--force' => $this->option('force'),
]);
} else {
$this->warn('No migrations found! Consider publish them first: <fg=green>php artisan rinvex:publish:tags</>');
}
$this->line('');
}
}
| <?php
declare(strict_types=1);
namespace Rinvex\Tags\Console\Commands;
use Illuminate\Console\Command;
class RollbackCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'rinvex:rollback:tags {--force : Force the operation to run when in production.}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Rollback Rinvex Tags Tables.';
/**
* Execute the console command.
*
* @return void
*/
public function handle(): void
{
$this->alert($this->description);
if (file_exists($path = 'database/migrations/rinvex/laravel-tags')) {
$this->call('migrate:reset', [
'--step' => true,
'--path' => $path,
'--force' => $this->option('force'),
]);
} else {
$this->warn('No migrations found! Consider publish them first: <fg=green>php artisan rinvex:publish:tags</>');
}
$this->line('');
}
}
|
[ddOnlineStorePlugin] Change configure to setup method
git-svn-id: 8b8afaa04106040b671d0ed3b268285890208be0@33046 ee427ae8-e902-0410-961c-c3ed070cd9f9 | <?php
/**
* PluginProductCategory form.
*
* @package ##PROJECT_NAME##
* @subpackage form
* @author ##AUTHOR_NAME##
* @version SVN: $Id: sfDoctrineFormPluginTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
*/
abstract class PluginProductCategoryForm extends BaseProductCategoryForm
{
public function setup()
{
parent::setup();
$this->useFields(array(
'id', 'name', 'description'
));
}
protected function doSave($con = null)
{
parent::doSave($con);
if($this->isNew())
{
$node = $this->object->getNode();
$parent = $this->object->getTable()->getTree()->fetchRoot();
if($parent)
{
$method = ($node->isValidNode() ? 'move' : 'insert') . 'AsLastChildOf';
$node->$method($parent); //calls $this->object->save internally
}
}
}
}
| <?php
/**
* PluginProductCategory form.
*
* @package ##PROJECT_NAME##
* @subpackage form
* @author ##AUTHOR_NAME##
* @version SVN: $Id: sfDoctrineFormPluginTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
*/
abstract class PluginProductCategoryForm extends BaseProductCategoryForm
{
public function configure()
{
parent::setup();
$this->useFields(array(
'id', 'name', 'description'
));
}
protected function doSave($con = null)
{
parent::doSave($con);
if($this->isNew())
{
$node = $this->object->getNode();
$parent = $this->object->getTable()->getTree()->fetchRoot();
if($parent)
{
$method = ($node->isValidNode() ? 'move' : 'insert') . 'AsLastChildOf';
$node->$method($parent); //calls $this->object->save internally
}
}
}
}
|
Revert "Use style from the original node, not the clone" | export default function getCloneDimensions(node, options) {
const { parentNode } = node
const context = document.createElement('div')
const clone = node.cloneNode(true)
const style = getComputedStyle(clone)
let rect = {}
// give the node some context to measure off of
// no height and hidden overflow hide node copy
context.style.height = 0
context.style.overflow = 'hidden'
// clean up any attributes that might cause a conflict with the original node
// i.e. inputs that should focus or submit data
clone.setAttribute('id', '')
clone.setAttribute('name', '')
// set props to get a true dimension calculation
clone.style.display = options.display || style.getPropertyValue('display')
if (style.getPropertyValue('width') !== '') {
clone.style.width = 'auto'
}
if (style.getPropertyValue('height') !== '') {
clone.style.height = 'auto'
}
// append copy to context
context.appendChild(clone)
// append context to DOM so we can measure
parentNode.appendChild(context)
// get accurate width and height
rect = clone.getBoundingClientRect()
// destroy clone
parentNode.removeChild(context)
return rect
}
| export default function getCloneDimensions(node, options) {
const { parentNode } = node
const context = document.createElement('div')
const clone = node.cloneNode(true)
const style = getComputedStyle(node)
let rect = {}
// give the node some context to measure off of
// no height and hidden overflow hide node copy
context.style.height = 0
context.style.overflow = 'hidden'
// clean up any attributes that might cause a conflict with the original node
// i.e. inputs that should focus or submit data
clone.setAttribute('id', '')
clone.setAttribute('name', '')
// set props to get a true dimension calculation
clone.style.display = options.display || style.getPropertyValue('display')
if (style.getPropertyValue('width') !== '') {
clone.style.width = 'auto'
}
if (style.getPropertyValue('height') !== '') {
clone.style.height = 'auto'
}
// append copy to context
context.appendChild(clone)
// append context to DOM so we can measure
parentNode.appendChild(context)
// get accurate width and height
rect = clone.getBoundingClientRect()
// destroy clone
parentNode.removeChild(context)
return rect
}
|
Add clearing if not recording and remove useless member | import configparser
import time
import RPi.GPIO as GPIO
from client import MumbleClient
class InterCom:
def __init__(self):
config = configparser.ConfigParser()
config.read('intercom.ini')
self.mumble_client = MumbleClient(config['mumbleclient'])
self.exit = False
if config['general']['gpiotype'] == 'BCM':
GPIO.setmode(GPIO.BCM)
self.button = int(config['general']['button'])
GPIO.setup(self.button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def run(self):
while not self.exit:
if GPIO.input(self.button):
self.mumble_client.send_input_audio()
else:
self.mumble_client.clear_input()
if __name__ == '__main__':
try:
InterCom().run()
except Exception as e:
raise e
finally:
GPIO.cleanup()
| import configparser
import time
import RPi.GPIO as GPIO
from client import MumbleClient
class InterCom:
def __init__(self):
config = configparser.ConfigParser()
config.read('intercom.ini')
self.mumble_client = MumbleClient(config['mumbleclient'])
self.exit = False
self.send_input = False
if config['general']['gpiotype'] == 'BCM':
GPIO.setmode(GPIO.BCM)
self.button = int(config['general']['button'])
GPIO.setup(self.button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def run(self):
while not self.exit:
if GPIO.input(self.button):
self.mumble_client.send_input_audio()
if __name__ == '__main__':
try:
InterCom().run()
except Exception as e:
raise e
finally:
GPIO.cleanup()
|
Use the `alias` function from the computed module | import Mixin from '@ember/object/mixin';
import { get } from '@ember/object';
import { alias } from '@ember/object/computed';
import { isPresent } from '@ember/utils';
export default Mixin.create({
/*
* Default namespace for application
* container keys.
*
* @type {String}
*/
namespace: alias('config.namespace'),
/*
* Prepend the namespace to the key
* before using it as a storage
* identifier.
*
* @method buildNamespace
*
* @param {String} key
* A string to prepend a namespace onto.
*
* @return {String}
* A namespaced key identifer.
*/
buildNamespace(key) {
const namespace = get(this, 'namespace');
return isPresent(namespace) ? `${namespace}:${key}` : `${key}`;
},
/*
* Determine whether the key has been
* previously namespaced.
*
* @method isNamespacedKey
*
* @param {String} key
* A namespaced key
*
* @return {Boolean}
* True if the key was previously namespaced, otherwise false.
*/
isNamespacedKey(key) {
return `${key}`.indexOf(this.buildNamespace('')) === 0;
}
});
| import Mixin from '@ember/object/mixin';
import { computed, get } from '@ember/object';
import { isPresent } from '@ember/utils';
export default Mixin.create({
/*
* Default namespace for application
* container keys.
*
* @type {String}
*/
namespace: computed.alias('config.namespace'),
/*
* Prepend the namespace to the key
* before using it as a storage
* identifier.
*
* @method buildNamespace
*
* @param {String} key
* A string to prepend a namespace onto.
*
* @return {String}
* A namespaced key identifer.
*/
buildNamespace(key) {
const namespace = get(this, 'namespace');
return isPresent(namespace) ? `${namespace}:${key}` : `${key}`;
},
/*
* Determine whether the key has been
* previously namespaced.
*
* @method isNamespacedKey
*
* @param {String} key
* A namespaced key
*
* @return {Boolean}
* True if the key was previously namespaced, otherwise false.
*/
isNamespacedKey(key) {
return `${key}`.indexOf(this.buildNamespace('')) === 0;
}
});
|
Add parser to body requests | 'use strict';
var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var session = require('express-session');
require('dotenv').load();
var app = express();
app.set('views', __dirname + '/app/views');
app.set('view engine', 'ejs');
app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use('/common', express.static(process.cwd() + '/app/common'));
var mongo_uri = process.env.MONGO_URI || 'mongodb://localhost/test';
mongoose.connect(mongo_uri);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('body-parser').json());
app.use(session({
secret: 'Graphriend',
resave: false,
saveUninitialized: true
}));
routes(app);
var port = process.env.PORT || 8080;
app.listen(port, function () {
console.log('Node.js listening on port ' + port + '...');
});
});
| 'use strict';
var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var session = require('express-session');
require('dotenv').load();
var app = express();
app.set('views', __dirname + '/app/views');
app.set('view engine', 'ejs');
app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use('/common', express.static(process.cwd() + '/app/common'));
var mongo_uri = process.env.MONGO_URI || 'mongodb://localhost/test';
mongoose.connect(mongo_uri);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
app.use(session({
secret: 'Graphriend',
resave: false,
saveUninitialized: true
}));
routes(app);
var port = process.env.PORT || 8080;
app.listen(port, function () {
console.log('Node.js listening on port ' + port + '...');
});
});
|
Fix bug in detecting missing Dive Manager app | var fs = require('fs');
var _ = require('lodash');
angular.module('suuntoDMEditor')
.service('dbpath', function () {
var getFirstSubDirectory = function (fromDir) {
var content = fs.readdirSync(fromDir);
var firstSub =
_(content)
.filter(function (f) { return fs.statSync(fromDir + f).isDirectory(); })
.reverse()
.first();
return firstSub;
}
this.getPath = function () {
var missing = {
exists: false,
path: ''
};
var suuntoDir = process.env.HOME + '/.config/Suunto/';
if (!fs.existsSync(suuntoDir)) { return missing; }
var dmDir = suuntoDir + getFirstSubDirectory(suuntoDir) + '/';
if (!fs.existsSync(dmDir)) { return missing; }
var buildDir = dmDir + getFirstSubDirectory(dmDir) + '/';
if (!fs.existsSync(buildDir)) { return missing; }
var dbPath = buildDir + 'DM4.db';
if (fs.existsSync(dbPath)) {
return {
exists: true,
path: dbPath
};
} else {
return missing;
}
};
});
| var fs = require('fs');
var _ = require('lodash');
angular.module('suuntoDMEditor')
.service('dbpath', function () {
var getFirstSubDirectory = function (fromDir) {
var content = fs.readdirSync(fromDir);
var firstSub =
_(content)
.filter(function (f) { return fs.statSync(fromDir + f).isDirectory(); })
.reverse()
.first();
return firstSub;
}
this.getPath = function () {
var suuntoDir = process.env.HOME + '/.config/Suunto/';
var dmDir = suuntoDir + getFirstSubDirectory(suuntoDir) + '/';
var buildDir = dmDir + getFirstSubDirectory(dmDir) + '/';
var dbPath = buildDir + 'DM4.db';
if (fs.existsSync(dbPath)) {
return {
exists: true,
path: dbPath
};
} else {
return {
exists: false,
path: ''
};
}
};
});
|
Use attachments for individual work items, all in the same reply. | /*eslint-env node*/
//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
var Botkit = require('botkit')
var controller = Botkit.slackbot({
debug: false
})
var bot = controller.spawn({
token: process.env.BOT_API_TOKEN
}).startRTM(function(err) {
if (err) {
console.error("Bot failed to connect to Slack. Error: " + err)
}
})
controller.hears(['(task|story|epic|defect) (\d*)'],'ambient',function(bot, message){
var matches = message.text.match(/(task|story|epic|defect) (\d*)/ig)
var attachments = [];
for(var i=0; i < matches.length; i++){
var id = matches[i].split(" ")[1]
attachments.push({
"fallback": matches[i],
"color": "#16B8DF",
"title_link": process.env.JAZZ_URI + "/resource/itemName/com.ibm.team.workitem.WorkItem/" + id,
"title": "Work Item " + id
})
}
if (attachments.length > 0) {
bot.reply(message, {
"attachments": attachments
})
}
})
| /*eslint-env node*/
//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
var Botkit = require('botkit')
var controller = Botkit.slackbot({
debug: false
})
var bot = controller.spawn({
token: process.env.BOT_API_TOKEN
}).startRTM(function(err) {
if (err) {
console.error("Bot failed to connect to Slack. Error: " + err)
}
})
controller.hears(['(task|story|epic|defect) (\d*)'],'ambient',function(bot, message){
var matches = message.text.match(/(task|story|epic|defect) (\d*)/ig)
for(var i=0; i < matches.length; i++){
var id = matches[i].split(" ")[1]
bot.reply(message, process.env.JAZZ_URI + "/resource/itemName/com.ibm.team.workitem.WorkItem/"+id)
}
})
|
Update package configuration, pt. ii | from setuptools import setup
setup(
name='tangled.auth',
version='0.1a2.dev0',
description='Tangled auth integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled.auth',
'tangled.auth.tests',
],
install_requires=[
'tangled.web>=0.1.dev0',
],
extras_require={
'dev': [
'tangled[dev]',
],
},
entry_points="""
[tangled.scripts]
auth = tangled.auth.command:Command
""",
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
],
)
| from setuptools import setup, find_packages
setup(
name='tangled.auth',
version='0.1a2.dev0',
description='Tangled auth integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=find_packages(),
install_requires=(
'tangled.web>=0.1.dev0',
),
extras_require={
'dev': (
'tangled[dev]',
),
},
entry_points="""
[tangled.scripts]
auth = tangled.auth.command:Command
""",
classifiers=(
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
),
)
|
Add docblock description to authenticate() | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Authentication;
interface AuthenticationServiceInterface
{
/**
* Authenticates and provides an authentication result
*
* @return Result
*/
public function authenticate();
/**
* Returns true if and only if an identity is available
*
* @return bool
*/
public function hasIdentity();
/**
* Returns the authenticated identity or null if no identity is available
*
* @return mixed|null
*/
public function getIdentity();
/**
* Clears the identity
*
* @return void
*/
public function clearIdentity();
}
| <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Authentication;
interface AuthenticationServiceInterface
{
/**
* @return Result
*/
public function authenticate();
/**
* Returns true if and only if an identity is available
*
* @return bool
*/
public function hasIdentity();
/**
* Returns the authenticated identity or null if no identity is available
*
* @return mixed|null
*/
public function getIdentity();
/**
* Clears the identity
*
* @return void
*/
public function clearIdentity();
}
|
Fix After You test description | 'use strict';
const assert = require('./../../assert');
const common = require('./../../common');
let battle;
describe('After You', function () {
afterEach(function () {
battle.destroy();
});
it(`should only cause the target to move next, not run a submove`, function () {
battle = common.createBattle({gameType: 'doubles'}, [[
{species: "Wynaut", ability: 'prankster', moves: ['afteryou']},
{species: "Necrozma", level: 50, ability: 'prankster', moves: ['photongeyser']},
], [
{species: "Dugtrio", moves: ['sleeptalk']},
{species: "Roggenrola", level: 1, ability: 'sturdy', moves: ['sleeptalk']},
]]);
// Photon Geyser has a mechanic where it ignores abilities with Mold Breaker,
// but doesn't when called via a submove like Sleep Talk. If it fails to KO through Sturdy,
// it's most likely because it's using submove behavior
battle.makeChoices('move afteryou -2, move photongeyser 2', 'auto');
const roggenrola = battle.p2.active[1];
assert.fainted(roggenrola);
});
});
| 'use strict';
const assert = require('./../../assert');
const common = require('./../../common');
let battle;
describe('Berserk', function () {
afterEach(function () {
battle.destroy();
});
it(`should only cause the target to move next, not run a submove`, function () {
battle = common.createBattle({gameType: 'doubles'}, [[
{species: "Wynaut", ability: 'prankster', moves: ['afteryou']},
{species: "Necrozma", level: 50, ability: 'prankster', moves: ['photongeyser']},
], [
{species: "Dugtrio", moves: ['sleeptalk']},
{species: "Roggenrola", level: 1, ability: 'sturdy', moves: ['sleeptalk']},
]]);
// Photon Geyser has a mechanic where it ignores abilities with Mold Breaker,
// but doesn't when called via a submove like Sleep Talk. If it fails to KO through Sturdy,
// it's most likely because it's using submove behavior
battle.makeChoices('move afteryou -2, move photongeyser 2', 'auto');
const roggenrola = battle.p2.active[1];
assert.fainted(roggenrola);
});
});
|
Install pgcrypto PGSQL extension but only if it does not exist already (e.g. from template1) | from django.core.management import call_command
from django.test.utils import get_runner
from django.conf import settings
from django.db import connections, DEFAULT_DB_ALIAS
# use jenkins runner if present otherwise the default django one
if 'django_jenkins' in settings.INSTALLED_APPS:
base_runner = 'django_jenkins.runner.CITestSuiteRunner'
else:
base_runner = 'django.test.runner.DiscoverRunner'
class CLADiscoverRunner(get_runner(settings, base_runner)):
"""
Overrides the default Runner and loads the initial_groups fixture.
This is because migrations are switched off during testing but
we do need `initial_groups` in order for the tests to pass.
"""
def setup_databases(self, **kwargs):
ret = super(CLADiscoverRunner, self).setup_databases(**kwargs)
connection = connections[DEFAULT_DB_ALIAS]
cursor = connection.cursor()
cursor.execute('CREATE EXTENSION IF NOT EXISTS pgcrypto')
call_command('loaddata', 'initial_groups')
return ret
| from django.core.management import call_command
from django.test.utils import get_runner
from django.conf import settings
from django.db import connections, DEFAULT_DB_ALIAS
# use jenkins runner if present otherwise the default django one
if 'django_jenkins' in settings.INSTALLED_APPS:
base_runner = 'django_jenkins.runner.CITestSuiteRunner'
else:
base_runner = 'django.test.runner.DiscoverRunner'
class CLADiscoverRunner(get_runner(settings, base_runner)):
"""
Overrides the default Runner and loads the initial_groups fixture.
This is because migrations are switched off during testing but
we do need `initial_groups` in order for the tests to pass.
"""
def setup_databases(self, **kwargs):
ret = super(CLADiscoverRunner, self).setup_databases(**kwargs)
connection = connections[DEFAULT_DB_ALIAS]
cursor = connection.cursor()
cursor.execute('CREATE EXTENSION pgcrypto')
call_command('loaddata', 'initial_groups')
return ret
|
Add logging and fix crash from previous feature | import url from 'url';
/**
* Skip opening the link through Facebook.
* It converts [facebook|messenger].com/l.php?u=<encodedUrl> to <unencodedUrl>.
*/
function skipFacebookRedirect (urlLink) {
const parsed = url.parse(urlLink, true);
log('skip facebook redirect, checking', urlLink);
if (!parsed || !parsed.hostname || !parsed.pathname) {
return urlLink;
}
const hostMatches = parsed.hostname.includes('facebook.com') || parsed.hostname.includes('messenger.com');
const pathMatches = parsed.pathname.includes('/l.php');
if (hostMatches && pathMatches && parsed.query.u) {
urlLink = parsed.query.u;
}
return urlLink;
}
/**
* Check if the given url is a downloadable file. Currently only detects Facebook CDN urls.
*/
function isDownloadUrl (urlLink) {
const isDlUrl = urlLink.startsWith('https://cdn.fbsbx.com') && urlLink.endsWith('&dl=1');
log('link is download url', urlLink, isDlUrl);
return isDlUrl;
}
export default {
skipFacebookRedirect,
isDownloadUrl
};
| import url from 'url';
/**
* Skip opening the link through Facebook.
* It converts [facebook|messenger].com/l.php?u=<encodedUrl> to <unencodedUrl>.
*/
function skipFacebookRedirect (urlLink) {
const parsed = url.parse(urlLink, true);
const hostMatches = parsed.hostname.includes('facebook.com') || parsed.hostname.includes('messenger.com');
const pathMatches = parsed.pathname.includes('/l.php');
if (hostMatches && pathMatches && parsed.query.u) {
urlLink = parsed.query.u;
}
return urlLink;
}
/**
* Check if the given url is a downloadable file. Currently only detects Facebook CDN urls.
*/
function isDownloadUrl (urlLink) {
return urlLink.startsWith('https://cdn.fbsbx.com') && urlLink.endsWith('&dl=1');
}
export default {
skipFacebookRedirect,
isDownloadUrl
};
|
Make the PASS command take advantage of processParams and handle the data dict correctly | from twisted.words.protocols import irc
from txircd.modbase import Command, Module
class PassCommand(Command, Module):
def onUse(self, user, data):
user.password = data["password"]
def processParams(self, user, params):
if user.registered == 0:
user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)")
return {}
if not params:
user.sendMessage(irc.ERR_NEEDMOREPARAMS, "PASS", ":Not enough parameters")
return {}
return {
"user": user,
"password": params[0]
}
def onRegister(self, user):
if self.ircd.server_password and self.ircd.server_password != user.password:
user.sendMessage("ERROR", ":Closing link: ({}@{}) [Access denied]".format(user.username, user.hostname), to=None, prefix=None)
return False
def Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.passcmd = PassCommand()
def spawn():
return {
"actions": {
"register": [self.passcmd.onRegister]
},
"commands": {
"PASS": self.passcmd
}
}
def cleanup():
self.ircd.actions.remove(self.passcmd)
del self.ircd.commands["PASS"]
del self.passcmd | from twisted.words.protocols import irc
from txircd.modbase import Command, Module
class PassCommand(Command, Module):
def onUse(self, user, params):
if user.registered == 0:
user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)")
return
if not params:
user.sendMessage(irc.ERR_NEEDMOREPARAMS, "PASS", ":Not enough parameters")
return
user.password = params[0]
def onRegister(self, user):
if self.ircd.server_password and self.ircd.server_password != user.password:
user.sendMessage("ERROR", ":Closing link: ({}@{}) [Access denied]".format(user.username, user.hostname), to=None, prefix=None)
return False
def Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.passcmd = PassCommand()
def spawn():
return {
"actions": {
"register": [self.passcmd.onRegister]
},
"commands": {
"PASS": self.passcmd
}
}
def cleanup():
self.ircd.actions.remove(self.passcmd)
del self.ircd.commands["PASS"]
del self.passcmd |
Print stack trace on all errors that have it | 'use strict';
var express = require('express')
, logger = require('morgan')
, mongoose = require('mongoose')
, path = require('path')
, messages = require('./routes/messages')
, users = require('./routes/users')
, config = require('./lib/config')
, app
;
app = express();
mongoose.connect(config.mongoUri, function (err) {
if (err) {
throw 'Couldn\'t connect to MongoDB: ' + err;
}
});
app.use(logger(config.logger));
app.use(require('body-parser').json());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', users);
app.use('/messages', messages);
/// catch 404 and forwarding to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.json({ error: err.message });
if (err.stack) {
console.error(err.stack);
}
});
module.exports = app;
| 'use strict';
var express = require('express')
, logger = require('morgan')
, mongoose = require('mongoose')
, path = require('path')
, messages = require('./routes/messages')
, users = require('./routes/users')
, config = require('./lib/config')
, app
;
app = express();
mongoose.connect(config.mongoUri, function (err) {
if (err) {
throw 'Couldn\'t connect to MongoDB: ' + err;
}
});
app.use(logger(config.logger));
app.use(require('body-parser').json());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', users);
app.use('/messages', messages);
/// catch 404 and forwarding to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.json({ error: err.message });
if (err.status !== 404) {
console.error(err.stack);
}
});
module.exports = app;
|
Fix React warning on the home page (add key attribute to list items) | /**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, { PropTypes } from 'react';
import Layout from '../../components/Layout';
import { title, html } from './index.md';
class HomePage extends React.Component {
static propTypes = {
articles: PropTypes.array.isRequired,
};
componentDidMount() {
document.title = title;
}
render() {
return (
<Layout>
<div dangerouslySetInnerHTML={{ __html: html }} />
<h4>Articles</h4>
<ul>
{this.props.articles.map((article, i) =>
<li key={i}><a href={article.url}>{article.title}</a> by {article.author}</li>
)}
</ul>
<p>
<br /><br />
</p>
</Layout>
);
}
}
export default HomePage;
| /**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, { PropTypes } from 'react';
import Layout from '../../components/Layout';
import { title, html } from './index.md';
class HomePage extends React.Component {
static propTypes = {
articles: PropTypes.array.isRequired,
};
componentDidMount() {
document.title = title;
}
render() {
return (
<Layout>
<div dangerouslySetInnerHTML={{ __html: html }} />
<h4>Articles</h4>
<ul>
{this.props.articles.map(article =>
<li><a href={article.url}>{article.title}</a> by {article.author}</li>
)}
</ul>
<p>
<br /><br />
</p>
</Layout>
);
}
}
export default HomePage;
|
Use standard methods in div creation. Fix for firefox and safari. | import inputData from './data.js';
import infiniteDivs from '../../lib/infinitedivs.js';
let rootElement = document.body;
function divGenerator(item) {
let div = document.createElement('div'),
img = document.createElement('img'),
span = document.createElement('span');
img.setAttribute('src', item.img);
img.setAttribute('style', 'vertical-align: middle; height: 50px; width: 50px; margin: 20px');
img.setAttribute('alt', 'avatar');
span.textContent = item.name;
span.setAttribute('style', 'text-decoration: underline');
div.appendChild(img);
div.appendChild(span);
return div;
}
let dataArray = inputData;
let config = {
bufferMultiplier: 2,
dataArray,
divGenerator,
divHeight: 90,
rootElement
};
let infinitedivs = new infiniteDivs(config);
function scrollListener() {
infinitedivs.viewDoctor();
};
document.addEventListener('scroll', scrollListener);
| import inputData from './data.js';
import infiniteDivs from '../../lib/infinitedivs.js';
let rootElement = document.body;
function divGenerator(item) {
let div = document.createElement('div'),
img = document.createElement('img'),
span = document.createElement('span');
img.src = item.img;
img.style = 'vertical-align: middle; height: 50px; width: 50px; margin: 20px';
img.alt = 'avatar';
span.innerText = item.name;
span.setAttribute('style', 'text-decoration: underline');
div.appendChild(img);
div.appendChild(span);
return div;
}
let dataArray = inputData;
let config = {
bufferMultiplier: 2,
dataArray,
divGenerator,
divHeight: 90,
rootElement
};
let infinitedivs = new infiniteDivs(config);
function scrollListener() {
infinitedivs.viewDoctor();
};
document.addEventListener('scroll', scrollListener);
|
Update David Molina's role on landing page | import React from 'react';
import LinkButton from 'shared/components/linkButton/linkButton';
import commonUrl from 'shared/constants/commonLinks';
import styles from './hero.css';
const hero = () => (
<div className={styles.container}>
<header className={styles.header}>
<h1 className={styles.heading}>Deploy the Future</h1>
<p className={styles.description}>
We're the largest community dedicated to helping military veterans and families launch
software development careers.
</p>
<div className={styles.btnContainer}>
<LinkButton link="/join" text="Join Us" theme="red-small" />
<LinkButton isExternal link={commonUrl.donateLink} text="Donate" theme="blue-small" />
</div>
</header>
<div className={styles.embedContainer}>
<div className={styles.embedVideo}>
<iframe
title="The New Developer - Operation Code - GitHub Universe 2016"
src="https://www.youtube.com/embed/xN7yMoe38xc?rel=0&showinfo=0&modestbranding=0&start=78&end=275"
frameBorder="0"
allowFullScreen
/>
</div>
<p className={styles.embedCaption}>
Founder and Board Chair David Molina speaks in San Francisco about Operation Code.
</p>
</div>
</div>
);
export default hero;
| import React from 'react';
import LinkButton from 'shared/components/linkButton/linkButton';
import commonUrl from 'shared/constants/commonLinks';
import styles from './hero.css';
const hero = () => (
<div className={styles.container}>
<header className={styles.header}>
<h1 className={styles.heading}>Deploy the Future</h1>
<p className={styles.description}>
We're the largest community dedicated to helping military veterans and families launch
software development careers.
</p>
<div className={styles.btnContainer}>
<LinkButton link="/join" text="Join Us" theme="red-small" />
<LinkButton isExternal link={commonUrl.donateLink} text="Donate" theme="blue-small" />
</div>
</header>
<div className={styles.embedContainer}>
<div className={styles.embedVideo}>
<iframe
title="The New Developer - Operation Code - GitHub Universe 2016"
src="https://www.youtube.com/embed/xN7yMoe38xc?rel=0&showinfo=0&modestbranding=0&start=78&end=275"
frameBorder="0"
allowFullScreen
/>
</div>
<p className={styles.embedCaption}>
Executive Director, David Molina, speaks in San Francisco about Operation Code.
</p>
</div>
</div>
);
export default hero;
|
Add back-office to student URL | """halaqat URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from back_office import urls as back_office_url
from students import urls as students_url
urlpatterns = [
url(r'^back_office/', include(back_office_url)),
url(r'^back-office/students/', include(students_url)),
url(r'^admin/', include(admin.site.urls)),
]
| """halaqat URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from back_office import urls as back_office_url
from students import urls as students_url
urlpatterns = [
url(r'^back_office/', include(back_office_url)),
url(r'^students/', include(students_url)),
url(r'^admin/', include(admin.site.urls)),
]
|
Use the correct main for cancel job | package com.ibm.streamsx.rest;
import java.io.IOException;
import java.math.BigInteger;
import com.ibm.streamsx.topology.internal.streams.InvokeCancel;
class StreamsConnectionImpl extends AbstractStreamsConnection {
private final String userName;
StreamsConnectionImpl(String userName, String authorization,
String resourcesUrl, boolean allowInsecure) throws IOException {
super(authorization, resourcesUrl, allowInsecure);
this.userName = userName;
}
@Override
String getAuthorization() {
return authorization;
}
@Override
boolean cancelJob(Instance instance, String jobId) throws IOException {
InvokeCancel cancelJob = new InvokeCancel(
instance.getDomain().getId(), instance.getId(),
new BigInteger(jobId), userName);
try {
return cancelJob.invoke(false) == 0;
} catch (Exception e) {
throw new RESTException("Unable to cancel job " + jobId
+ " in instance " + instance.getId(), e);
}
}
}
| package com.ibm.streamsx.rest;
import java.io.IOException;
import java.math.BigInteger;
import com.ibm.streamsx.topology.internal.streams.InvokeCancel;
class StreamsConnectionImpl extends AbstractStreamsConnection {
private final String userName;
StreamsConnectionImpl(String userName, String authorization,
String resourcesUrl, boolean allowInsecure) throws IOException {
super(authorization, resourcesUrl, allowInsecure);
this.userName = userName;
}
@Override
String getAuthorization() {
return authorization;
}
@Override
boolean cancelJob(Instance instance, String jobId) throws IOException {
// TODO - correct domain id
InvokeCancel cancelJob = new InvokeCancel(null, instance.getId(), new BigInteger(jobId), userName);
try {
return cancelJob.invoke(false) == 0;
} catch (Exception e) {
throw new RESTException("Unable to cancel job " + jobId
+ " in instance " + instance.getId(), e);
}
}
}
|
scripts: Use the OrderedDict class for JSON objects. | #!/usr/bin/env python3
# Touhou Community Reliant Automatic Patcher
# Scripts
#
# ----
#
"""Utility functions shared among all the scripts."""
from collections import OrderedDict
import json
import os
json_load_params = {
'object_pairs_hook': OrderedDict
}
json_dump_params = {
'ensure_ascii': False,
'indent': '\t',
'separators': (',', ': '),
'sort_keys': True
}
# Default parameters for JSON input and output
def json_load(fn):
with open(fn, 'r', encoding='utf-8') as file:
return json.load(file, **json_load_params)
def json_store(fn, obj, dirs=['']):
"""Saves the JSON object [obj] to [fn], creating all necessary
directories in the process. If [dirs] is given, the function is
executed for every root directory in the array."""
for i in dirs:
full_fn = os.path.join(i, fn)
os.makedirs(os.path.dirname(full_fn), exist_ok=True)
with open(full_fn, 'w', encoding='utf-8') as file:
json.dump(obj, file, **json_dump_params)
file.write('\n')
| #!/usr/bin/env python3
# Touhou Community Reliant Automatic Patcher
# Scripts
#
# ----
#
"""Utility functions shared among all the scripts."""
import json
import os
json_dump_params = {
'ensure_ascii': False,
'indent': '\t',
'separators': (',', ': '),
'sort_keys': True
}
# Default parameters for JSON input and output
def json_load(fn):
with open(fn, 'r', encoding='utf-8') as file:
return json.load(file)
def json_store(fn, obj, dirs=['']):
"""Saves the JSON object [obj] to [fn], creating all necessary
directories in the process. If [dirs] is given, the function is
executed for every root directory in the array."""
for i in dirs:
full_fn = os.path.join(i, fn)
os.makedirs(os.path.dirname(full_fn), exist_ok=True)
with open(full_fn, 'w', encoding='utf-8') as file:
json.dump(obj, file, **json_dump_params)
file.write('\n')
|
Add theme color for Chrome in Android 5 | <meta charset="UTF-8">
<meta name="msvalidate.01" content="0FB9B019DA55297EDC00A30165EA3E85" />
<meta name=viewport content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ed8f31">
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-51951207-1', 'auto');
ga('require', 'displayfeatures');
ga('send', 'pageview');
</script>
| <meta charset="UTF-8">
<meta name="msvalidate.01" content="0FB9B019DA55297EDC00A30165EA3E85" />
<meta name=viewport content="width=device-width, initial-scale=1">
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-51951207-1', 'auto');
ga('require', 'displayfeatures');
ga('send', 'pageview');
</script>
|
Change outdated command to show package manager by default | var fs = require('fs')
, events = require('events')
, eventEmitter = new events.EventEmitter()
, pluginDirectory = __dirname + '/package-managers'
var Opm = {
verbosity: 0,
// Setup package manager and ready plugins
init: function () {
return fs.readdirSync(pluginDirectory).map( (pm) => {
require(`${pluginDirectory}/${pm}`)
})
},
// Allows plugins to register for events
on: function (event, cb) {
eventEmitter.on(event, cb)
},
// Utility function to print a package's info for a user to see
printPackageInfo: function (package) {
console.log(`(${package.packageManager}) ${package.name}`)
},
// Tell plugins to list outdated packages
outdated: function () {
eventEmitter.emit('outdated', this.showOutdated)
},
// Callback for 'outdated' event that shows outdated packages to the user
showOutdated: function (outdatedPackages) {
outdatedPackages.map( (pkg) => Opm.printPackageInfo(pkg) )
}
}
module.exports = Opm
| var fs = require('fs')
, events = require('events')
, eventEmitter = new events.EventEmitter()
, pluginDirectory = __dirname + '/package-managers'
var Opm = {
verbosity: 0,
// Setup package manager and ready plugins
init: function () {
return fs.readdirSync(pluginDirectory).map( (pm) => {
require(`${pluginDirectory}/${pm}`)
})
},
// Allows plugins to register for events
on: function (event, cb) {
eventEmitter.on(event, cb)
},
// Utility function to print a package's info for a user to see
printPackageInfo: function (package) {
if (this.verbosity > 1) {
console.log(`${package.name} ${package.version ? package.version + ' < ': ''}${package.latestVersion ? package.latestVersion : ''} (${package.packageManager})`)
} else if (this.verbosity) {
console.log(`(${package.packageManager}) ${package.name}`)
} else {
console.log(package.name)
}
},
// Tell plugins to list outdated packages
outdated: function () {
eventEmitter.emit('outdated', this.showOutdated)
},
// Callback for 'outdated' event that shows outdated packages to the user
showOutdated: function (outdatedPackages) {
outdatedPackages.map( (pkg) => Opm.printPackageInfo(pkg) )
}
}
module.exports = Opm
|
Fix typo in package description | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-argcache',
version='0.1',
license='AGPLv3',
description='A function-level caching and invalidaton framework for Django.',
long_description=README,
url='https://github.com/luac/django-argcache/',
author='Anthony Lu',
author_email='lua@mit.edu',
packages=[
'argcache',
'argcache.extras',
],
package_dir={
'argcache': 'src'
},
include_package_data=True,
install_requires=[
'django>=1.7',
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: License :: OSI Approved :: GNU Affero General Public License v3',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
)
| import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-argcache',
version='0.1',
license='AGPLv3',
description='A function-level caching and invalidaton fraemwork for Django.',
long_description=README,
url='https://github.com/luac/django-argcache/',
author='Anthony Lu',
author_email='lua@mit.edu',
packages=[
'argcache',
'argcache.extras',
],
package_dir={
'argcache': 'src'
},
include_package_data=True,
install_requires=[
'django>=1.7',
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: License :: OSI Approved :: GNU Affero General Public License v3',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
)
|
Check if target directory is empty instead of current directory and remove overwrite_if_exists argument | import os
def execute(name, branch):
try:
from cookiecutter.main import cookiecutter
except ImportError as exc:
raise ImportError(
'You must install "cookiecutter" to use this command.\n\n $ pip install cookiecutter\n'
) from exc
overwrite_if_exists = False
project_path = os.path.join(os.getcwd(), name)
if os.path.isdir(project_path) and not os.listdir(project_path):
overwrite_if_exists = True
return cookiecutter(
'https://github.com/python-bonobo/cookiecutter-bonobo.git',
extra_context={'name': name},
no_input=True,
checkout=branch,
overwrite_if_exists=overwrite_if_exists
)
def register(parser):
parser.add_argument('name')
parser.add_argument('--branch', '-b', default='master')
return execute
| import os
def execute(name, branch, overwrite_if_exists=False):
try:
from cookiecutter.main import cookiecutter
except ImportError as exc:
raise ImportError(
'You must install "cookiecutter" to use this command.\n\n $ pip install cookiecutter\n'
) from exc
if os.listdir(os.getcwd()) == []:
overwrite_if_exists = True
return cookiecutter(
'https://github.com/python-bonobo/cookiecutter-bonobo.git',
extra_context={'name': name},
no_input=True,
checkout=branch,
overwrite_if_exists=overwrite_if_exists
)
def register(parser):
parser.add_argument('name')
parser.add_argument('--branch', '-b', default='master')
return execute
|
Remove lucene query builder and bumper version | from setuptools import setup, find_packages
setup(
name='neomodel',
version='1.0.0',
description='An object mapper for the neo4j graph database.',
long_description=open('README.rst').read(),
author='Robin Edwards',
author_email='robin.ge@gmail.com',
zip_safe=True,
url='http://github.com/robinedwards/neomodel',
license='MIT',
packages=find_packages(),
keywords='graph neo4j py2neo ORM',
tests_require=['nose==1.1.2'],
test_suite='nose.collector',
install_requires=['py2neo==1.6.1', 'pytz==2013.8'],
classifiers=[
"Development Status :: 5 - Production/Stable",
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Topic :: Database",
])
| from setuptools import setup, find_packages
setup(
name='neomodel',
version='0.4.0',
description='An object mapper for the neo4j graph database.',
long_description=open('README.rst').read(),
author='Robin Edwards',
author_email='robin.ge@gmail.com',
zip_safe=True,
url='http://github.com/robinedwards/neomodel',
license='MIT',
packages=find_packages(),
keywords='graph neo4j py2neo ORM',
tests_require=['nose==1.1.2'],
test_suite='nose.collector',
install_requires=['py2neo==1.6.1', 'pytz==2013.8', 'lucene-querybuilder==0.2'],
classifiers=[
"Development Status :: 5 - Production/Stable",
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Topic :: Database",
])
|
Add support for https redirect | from .base import *
import dj_database_url
if os.environ.get('DEBUG') == 'False':
DEBUG = False
else:
DEBUG = True
try:
from .local import *
except ImportError:
pass
ADMINS = ADMINS + (
)
ALLOWED_HOSTS = ['*']
DATABASES = {'default': dj_database_url.config()}
SOCIAL_AUTH_YAMMER_KEY = os.environ.get('SOCIAL_AUTH_YAMMER_KEY')
SOCIAL_AUTH_YAMMER_SECRET = os.environ.get('SOCIAL_AUTH_YAMMER_SECRET')
SOCIAL_AUTH_REDIRECT_IS_HTTPS = os.environ.get('SOCIAL_AUTH_REDIRECT_IS_HTTPS', False)
AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME']
STATICFILES_STORAGE = 'core.storage.S3PipelineManifestStorage'
STATIC_URL = 'http://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME
AWS_QUERYSTRING_AUTH = False
AWS_S3_FILE_OVERWRITE = True
PIPELINE_JS_COMPRESSOR = 'pipeline.compressors.yuglify.YuglifyCompressor'
PIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.yuglify.YuglifyCompressor'
PIPELINE_YUGLIFY_BINARY = '/app/.heroku/python/bin/yuglify'
| from .base import *
import dj_database_url
if os.environ.get('DEBUG') == 'False':
DEBUG = False
else:
DEBUG = True
try:
from .local import *
except ImportError:
pass
ADMINS = ADMINS + (
)
ALLOWED_HOSTS = ['*']
DATABASES = {'default': dj_database_url.config()}
SOCIAL_AUTH_YAMMER_KEY = os.environ.get('SOCIAL_AUTH_YAMMER_KEY')
SOCIAL_AUTH_YAMMER_SECRET = os.environ.get('SOCIAL_AUTH_YAMMER_SECRET')
AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME']
STATICFILES_STORAGE = 'core.storage.S3PipelineManifestStorage'
STATIC_URL = 'http://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME
AWS_QUERYSTRING_AUTH = False
AWS_S3_FILE_OVERWRITE = True
PIPELINE_JS_COMPRESSOR = 'pipeline.compressors.yuglify.YuglifyCompressor'
PIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.yuglify.YuglifyCompressor'
PIPELINE_YUGLIFY_BINARY = '/app/.heroku/python/bin/yuglify'
|
Remove unnecessary synchronization on a PrintStream instance | /*
* Copyright (C) 2004 - 2014 Brian McCallister
*
* 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 org.skife.jdbi.v2.logging;
import java.io.PrintStream;
/**
*
*/
public class PrintStreamLog extends FormattedLog
{
private final PrintStream out;
/**
* Log to standard out.
*/
public PrintStreamLog()
{
this(System.out);
}
/**
* Specify the print stream to log to
* @param out The print stream to log to
*/
public PrintStreamLog(PrintStream out) {
this.out = out;
}
@Override
protected final boolean isEnabled()
{
return true;
}
@Override
protected void log(String msg)
{
out.println(msg);
}
}
| /*
* Copyright (C) 2004 - 2014 Brian McCallister
*
* 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 org.skife.jdbi.v2.logging;
import java.io.PrintStream;
/**
*
*/
public class PrintStreamLog extends FormattedLog
{
private final PrintStream out;
/**
* Log to standard out.
*/
public PrintStreamLog()
{
this(System.out);
}
/**
* Specify the print stream to log to
* @param out The print stream to log to
*/
public PrintStreamLog(PrintStream out) {
this.out = out;
}
@Override
protected final boolean isEnabled()
{
return true;
}
@Override
protected void log(String msg)
{
synchronized(out) {
out.println(msg);
}
}
}
|
Check if we actually have an array. | <?php
/**
* Validate array types.
*
* @package HylianShield
* @subpackage Validator
* @copyright 2014 Noë Snaterse.
*/
namespace HylianShield\Validator\CoreArray;
/**
* CoreArray.
*/
class Numeric extends \HylianShield\Validator\CoreArray
{
/**
* The type.
*
* @var string $type
*/
protected $type = 'array_numeric';
/**
* Constructs Numeric array validators.
*/
public function __contruct()
{
$this->validator = function ($array) {
// First check if $array is an actual array.
if (!is_array($array)) {
return false;
}
// Then get all the keys
$keys = array_keys($array);
// And check if they all are numeric.
for ($i = 0; $i < count($keys); $i++) {
if ($i !== $keys[$i]) {
return false;
}
}
return true;
};
}
} | <?php
/**
* Validate array types.
*
* @package HylianShield
* @subpackage Validator
* @copyright 2014 Noë Snaterse.
*/
namespace HylianShield\Validator\CoreArray;
/**
* CoreArray.
*/
class Numeric extends \HylianShield\Validator\CoreArray
{
/**
* The type.
*
* @var string $type
*/
protected $type = 'array_numeric';
/**
* Constructs Numeric array validators.
*/
public function __contruct()
{
$this->validator = function ($array) {
// First get all the keys
$keys = array_keys($array);
for ($i = 0; $i < count($keys); $i++) {
if ($i !== $keys[$i]) {
return false;
}
}
return true;
};
}
} |
Stop leep test being ignored | import unittest
from leap import is_leap_year
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.5.1
class LeapTest(unittest.TestCase):
def test_year_not_divisible_by_4(self):
self.assertIs(is_leap_year(2015), False)
def test_year_divisible_by_2_not_divisible_by_4(self):
self.assertIs(is_leap_year(1970), False)
def test_year_divisible_by_4_not_divisible_by_100(self):
self.assertIs(is_leap_year(1996), True)
def test_year_divisible_by_100_not_divisible_by_400(self):
self.assertIs(is_leap_year(2100), False)
def test_year_divisible_by_400(self):
self.assertIs(is_leap_year(2000), True)
def test_year_divisible_by_200_not_divisible_by_400(self):
self.assertIs(is_leap_year(1800), False)
if __name__ == '__main__':
unittest.main()
| import unittest
from leap import is_leap_year
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.5.1
class LeapTest(unittest.TestCase):
def test_year_not_divisible_by_4(self):
self.assertIs(is_leap_year(2015), False)
def year_divisible_by_2_not_divisible_by_4(self):
self.assertIs(is_leap_year(1970), False)
def test_year_divisible_by_4_not_divisible_by_100(self):
self.assertIs(is_leap_year(1996), True)
def test_year_divisible_by_100_not_divisible_by_400(self):
self.assertIs(is_leap_year(2100), False)
def test_year_divisible_by_400(self):
self.assertIs(is_leap_year(2000), True)
def test_year_divisible_by_200_not_divisible_by_400(self):
self.assertIs(is_leap_year(1800), False)
if __name__ == '__main__':
unittest.main()
|
Enable foreign key constraint for SQLite | __all__ = [
'create_engine',
]
import sqlalchemy
def create_engine(db_uri, check_same_thread=False, echo=False):
engine = sqlalchemy.create_engine(
db_uri,
echo=echo,
connect_args={
'check_same_thread': check_same_thread,
},
)
@sqlalchemy.event.listens_for(engine, 'connect')
def do_connect(dbapi_connection, _):
# Stop pysqlite issue commit automatically.
dbapi_connection.isolation_level = None
# Enable foreign key.
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys = ON")
cursor.close()
@sqlalchemy.event.listens_for(engine, 'begin')
def do_begin(connection):
connection.execute('BEGIN EXCLUSIVE')
return engine
| __all__ = [
'create_engine',
]
import sqlalchemy
def create_engine(db_uri, check_same_thread=False, echo=False):
engine = sqlalchemy.create_engine(
db_uri,
echo=echo,
connect_args={
'check_same_thread': check_same_thread,
},
)
@sqlalchemy.event.listens_for(engine, 'connect')
def do_connect(dbapi_connection, _):
# Stop pysqlite issue commit automatically.
dbapi_connection.isolation_level = None
@sqlalchemy.event.listens_for(engine, 'begin')
def do_begin(connection):
connection.execute('BEGIN EXCLUSIVE')
return engine
|
bigtable/emulator: Disable grpc tracing for emulator server
Change-Id: I4ec7670fe2b1b880c4dc7dfdae8acd09993031df
Reviewed-on: https://code-review.googlesource.com/9091
Reviewed-by: Jonathan Amsterdam <e3d3698b2ccd5955e4adf250d0785062d0f9018b@google.com> | // Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
cbtemulator launches the in-memory Cloud Bigtable server on the given address.
*/
package main
import (
"flag"
"fmt"
"log"
"cloud.google.com/go/bigtable/bttest"
"google.golang.org/grpc"
)
var (
host = flag.String("host", "localhost", "the address to bind to on the local machine")
port = flag.Int("port", 9000, "the port number to bind to on the local machine")
)
func main() {
grpc.EnableTracing = false
flag.Parse()
srv, err := bttest.NewServer(fmt.Sprintf("%s:%d", *host, *port))
if err != nil {
log.Fatalf("failed to start emulator: %v", err)
}
fmt.Printf("Cloud Bigtable emulator running on %s\n", srv.Addr)
select {}
}
| // Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
cbtemulator launches the in-memory Cloud Bigtable server on the given address.
*/
package main
import (
"flag"
"fmt"
"log"
"cloud.google.com/go/bigtable/bttest"
)
var (
host = flag.String("host", "localhost", "the address to bind to on the local machine")
port = flag.Int("port", 9000, "the port number to bind to on the local machine")
)
func main() {
flag.Parse()
srv, err := bttest.NewServer(fmt.Sprintf("%s:%d", *host, *port))
if err != nil {
log.Fatalf("failed to start emulator: %v", err)
}
fmt.Printf("Cloud Bigtable emulator running on %s\n", srv.Addr)
select {}
}
|
Use Render() and Loader here | package main
import (
"flag"
"fmt"
"os"
"github.com/lestrrat/go-xslate"
"github.com/lestrrat/go-xslate/loader"
)
func usage() {
fmt.Fprintf(os.Stderr, "usage: xslate [options...] [input-files]\n")
flag.PrintDefaults()
os.Exit(2)
}
func main() {
flag.Usage = usage
flag.Parse()
args := flag.Args()
if len(args) < 1 {
fmt.Fprintf(os.Stderr, "Input file is missing.\n")
os.Exit(1)
}
tx := xslate.New()
// TODO: Accept --path arguments
pwd, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to get current working directory: %s\n", err)
os.Exit(1)
}
tx.Loader, _ = loader.NewLoadFile([]string { pwd })
for _, file := range args {
output, err := tx.Render(file, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to render %s: %s\n", file, err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, output)
}
} | package main
import (
"flag"
"fmt"
"os"
"github.com/lestrrat/go-xslate"
)
func usage() {
fmt.Fprintf(os.Stderr, "usage: xslate [options...] [input-files]\n")
flag.PrintDefaults()
os.Exit(2)
}
func main() {
flag.Usage = usage
flag.Parse()
args := flag.Args()
if len(args) < 1 {
fmt.Fprintf(os.Stderr, "Input file is missing.\n")
os.Exit(1)
}
tx := xslate.New()
for _, file := range args {
fh, err := os.Open(file)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to open %s for reading: %s\n", file, err)
os.Exit(1)
}
output, err := tx.RenderReader(fh, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to render %s: %s\n", file, err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, output)
}
} |
Remove coverage report (it's empty anyway). | module.exports = function( config ) {
'use strict';
config.set( {
autoWatch: false,
basePath: '../../',
browsers: ['PhantomJS', 'Firefox', 'Chrome'],
exclude: [],
frameworks: ['jasmine'],
junitReporter : {
outputFile: 'output/test/unit.xml',
suite: 'unit'
},
plugins : [
'karma-chrome-launcher',
'karma-coverage',
'karma-jasmine',
'karma-junit-reporter',
'karma-firefox-launcher',
'karma-phantomjs-launcher',
'karma-script-launcher'
],
reporters: ['progress','junit','coverage']
} );
}; | module.exports = function( config ) {
'use strict';
config.set( {
autoWatch: false,
basePath: '../../',
browsers: ['PhantomJS', 'Firefox', 'Chrome'],
coverageReporter: {
reporters: [
{ type: 'html', dir: 'output/test/coverage/' },
{ type: 'cobertura', dir: 'output/test/coverage/' }
]
},
exclude: [],
frameworks: ['jasmine'],
junitReporter : {
outputFile: 'output/test/unit.xml',
suite: 'unit'
},
plugins : [
'karma-chrome-launcher',
'karma-coverage',
'karma-jasmine',
'karma-junit-reporter',
'karma-firefox-launcher',
'karma-phantomjs-launcher',
'karma-script-launcher'
],
reporters: ['progress','junit','coverage']
} );
}; |
Remove unimplemented methods from help | var argv = require('minimist')(process.argv.slice(2));
var marco = require('./lib/marco.js');
var through = require('through2');
var split = require('split');
var usage = function() {
var text = [];
text.push('Usage: node example.js [-s] [-m] [-h]');
text.push('');
text.push(' --state matches query to states');
text.push(' --municipality matches query against municipalities');
text.push(' --help prints this help message.');
text.push('');
return text.join('\n');
}
var state = argv.state || argv.s;
var municipality = argv.municipality || argv.m;
// STREAMING
function setPipe() {
var ts = through(() => {});
if (state) {
ts = marco.toStatePolygon();
}
process.stdin
.pipe(split())
.pipe(ts)
.pipe(process.stdout);
}
setPipe();
// SIMPLE QUERIES
if (state) {
marco.findState(state, (err, data) => {
if (!err && data)
console.log(JSON.stringify(data));
});
} else if (municipality) {
marco.findMunicipality(municipality, (err, data) => {
if (!err && data)
console.log(JSON.stringify(data));
});
} else {
console.log(usage());
process.exit(1);
}
| var argv = require('minimist')(process.argv.slice(2));
var marco = require('./lib/marco.js');
var through = require('through2');
var split = require('split');
var usage = function() {
var text = [];
text.push('Usage: node example.js [-s] [-m] [-h]');
text.push('');
text.push(' --centroid returns a Point feature');
text.push(' --shape returns a Polygon feature');
text.push(' --state matches query to states');
text.push(' --municipality matches query against municipalities');
text.push(' --multiple returns all matches found per query');
text.push(' --help prints this help message.');
text.push('');
return text.join('\n');
}
var state = argv.state || argv.s;
var municipality = argv.municipality || argv.m;
// STREAMING
function setPipe() {
var ts = through(() => {});
if (state) {
ts = marco.toStatePolygon();
}
process.stdin
.pipe(split())
.pipe(ts)
.pipe(process.stdout);
}
setPipe();
// SIMPLE QUERIES
if (state) {
marco.findState(state, (err, data) => {
if (!err && data)
console.log(JSON.stringify(data));
});
} else if (municipality) {
marco.findMunicipality(municipality, (err, data) => {
if (!err && data)
console.log(JSON.stringify(data));
});
} else {
console.log(usage());
process.exit(1);
}
|
Fix bug with campaign id | from django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
to_address = ','.join([g['address'] for g in group_api.get_groups(email['sequence'])])
elif email['audience'] == 'individuals':
to_address = 'sequence-{0}-all@{1}'.format(email['sequence'], settings.EMAIL_DOMAIN)
mailgun_api.send_email(
to_address,
settings.DEFAULT_FROM_EMAIL,
email['subject'],
email['text_body'],
email['html_body'],
email['tags'].split(','),
'sequence-{0}-campaign'.format(email['sequence'])
)
mail_api.mark_sent(email_uri)
| from django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
to_address = ','.join([g['address'] for g in group_api.get_groups(email['sequence'])])
elif email['audience'] == 'individuals':
to_address = 'sequence-{0}-all@{1}'.format(email['sequence'], settings.EMAIL_DOMAIN)
mailgun_api.send_email(
to_address,
settings.DEFAULT_FROM_EMAIL,
email['subject'],
email['text_body'],
email['html_body'],
email['tags'].split(','),
'sequence-{0}-campaign'
)
mail_api.mark_sent(email_uri)
|
Comment and toast delete tested | (function () {
'use strict';
angular
.module('drinks', ['ngAnimate', 'toastr'])
.controller('DrinksListController', DrinksListController);
DrinksListController.$inject = ['DrinksService', '$state' , '$scope', 'toastr'];
function DrinksListController(DrinksService, $state, $scope, toastr) {
var vm = this;
vm.AddToMenu = AddToMenu;
vm.mvOnMenu = mvOnMenu;
vm.mvOffMenu = mvOffMenu;
vm.drinks = DrinksService.query();
function AddToMenu(drink) {
drink.$update(successCallback, errorCallback);
function successCallback(res) {
$state.go('drinks.list', {
drinkId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;
}
}
//Menu drink toggle notification via toastr
function mvOnMenu(drink) {
toastr.success(
drink.drinkName + ' was added to tap!'
);
}
function mvOffMenu(drink) {
toastr.success(
drink.drinkName + ' was removed from tap!'
);
}
}
})();
| (function () {
'use strict';
angular
.module('drinks', ['ngAnimate', 'toastr'])
.controller('DrinksListController', DrinksListController);
DrinksListController.$inject = ['DrinksService', '$state' , '$scope', 'toastr'];
function DrinksListController(DrinksService, $state, $scope, toastr) {
var vm = this;
vm.AddToMenu = AddToMenu;
vm.mvOnMenu = mvOnMenu;
vm.mvOffMenu = mvOffMenu;
vm.drinks = DrinksService.query();
function AddToMenu(drink) {
drink.$update(successCallback, errorCallback);
function successCallback(res) {
$state.go('drinks.list', {
drinkId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;
}
}
//Menu drink toggle notification via toastr
function mvOnMenu(drink) {
toastr.success(
drink.drinkName + ' was added to tap!'
);
}
function mvOffMenu(drink) {
toastr.success(
drink.drinkName + ' was removed from tap!'
);
}
}
})();
|
Replace execfile with py3-compatible equivalent | # -*- coding: utf-8 -*-
import os
import stat
from os.path import join, abspath
from subprocess import call
def prepare(globs, locs):
# RTD defaults the current working directory to where conf.py resides.
# In our case, that means <root>/docs/src/.
cwd = os.getcwd()
root = abspath(join(cwd, '..', '..'))
os.chdir(root)
# Download the PHP binary & composer.phar if necessary
base = 'https://github.com/Erebot/Buildenv/releases/download/1.4.0'
for f in ('php', 'composer.phar'):
call(['curl', '-L', '-z', f, '-o', f, '%s/%s' % (base, f)])
# Make sure the PHP interpreter is executable
os.chmod('./php', stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
# Call composer to download/update dependencies as necessary
os.environ['COMPOSER_CACHE_DIR'] = './cache'
call(['./php', 'composer.phar', 'update', '-n', '--ignore-platform-reqs',
'--no-progress'], env=os.environ)
# Load the second-stage configuration file.
os.chdir(cwd)
conf = join(root, 'vendor', 'erebot', 'buildenv', 'sphinx', 'rtd.py')
print "Including the second configuration file (%s)..." % (conf, )
exec(compile(open(conf).read(), conf, 'exec'), globs, locs)
prepare(globals(), locals())
| # -*- coding: utf-8 -*-
import os
import stat
from os.path import join, abspath
from subprocess import call
def prepare(globs, locs):
# RTD defaults the current working directory to where conf.py resides.
# In our case, that means <root>/docs/src/.
cwd = os.getcwd()
root = abspath(join(cwd, '..', '..'))
os.chdir(root)
# Download the PHP binary & composer.phar if necessary
base = 'https://github.com/Erebot/Buildenv/releases/download/1.4.0'
for f in ('php', 'composer.phar'):
call(['curl', '-L', '-z', f, '-o', f, '%s/%s' % (base, f)])
# Make sure the PHP interpreter is executable
os.chmod('./php', stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
# Call composer to download/update dependencies as necessary
os.environ['COMPOSER_CACHE_DIR'] = './cache'
call(['./php', 'composer.phar', 'update', '-n', '--ignore-platform-reqs',
'--no-progress'], env=os.environ)
# Load the second-stage configuration file.
os.chdir(cwd)
conf = join(root, 'vendor', 'erebot', 'buildenv', 'sphinx', 'rtd.py')
print "Including the second configuration file (%s)..." % (conf, )
execfile(conf, globs, locs)
prepare(globals(), locals())
|
Remove settings object from gulp-ruby-sass call | var gulp = require('gulp');
var sass = require('gulp-sass');
var rubySass = require('gulp-ruby-sass');
var rename = require('gulp-rename');
var Super = require('supercollider').init;
gulp.task('docs', function() {
gulp.src('./docs/*.md')
.pipe(Super({
template: './docs/_template.html',
adapters: ['sass']
}))
.pipe(gulp.dest('./build'));
});
gulp.task('sass', function() {
return rubySass('./motion-ui.scss')
.on('error', function (err) {
console.error('Error:', err.message);
})
.pipe(gulp.dest('./build/assets'));
});
gulp.task('dist', ['sass'], function() {
gulp.src('./build/assets/motion-ui.css')
.pipe(gulp.dest('./dist'))
.pipe(sass({
outputStyle: 'compressed'
}))
.pipe(rename('motion-ui.min.css'))
.pipe(gulp.dest('./dist'));
});
gulp.task('default', ['docs', 'sass'], function() {
gulp.watch('./docs/*.md', ['docs']);
gulp.watch(['./src/**/*.scss', './motion-ui.scss'], ['sass']);
}); | var gulp = require('gulp');
var sass = require('gulp-sass');
var rubySass = require('gulp-ruby-sass');
var rename = require('gulp-rename');
var Super = require('supercollider').init;
gulp.task('docs', function() {
gulp.src('./docs/*.md')
.pipe(Super({
template: './docs/_template.html',
adapters: ['sass']
}))
.pipe(gulp.dest('./build'));
});
gulp.task('sass', function() {
return rubySass('./motion-ui.scss', {
outputStyle: 'expanded'
})
.on('error', function (err) {
console.error('Error:', err.message);
})
.pipe(gulp.dest('./build/assets'));
});
gulp.task('dist', ['sass'], function() {
gulp.src('./build/assets/motion-ui.css')
.pipe(gulp.dest('./dist'))
.pipe(sass({
outputStyle: 'compressed'
}))
.pipe(rename('motion-ui.min.css'))
.pipe(gulp.dest('./dist'));
});
gulp.task('default', ['docs', 'sass'], function() {
gulp.watch('./docs/*.md', ['docs']);
gulp.watch(['./src/**/*.scss', './motion-ui.scss'], ['sass']);
}); |
Break on error in ReadJSON instead of continuing and panicing on
NewQuery later on. Fixes panic on connection loss. | package certstream
import (
"time"
"github.com/gorilla/websocket"
"github.com/jmoiron/jsonq"
"github.com/pkg/errors"
)
func CertStreamEventStream(skipHeartbeats bool) (chan jsonq.JsonQuery, chan error) {
outputStream := make(chan jsonq.JsonQuery)
errStream := make(chan error)
go func() {
for {
c, _, err := websocket.DefaultDialer.Dial("wss://certstream.calidog.io", nil)
if err != nil {
errStream <- errors.Wrap(err, "Error connecting to certstream! Sleeping a few seconds and reconnecting... ")
time.Sleep(5 * time.Second)
continue
}
defer c.Close()
defer close(outputStream)
for {
var v interface{}
err = c.ReadJSON(&v)
if err != nil {
errStream <- errors.Wrap(err, "Error decoding json frame!")
break
}
jq := jsonq.NewQuery(v)
res, err := jq.String("message_type")
if err != nil {
errStream <- errors.Wrap(err, "Error creating jq object!")
}
if skipHeartbeats && res == "heartbeat" {
continue
}
outputStream <- *jq
}
}
}()
return outputStream, errStream
}
| package certstream
import (
"time"
"github.com/gorilla/websocket"
"github.com/jmoiron/jsonq"
"github.com/pkg/errors"
)
func CertStreamEventStream(skipHeartbeats bool) (chan jsonq.JsonQuery, chan error) {
outputStream := make(chan jsonq.JsonQuery)
errStream := make(chan error)
go func() {
for {
c, _, err := websocket.DefaultDialer.Dial("wss://certstream.calidog.io", nil)
if err != nil {
errStream <- errors.Wrap(err, "Error connecting to certstream! Sleeping a few seconds and reconnecting... ")
time.Sleep(5 * time.Second)
continue
}
defer c.Close()
defer close(outputStream)
for {
var v interface{}
err = c.ReadJSON(&v)
if err != nil {
errStream <- errors.Wrap(err, "Error decoding json frame!")
}
jq := jsonq.NewQuery(v)
res, err := jq.String("message_type")
if err != nil {
errStream <- errors.Wrap(err, "Error creating jq object!")
}
if skipHeartbeats && res == "heartbeat" {
continue
}
outputStream <- *jq
}
}
}()
return outputStream, errStream
}
|
Set size on SVG in scatterplotSquare example. |
function makeScatterplotSquare() {
var data = makeNormallyDistributedData(100, 50, 20, 60, 10);
var dataset = {data: data, metadata: {cssClass: "transparent-square"}};
var xScale = new Plottable.LinearScale();
var xAxis = new Plottable.XAxis(xScale, "bottom").tickSize(2, 0);
var yScale = new Plottable.LinearScale();
var yAxis = new Plottable.YAxis(yScale, "left")
.tickLabelPosition("bottom")
.tickSize(50);
function rAccessor() { return 5; }
var r = new Plottable.SquareRenderer(dataset, xScale, yScale,
null, null, rAccessor);
var svg = d3.select("#scatterplot-square");
svg.attr("width", 800).attr("height", 320);
var innerTable = new Plottable.Table([[yAxis, r],
[null, xAxis]]);
innerTable.renderTo(svg);
xScale.padDomain().nice();
yScale.padDomain().nice();
};
window.onload = makeScatterplotSquare;
|
function makeScatterplotSquare() {
var data = makeNormallyDistributedData(100, 50, 20, 60, 10);
var dataset = {data: data, metadata: {cssClass: "transparent-square"}};
var xScale = new Plottable.LinearScale();
var xAxis = new Plottable.XAxis(xScale, "bottom").tickSize(2, 0);
var yScale = new Plottable.LinearScale();
var yAxis = new Plottable.YAxis(yScale, "left")
.tickLabelPosition("bottom")
.tickSize(50);
function rAccessor() { return 5; }
var r = new Plottable.SquareRenderer(dataset, xScale, yScale,
null, null, rAccessor);
var svg = d3.select("#scatterplot-square");
var innerTable = new Plottable.Table([[yAxis, r],
[null, xAxis]]);
innerTable.renderTo(svg);
xScale.padDomain().nice();
yScale.padDomain().nice();
};
window.onload = makeScatterplotSquare;
|
Decrease high timeout in ci | var path = require('path');
var webpack = require('./webpack.config');
process.env.CHROME_BIN = require('puppeteer').executablePath();
module.exports = function (config) {
config.set({
basePath: '.',
frameworks: ['mocha'],
reporters: ['mocha'],
client: {
captureConsole: true,
},
files: [
{pattern: path.resolve('./build/injector.js'), watched: false},
{pattern: process.env.KARMA_FILE_PATTERN, watched: false}
],
preprocessors: {
'build/injector.js': ['webpack'],
'src/*.spec.ts': ['webpack', 'sourcemap']
},
mime: {
'text/x-typescript': ['ts','tsx']
},
webpack: webpack,
webpackMiddleware: {
noInfo: true,
stats: 'errors-only'
},
port: 9876,
colors: true,
singleRun: true,
logLevel: config.LOG_INFO
});
};
| var path = require('path');
var webpack = require('./webpack.config');
process.env.CHROME_BIN = require('puppeteer').executablePath();
module.exports = function (config) {
config.set({
basePath: '.',
frameworks: ['mocha'],
reporters: ['mocha'],
client: {
captureConsole: true,
mocha: {
timeout : 10000, // 10 seconds - upped from 2 seconds
retries: 3 // Allow for slow server on CI.
}
},
files: [
{pattern: path.resolve('./build/injector.js'), watched: false},
{pattern: process.env.KARMA_FILE_PATTERN, watched: false}
],
preprocessors: {
'build/injector.js': ['webpack'],
'src/*.spec.ts': ['webpack', 'sourcemap']
},
mime: {
'text/x-typescript': ['ts','tsx']
},
webpack: webpack,
webpackMiddleware: {
noInfo: true,
stats: 'errors-only'
},
browserNoActivityTimeout: 31000, // 31 seconds - upped from 10 seconds
browserDisconnectTimeout: 31000, // 31 seconds - upped from 2 seconds
browserDisconnectTolerance: 2,
port: 9876,
colors: true,
singleRun: true,
logLevel: config.LOG_INFO
});
};
|
Fix path on .scss file detected | var path = require('path');
var findParentDir = require('find-parent-dir');
var fs = require('fs');
function resolve(targetUrl, source) {
var packageRoot = findParentDir.sync(source, 'node_modules');
if (!packageRoot) {
return null;
}
var filePath = path.resolve(packageRoot, 'node_modules', targetUrl);
var isPotentiallyDirectory = !path.extname(filePath);
if (isPotentiallyDirectory) {
if (fs.existsSync(filePath + '.scss')) {
return filePath + '.scss';
}
if (fs.existsSync(filePath)) {
return path.resolve(filePath, 'index');
}
}
if (fs.existsSync(path.dirname(filePath))) {
return filePath;
}
return resolve(targetUrl, path.dirname(packageRoot));
}
module.exports = function importer (url, prev, done) {
return (url[ 0 ] === '~') ? { file: resolve(url.substr(1), prev) } : null;
};
| var path = require('path');
var findParentDir = require('find-parent-dir');
var fs = require('fs');
function resolve(targetUrl, source) {
var packageRoot = findParentDir.sync(source, 'node_modules');
if (!packageRoot) {
return null;
}
var filePath = path.resolve(packageRoot, 'node_modules', targetUrl);
var isPotentiallyDirectory = !path.extname(filePath);
if (isPotentiallyDirectory) {
if (fs.existsSync(filePath + '.scss')) {
return path.resolve(filePath, 'index');
}
if (fs.existsSync(filePath)) {
return path.resolve(filePath, 'index');
}
}
if (fs.existsSync(path.dirname(filePath))) {
return filePath;
}
return resolve(targetUrl, path.dirname(packageRoot));
}
module.exports = function importer (url, prev, done) {
return (url[ 0 ] === '~') ? { file: resolve(url.substr(1), prev) } : null;
};
|
Fix addAlamidRoute helper to work with current middler version | "use strict";
var middler = require("middler"),
httpCrud = require("../shared/helpers/httpCrud.js");
var router = {
http: null,
alamid:null
};
function get(type) {
type = type || "alamid";
if (router[type] === null) {
router[type] = middler();
//extension to be able to use crud methods instead of HTTP-methods
router[type].addAlamidRoute = function (methods, route, fns) {
if (!Array.isArray(methods)) {
methods = [methods];
}
methods.forEach(function (method, index) {
methods[index] = httpCrud.convertCRUDtoHTTP(method);
});
this.add(methods, route, fns);
};
}
return router[type];
}
function set(routerInstance, type) {
type = type || "alamid";
return router[type] = routerInstance;
}
function reset (type) {
if (type !== undefined) {
router[type] = null;
return;
}
router.alamid = null;
router.http = null;
}
exports.get = get;
exports.set = set;
exports.reset = reset; | "use strict";
var middler = require("middler"),
httpCrud = require("../shared/helpers/httpCrud.js");
var router = {
http: null,
alamid:null
};
//prototype extension to be able to use crud methods instead of HTTP-methods
middler.Middler.prototype.addAlamidRoute = function (methods, route, fns) {
if (!Array.isArray(methods)) {
methods = [methods];
}
methods.forEach(function (method, index) {
methods[index] = httpCrud.convertCRUDtoHTTP(method);
});
this.add(methods, route, fns);
};
function get(type) {
type = type || "alamid";
if (router[type] === null) {
router[type] = middler();
}
return router[type];
}
function set(routerInstance, type) {
type = type || "alamid";
return router[type] = routerInstance;
}
function reset (type) {
if (type !== undefined) {
router[type] = null;
return;
}
router.alamid = null;
router.http = null;
}
exports.get = get;
exports.set = set;
exports.reset = reset; |
Replace echo with `p` or `print_unescaped`
Using echo instead of `p` or `print_unescaped` is a bad style, to prevent people from copying it I've adjusted it. | <form action="<?php print_unescaped(OC_Helper::linkToRoute('core_lostpassword_reset', $_['args'])) ?>" method="post">
<fieldset>
<?php if($_['success']): ?>
<h1><?php p($l->t('Your password was reset')); ?></h1>
<p><a href="<?php print_unescaped(OC_Helper::linkTo('', 'index.php')) ?>/"><?php p($l->t('To login page')); ?></a></p>
<?php else: ?>
<p class="infield">
<label for="password" class="infield"><?php p($l->t('New password')); ?></label>
<input type="password" name="password" id="password" value="" required />
</p>
<input type="submit" id="submit" value="<?php p($l->t('Reset password')); ?>" />
<?php endif; ?>
</fieldset>
</form>
| <form action="<?php echo OC_Helper::linkToRoute('core_lostpassword_reset', $_['args']) ?>" method="post">
<fieldset>
<?php if($_['success']): ?>
<h1><?php echo $l->t('Your password was reset'); ?></h1>
<p><a href="<?php echo OC_Helper::linkTo('', 'index.php') ?>/"><?php echo $l->t('To login page'); ?></a></p>
<?php else: ?>
<p class="infield">
<label for="password" class="infield"><?php echo $l->t( 'New password' ); ?></label>
<input type="password" name="password" id="password" value="" required />
</p>
<input type="submit" id="submit" value="<?php echo $l->t('Reset password'); ?>" />
<?php endif; ?>
</fieldset>
</form>
|
Convert to unicode for printing. | # Comet VOEvent Broker.
# Example event handler: print an event.
import lxml.etree as ElementTree
from zope.interface import implementer
from twisted.plugin import IPlugin
from comet.icomet import IHandler
# Event handlers must implement IPlugin and IHandler.
@implementer(IPlugin, IHandler)
class EventPrinter(object):
# Simple example of an event handler plugin. This simply prints the
# received event to standard output.
# The name attribute enables the user to specify plugins they want on the
# command line.
name = "print-event"
# When the handler is called, it is passed an instance of
# comet.utility.xml.xml_document.
def __call__(self, event):
"""
Print an event to standard output.
"""
print(ElementTree.tounicode(event.element))
# This instance of the handler is what actually constitutes our plugin.
print_event = EventPrinter()
| # Comet VOEvent Broker.
# Example event handler: print an event.
import lxml.etree as ElementTree
from zope.interface import implementer
from twisted.plugin import IPlugin
from comet.icomet import IHandler
# Event handlers must implement IPlugin and IHandler.
@implementer(IPlugin, IHandler)
class EventPrinter(object):
# Simple example of an event handler plugin. This simply prints the
# received event to standard output.
# The name attribute enables the user to specify plugins they want on the
# command line.
name = "print-event"
# When the handler is called, it is passed an instance of
# comet.utility.xml.xml_document.
def __call__(self, event):
"""
Print an event to standard output.
"""
print(ElementTree.tostring(event.element))
# This instance of the handler is what actually constitutes our plugin.
print_event = EventPrinter()
|
Add more chat room infos. | module.exports = {
appKey : 'mgb7ka1nbs3wg',
appSecret : 'm1Rv2MHHND',
token : {
userId : '0001',
name : 'TestUser',
portraitUri : 'http://rongcloud.cn/images/logo.png'
},
message : {
fromUserId : '546eb521c613156d331e91bb',
toUserId : '5460603c1002a6e311f89e7f',
textMsg : 'Hello, world!'
},
group : {
userId : '5460603c1002a6e311f89e7f',
groupIdNamePairs : { 'ProgrammerGroup1' : '程序猿交流群1', 'DriverGroup1' : '赛车手爱好者2群' }
},
chatroom : {
chatroomIdNamePairs : { 'EatingFans' : '吃货大本营', 'ProCylcing' : '骑行专家', 'DriodGeek' : '手机极客', 'HackerHome' : '黑客之家' }
}
} | module.exports = {
appKey : 'mgb7ka1nbs3wg',
appSecret : 'm1Rv2MHHND',
token : {
userId : '0001',
name : 'TestUser',
portraitUri : 'http://rongcloud.cn/images/logo.png'
},
message : {
fromUserId : '546eb521c613156d331e91bb',
toUserId : '5460603c1002a6e311f89e7f',
textMsg : 'Hello, world!'
},
group : {
userId : '5460603c1002a6e311f89e7f',
groupIdNamePairs : { 'ProgrammerGroup1' : '程序猿交流群1', 'DriverGroup1' : '赛车手爱好者2群' }
}
} |
Change confirm dialog so that it doesn't show cancel button if not callback | define([
], function() {
"use strict";
return {
props: {
title: {
type: String,
default: "Confirm"
},
closeCallback: {
type: Function,
default: undefined
},
okCallback: {
type: Function,
default: function() {}
}
},
template: '<transition name="modal">' +
' <div class="modal-mask">' +
' <div class="modal-wrapper">' +
' <div class="modal-container">' +
' <div class="modal-header"><slot name="header"><h4>{{ title }}</h4></slot></div>' +
' <div class="modal-body"><slot></slot></div>' +
' <div class="modal-footer text-right">' +
' <button v-if="closeCallback !== undefined" type="button" class="btn btn-default" @click="closeCallback">Cancel</button>' +
' <button class="btn btn-primary primary" @click="okCallback">Ok</button>' +
' </div>' +
' </div>' +
' </div>' +
' </div>' +
'</transition>'
};
});
| define([
], function() {
"use strict";
return {
props: {
title: {
type: String,
default: "Confirm"
},
closeCallback: {
type: Function,
default: function() {}
},
okCallback: {
type: Function,
default: function() {}
}
},
template: '<transition name="modal">' +
' <div class="modal-mask">' +
' <div class="modal-wrapper">' +
' <div class="modal-container">' +
' <div class="modal-header"><slot name="header"><h4>{{ title }}</h4></slot></div>' +
' <div class="modal-body"><slot></slot></div>' +
' <div class="modal-footer text-right">' +
' <button type="button" class="btn btn-default" @click="closeCallback">Cancel</button>' +
' <button class="btn btn-primary primary" @click="okCallback">Ok</button>' +
' </div>' +
' </div>' +
' </div>' +
' </div>' +
'</transition>'
};
});
|
Use new Component.mount API for documentation. | var Documentation = require('./model/Documentation');
var Component = require('../ui/Component');
var DocumentationReader = require('./DocumentationReader');
var $ = require('../util/jquery');
var _ = require('../util/helpers');
var importDocumentation = require('./model/importDocumentation');
var _loadDocument = function(cb) {
_.request('GET', './documentation.json', null, function(err, rawDoc) {
if (err) { console.error(err); cb(err); }
var doc = importDocumentation(rawDoc);
window.doc = doc;
// console.log('LE DOC', doc);
cb(null, doc);
});
};
$(function() {
var doc = new Documentation();
window.doc = doc;
_loadDocument(function(err, doc) {
Component.mount(DocumentationReader, {
doc: doc
}, $('body'));
});
}); | var Documentation = require('./model/Documentation');
var Component = require('../ui/Component');
var DocumentationReader = require('./DocumentationReader');
var $$ = Component.$$;
var $ = require('../util/jquery');
var _ = require('../util/helpers');
var importDocumentation = require('./model/importDocumentation');
var _loadDocument = function(cb) {
_.request('GET', './documentation.json', null, function(err, rawDoc) {
if (err) { console.error(err); cb(err); }
var doc = importDocumentation(rawDoc);
window.doc = doc;
// console.log('LE DOC', doc);
cb(null, doc);
});
};
$(function() {
var doc = new Documentation();
window.doc = doc;
_loadDocument(function(err, doc) {
Component.mount($$(DocumentationReader, {
doc: doc
}), $('body'));
});
}); |
Replace remaining instantiation from constructor | var common = require('../../common');
var connection = common.createConnection();
var assert = require('assert');
var rows = undefined;
var rows1 = undefined;
var fields = undefined;
var fields1 = undefined;
var buf = Buffer.from([0x80, 0x90, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 100, 255, 255]);
connection.execute('SELECT HEX(?) as buf', [buf], function(
err,
_rows,
_fields
) {
if (err) {
throw err;
}
rows = _rows;
fields = _fields;
});
connection.query('SELECT HEX(?) as buf', [buf], function(err, _rows, _fields) {
if (err) {
throw err;
}
rows1 = _rows;
fields1 = _fields;
connection.end();
});
process.on('exit', function() {
assert.deepEqual(rows, [{ buf: buf.toString('hex').toUpperCase() }]);
assert.deepEqual(rows1, [{ buf: buf.toString('hex').toUpperCase() }]);
});
| var common = require('../../common');
var connection = common.createConnection();
var assert = require('assert');
var rows = undefined;
var rows1 = undefined;
var fields = undefined;
var fields1 = undefined;
var buf = Buffer([0x80, 0x90, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 100, 255, 255]);
connection.execute('SELECT HEX(?) as buf', [buf], function(
err,
_rows,
_fields
) {
if (err) {
throw err;
}
rows = _rows;
fields = _fields;
});
connection.query('SELECT HEX(?) as buf', [buf], function(err, _rows, _fields) {
if (err) {
throw err;
}
rows1 = _rows;
fields1 = _fields;
connection.end();
});
process.on('exit', function() {
assert.deepEqual(rows, [{ buf: buf.toString('hex').toUpperCase() }]);
assert.deepEqual(rows1, [{ buf: buf.toString('hex').toUpperCase() }]);
});
|
Change function to arrow function
- Add missing semicolons
Signed-off-by: Kien Ha <3e36ebd6a7c89ee7d9a20a5fbbffc571f107e566@gmail.com> | "use strict";
function setAllBlogId() {
let blogLinkElements = document.querySelectorAll('.blog-link');
for(let i = blogLinkElements.length - 1; i >= 0; i--) {
blogLinkElements[i].id = 'blog-' + (i+1);
}
}
setAllBlogId();
$(document).ready(() => {
$("#blog-1").click(() => {
$("#blog-1").load("blogs/2018-06-05-remove-persistent-running-app-in-notification-background.html #blogPost");
});
});
$(document).ready(() => {
$("#blog-2").click(() => {
$("#blog-2").load("blogs/2016-08-29-thoughts-on-internship-with-OpenDayLight.html #blogPost");
});
});
| "use strict";
function setAllBlogId() {
let blogLinkElements = document.querySelectorAll('.blog-link');
for(let i = blogLinkElements.length - 1; i >= 0; i--) {
blogLinkElements[i].id = 'blog-' + (i+1);
}
}
setAllBlogId();
$(document).ready(function() {
$("#blog-1").click(function() {
$("#blog-1").load("blogs/2018-06-05-remove-persistent-running-app-in-notification-background.html #blogPost")
});
});
$(document).ready(function() {
$("#blog-2").click(function() {
$("#blog-2").load("blogs/2016-08-29-thoughts-on-internship-with-OpenDayLight.html #blogPost")
});
});
|
Create junction to an absolute path | // +build windows
package gps
import (
"os/exec"
"testing"
)
// setupUsingJunctions inflates fs onto the host file system, but uses Windows
// directory junctions for links.
func (fs filesystemState) setupUsingJunctions(t *testing.T) {
fs.setupDirs(t)
fs.setupFiles(t)
fs.setupJunctions(t)
}
func (fs filesystemState) setupJunctions(t *testing.T) {
for _, link := range fs.links {
from := link.path.prepend(fs.root)
to := fsPath{link.to}.prepend(fs.root)
// There is no way to make junctions in the standard library, so we'll just
// do what the stdlib's os tests do: run mklink.
//
// Also, all junctions must point to absolute paths.
output, err := exec.Command("cmd", "/c", "mklink", "/J", from.String(), to.String()).CombinedOutput()
if err != nil {
t.Fatalf("failed to run mklink %v %v: %v %q", from.String(), to.String(), err, output)
}
}
}
| // +build windows
package gps
import (
"os/exec"
"testing"
)
// setupUsingJunctions inflates fs onto the host file system, but uses Windows
// directory junctions for links.
func (fs filesystemState) setupUsingJunctions(t *testing.T) {
fs.setupDirs(t)
fs.setupFiles(t)
fs.setupJunctions(t)
}
func (fs filesystemState) setupJunctions(t *testing.T) {
for _, link := range fs.links {
p := link.path.prepend(fs.root)
// There is no way to make junctions in the standard library, so we'll just
// do what the stdlib's os tests do: run mklink.
output, err := exec.Command("cmd", "/c", "mklink", "/J", p.String(), link.to).CombinedOutput()
if err != nil {
t.Fatalf("failed to run mklink %v %v: %v %q", p.String(), link.to, err, output)
}
}
}
|
Write init setting and pick a start | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from ds_min_priority_queue_tuple import MinPriorityQueue
def prim(w_graph_d):
"""Prim's algorithm for minimum spanning tree in weighted graph.
Time complexity for graph G(V, E): (|V|+|E|)log(|V|).
"""
min_pq = MinPriorityQueue()
key_d = {v: np.inf for v in w_graph_d.keys()}
previous_d = {v: None for v in w_graph_d.keys()}
visited_d = {v: False for v in w_graph_d.keys()}
# Pick an arbitrary vertex as start.
s = w_graph_d.keys()[0]
visited_d[s] = True
key_d[s] = 0
min_pq.insert([key_d[s], s])
pass
def main():
w_graph_d = {
'a': {'b': 1, 'd': 4, 'e': 3},
'b': {'a': 1, 'd': 4, 'e': 2},
'c': {'e': 4, 'f': 5},
'd': {'a': 4, 'b': 4, 'e': 4},
'e': {'a': 3, 'b': 2, 'c': 4, 'd': 4, 'f': 7},
'f': {'c': 5, 'e': 7}
}
print('w_graph_d:\n{}'.format(w_graph_d))
print('Prim minimum spanning tree')
pass
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from ds_min_priority_queue_tuple import MinPriorityQueue
def prim():
"""Prim's algorithm for minimum spanning tree in weighted graph.
Time complexity for graph G(V, E): (|V|+|E|)log(|V|).
"""
pass
def main():
w_graph_d = {
'a': {'b': 1, 'd': 4, 'e': 3},
'b': {'a': 1, 'd': 4, 'e': 2},
'c': {'e': 4, 'f': 5},
'd': {'a': 4, 'b': 4, 'e': 4},
'e': {'a': 3, 'b': 2, 'c': 4, 'd': 4, 'f': 7},
'f': {'c': 5, 'e': 7}
}
start_vertex = 'a'
print('w_graph_d:\n{}'.format(w_graph_d))
print('Prim minimum spanning tree from {}:'.format(start_vertex))
pass
if __name__ == '__main__':
main()
|
core: Fix MissingFormatArgumentException in ParseRuntimeException when args array is empty | /*
* Copyright (C) 2009-2011 Mathias Doenitz
*
* 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 org.parboiled.errors;
/**
* Exception that is thrown for any problem during the parsing run that cannot be overcome automatically.
*/
public class ParserRuntimeException extends RuntimeException {
public ParserRuntimeException() {
}
public ParserRuntimeException(String message) {
super(message);
}
public ParserRuntimeException(String message, Throwable cause) {
super(message, cause);
}
public ParserRuntimeException(String message, Object... messageArgs) {
super(String.format(message, messageArgs));
}
public ParserRuntimeException(Throwable cause, String message, Object... messageArgs) {
super(messageArgs.length > 0 ? String.format(message, messageArgs) : message, cause);
}
public ParserRuntimeException(Throwable cause) {
super(cause);
}
} | /*
* Copyright (C) 2009-2011 Mathias Doenitz
*
* 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 org.parboiled.errors;
/**
* Exception that is thrown for any problem during the parsing run that cannot be overcome automatically.
*/
public class ParserRuntimeException extends RuntimeException {
public ParserRuntimeException() {
}
public ParserRuntimeException(String message) {
super(message);
}
public ParserRuntimeException(String message, Throwable cause) {
super(message, cause);
}
public ParserRuntimeException(String message, Object... messageArgs) {
super(String.format(message, messageArgs));
}
public ParserRuntimeException(Throwable cause, String message, Object... messageArgs) {
super(String.format(message, messageArgs), cause);
}
public ParserRuntimeException(Throwable cause) {
super(cause);
}
} |
Add template for bags get and post verbs. | var express = require('express');
var app = express();
var bodyParser = require('body-parser');
//Parse setup
GLOBAL.Parse = require('parse').Parse;
Parse.initialize("W42PEkh5M824lpvx1FZsJxWBP6Eq7o9rvNHyJFP5", "5OA1f5vv9VbcCCT1reXAckJYPylUszIcRhDWUfT7");
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// ROUTES FOR OUR API
// get an instance of the express Router
var router = express.Router();
router.get('/', function(req, res) {
res.json({ message: 'Slingshot API' });
});
router.route('/bags')
.get(function(req, res) {
res.send('GET request for: bags');
})
.post(function(req, res) {
res.send('POST request for: bags');
});
app.use('/api', router);
module.exports = app; | var express = require('express');
var app = express();
var bodyParser = require('body-parser');
//Parse setup
GLOBAL.Parse = require('parse').Parse;
Parse.initialize("W42PEkh5M824lpvx1FZsJxWBP6Eq7o9rvNHyJFP5", "5OA1f5vv9VbcCCT1reXAckJYPylUszIcRhDWUfT7");
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
function savetoparse(str) {
var TestObject = Parse.Object.extend("TestObject");
var testObject = new TestObject();
testObject.save({query: str}, {
success: function(object) {
console.log("Saved: " + str);
},
error: function(model, error) {
console.log("Failed!");
}
});
}
// test route to make sure everything is working (accessed at GET http://localhost:3000/api)
router.get('/', function(req, res) {
res.json({ message: 'Slingshot API' });
});
router.get('/save/:str', function(req, res) {
res.json({ str: req.params.str});
savetoparse(req.params.str);
});
app.use('/api', router);
module.exports = app; |
Fix naive stream reading implementation. | import CodeGenerator from './code-generator';
import {CodeGeneratorRequest} from "google-protobuf/google/protobuf/compiler/plugin_pb.js";
const generateCode = (serializedRequest) => {
const request = CodeGeneratorRequest.deserializeBinary(serializedRequest);
const generator = new CodeGenerator();
const response = generator.generate(request);
const serializedResponse = response.serializeBinary();
return Buffer.from(serializedResponse); // TODO: is Buffer.from necessary?
};
const stdin = (stream) => new Promise((resolve, reject) => {
let value = [];
let length = 0;
stream.on("readable", () => {
var chunk;
while ((chunk = stream.read())) {
value.push(chunk);
length += chunk.length;
}
});
stream.on("end", () => {
resolve(Buffer.concat(value, length));
});
});
const main = () => stdin(process.stdin)
.then((data) => new Uint8Array(data))
.then(generateCode)
.then((output) => process.stdout.write(output, {encoding:'binary'}))
.then(() => process.exit(0))
.catch((error) => {
console.warn(error);
process.exit(1);
});
export default main;
| import CodeGenerator from './code-generator';
import {CodeGeneratorRequest} from "google-protobuf/google/protobuf/compiler/plugin_pb.js";
const generateCode = (serializedRequest) => {
const request = CodeGeneratorRequest.deserializeBinary(serializedRequest);
const generator = new CodeGenerator();
const response = generator.generate(request);
const serializedResponse = response.serializeBinary();
return Buffer.from(serializedResponse); // TODO: is Buffer.from necessary?
};
const main = () => {
process.stdin.on('readable', () => {
const data = process.stdin.read();
if (data == null) return;
const input = new Uint8Array(data); // TODO: s/Uint8Array/Buffer
const output = generateCode(input);
process.stdout.write(output, {encoding:'binary'});
process.exit(0);
});
};
export default main;
|
[Fix] Add __doc__ to module functions | '''Due to the needs arising from completing the project on time, I have defined redundant.py
which will hold replacement modules as I migrate from file based application to lists only web application. This modules
so far will offer the capabilities of registration, creating a shopping list and adding items into
a shopping list'''
global account
account=[]
def register(username,email,password):
'''registration list'''
account.append(username)
account.append(email)
account.append(password)
return account
global shopping_list_container
shopping_list_container=[]#contain shopping lists only
def create(list_name):
'''container of names of shopping lists'''
#list_name=[]
shopping_list_container.append(list_name)
return shopping_list_container#list of dictionaries
def list_update(nameoflist,item):
'''adding item to a given name of list'''
nameoflist.append(item)
shopping_list_container.append(nameoflist)
global itemsdictionary
itemsdictionary={}
def create1(slist):
'''update shopping lists with key (names) and items(as dictionaris)'''
itemsdictionary.update(slist)
global shared_shopping_list_container
shared_shopping_list_container=[]
def create3(list_name):
'''container for the shared lists. In future may be integrated with facebook'''
#list_name=[]
shared_shopping_list_container.append(list_name)
return shared_shopping_list_container#list of dictionaries
global shareditemsdictionary
shareditemsdictionary={}
def create2(slist):
'''updating shared dictionary'''
shareditemsdictionary.update(slist)
| '''Due to the needs arising from completing the project on time, I have defined redundant.py
which will hold replacement modules as I migrate from file based application to lists only web application. This modules
so far will offer the capabilities of registration, creating a shopping list and adding items into
a shopping list'''
global account
account=[]
def register(username,email,password):
account.append(username)
account.append(email)
account.append(password)
return account
global shopping_list_container
shopping_list_container=[]#contain shopping lists only
def create(list_name):
#list_name=[]
shopping_list_container.append(list_name)
return shopping_list_container#list of dictionaries
def list_update(nameoflist,item):
nameoflist.append(item)
shopping_list_container.append(nameoflist)
global itemsdictionary
itemsdictionary={}
def create1(slist):
itemsdictionary.update(slist)
global shared_shopping_list_container
shared_shopping_list_container=[]
def create3(list_name):
#list_name=[]
shared_shopping_list_container.append(list_name)
return shared_shopping_list_container#list of dictionaries
global shareditemsdictionary
shareditemsdictionary={}
def create2(slist):
shareditemsdictionary.update(slist)
|
Make documentation more explicit for WTForms deprecation. | import warnings
from wtforms import form
from wtforms.ext.i18n.utils import get_translations
translations_cache = {}
class Form(form.Form):
"""
Base form for a simple localized WTForms form.
**NOTE** this class is now un-necessary as the i18n features have
been moved into the core of WTForms, but it will be kept for
compatibility reasons until WTForms 1.2.
This will use the stdlib gettext library to retrieve an appropriate
translations object for the language, by default using the locale
information from the environment.
If the LANGUAGES class variable is overridden and set to a sequence of
strings, this will be a list of languages by priority to use instead, e.g::
LANGUAGES = ['en_GB', 'en']
One can also provide the languages by passing `LANGUAGES=` to the
constructor of the form.
Translations objects are cached to prevent having to get a new one for the
same languages every instantiation.
"""
LANGUAGES = None
def __init__(self, *args, **kwargs):
warnings.warn('i18n is now in core, wtforms.ext.i18n will be removed in WTForms 1.2', DeprecationWarning)
super(Form, self).__init__(*args, **kwargs)
def _get_translations(self):
languages = tuple(self.LANGUAGES) if self.LANGUAGES else None
if languages not in translations_cache:
translations_cache[languages] = get_translations(languages)
return translations_cache[languages]
| import warnings
from wtforms import form
from wtforms.ext.i18n.utils import get_translations
translations_cache = {}
class Form(form.Form):
"""
Base form for a simple localized WTForms form.
This will use the stdlib gettext library to retrieve an appropriate
translations object for the language, by default using the locale
information from the environment.
If the LANGUAGES class variable is overridden and set to a sequence of
strings, this will be a list of languages by priority to use instead, e.g::
LANGUAGES = ['en_GB', 'en']
One can also provide the languages by passing `LANGUAGES=` to the
constructor of the form.
Translations objects are cached to prevent having to get a new one for the
same languages every instantiation.
"""
LANGUAGES = None
def __init__(self, *args, **kwargs):
warnings.warn('wtforms.ext.i18n will be removed in WTForms 1.2', DeprecationWarning)
super(Form, self).__init__(*args, **kwargs)
def _get_translations(self):
languages = tuple(self.LANGUAGES) if self.LANGUAGES else None
if languages not in translations_cache:
translations_cache[languages] = get_translations(languages)
return translations_cache[languages]
|
Disable debug logging in socket.io | // Load required modules
var http = require("http"); // http server core module
var express = require("express"); // web framework external module
var io = require("socket.io"); // web socket external module
var easyrtc = require("easyrtc"); // EasyRTC external module
// Setup and configure Express http server. Expect a subfolder called "static" to be the web root.
var httpApp = express();
httpApp.configure(function() {
httpApp.use(express.static(__dirname + "/static/"));
});
// Start Express http server on port 8080
var webServer = http.createServer(httpApp).listen(8080);
// Start Socket.io so it attaches itself to Express server
var socketServer = io.listen(webServer, {"log level":1});
// Start EasyRTC server
var rtc = easyrtc.listen(httpApp, socketServer);
| // Load required modules
var http = require("http"); // http server core module
var express = require("express"); // web framework external module
var io = require("socket.io"); // web socket external module
var easyrtc = require("easyrtc"); // EasyRTC external module
// Setup and configure Express http server. Expect a subfolder called "static" to be the web root.
var httpApp = express();
httpApp.configure(function() {
httpApp.use(express.static(__dirname + "/static/"));
});
// Start Express http server on port 8080
var webServer = http.createServer(httpApp).listen(8080);
// Start Socket.io so it attaches itself to Express server
var socketServer = io.listen(webServer);
// Start EasyRTC server
var rtc = easyrtc.listen(httpApp, socketServer);
|
Fix wrong handling of paste event that would result in streaming from a magnet if pasting into input for download for eg | export default {
mounted () {
document.addEventListener('paste', this.handlePaste)
},
beforeDestroy () {
document.removeEventListener('paste', this.handlePaste)
},
computed: {
isClientPage () {
return this.$route.path === '/torrenting'
}
},
methods: {
/**
* @param {ClipboardEvent} e
*/
handlePaste (e) {
const text = e.clipboardData.getData('text')
if (e.target.tagName.toUpperCase() === 'INPUT') return
if (/magnet:\?/.test(text)) {
if (!this.isClientPage) {
e.preventDefault()
this.$store.dispatch('streaming/play', {
link: text,
isTorrent: true,
name: null,
neighbours: null
})
}
}
}
}
}
| export default {
mounted () {
document.addEventListener('paste', this.handlePaste)
},
beforeDestroy () {
document.removeEventListener('paste', this.handlePaste)
},
computed: {
isClientPage () {
return this.$route.path === '/torrenting'
}
},
methods: {
handlePaste (e) {
const text = e.clipboardData.getData('text')
if (/magnet:\?/.test(text)) {
if (!this.isClientPage) {
e.preventDefault()
this.$store.dispatch('streaming/play', {
link: text,
isTorrent: true,
name: null,
neighbours: null
})
}
}
}
}
}
|
Use attr access vs key | import yaml
from builder import utils
def bind_subparser(subparsers):
parser_destroy = subparsers.add_parser('destroy')
parser_destroy.set_defaults(func=destroy)
return parser_destroy
def destroy(args, cloud, tracker):
"""Destroy a previously built environment."""
created_servers = set()
already_gone = set()
for r in tracker.last_block:
if r.kind == 'server_create':
created_servers.add(r.server.name)
if r.kind == 'server_destroy':
already_gone.add(r.name)
servers = created_servers - already_gone
if not servers:
print("Nothing to destroy.")
else:
while servers:
server = servers.pop()
print("Destroying server %s, please wait..." % server)
cloud.delete_server(server, wait=True)
tracker.record({'kind': 'server_destroy', 'name': server})
# TODO(harlowja): we should be able to remove individual creates,
# but for now this will be the crappy way of closing off the
# previously unfinished business.
if tracker.status == utils.Tracker.INCOMPLETE:
tracker.mark_end()
| import yaml
from builder import utils
def bind_subparser(subparsers):
parser_destroy = subparsers.add_parser('destroy')
parser_destroy.set_defaults(func=destroy)
return parser_destroy
def destroy(args, cloud, tracker):
"""Destroy a previously built environment."""
created_servers = set()
already_gone = set()
for r in tracker.last_block:
if r['kind'] == 'server_create':
created_servers.add(r.server.name)
if r['kind'] == 'server_destroy':
already_gone.add(r.name)
servers = created_servers - already_gone
if not servers:
print("Nothing to destroy.")
else:
while servers:
server = servers.pop()
print("Destroying server %s, please wait..." % server)
cloud.delete_server(server, wait=True)
tracker.record({'kind': 'server_destroy', 'name': server})
# TODO(harlowja): we should be able to remove individual creates,
# but for now this will be the crappy way of closing off the
# previously unfinished business.
if tracker.status == utils.Tracker.INCOMPLETE:
tracker.mark_end()
|
Enable event handling before keyring is loaded | /**
* Mailvelope - secure email with OpenPGP encryption for Webmail
* Copyright (C) 2012-2017 Mailvelope GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import {initBrowserRuntime, initNativeMessaging} from './lib/browser.runtime';
import {init as initModel} from './modules/pgpModel';
import {init as initKeyring} from './modules/keyring';
import {initController} from './controller/main.controller';
import {initScriptInjection} from './lib/inject';
async function main() {
initBrowserRuntime();
initController();
await initModel();
await initNativeMessaging();
await initKeyring();
initScriptInjection();
}
main();
| /**
* Mailvelope - secure email with OpenPGP encryption for Webmail
* Copyright (C) 2012-2017 Mailvelope GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import {initBrowserRuntime, initNativeMessaging} from './lib/browser.runtime';
import {init as initModel} from './modules/pgpModel';
import {init as initKeyring} from './modules/keyring';
import {initController} from './controller/main.controller';
import {initScriptInjection} from './lib/inject';
async function main() {
initBrowserRuntime();
await initModel();
await initNativeMessaging();
await initKeyring();
initController();
initScriptInjection();
}
main();
|
Use recommended react plugin for eslint
- this avoids the annoying `unused variable 'React' error`, becuase React needs to be in scope for jsx | module.exports = {
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": ["eslint:recommended", "plugin:react/recommended"],
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"double"
],
"semi": [
"error",
"never"
]
}
}
| module.exports = {
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"double"
],
"semi": [
"error",
"never"
]
}
}
|
Remove redundant parenthesis in Image | import datetime
from utils.utils import limit_file_name
class Image:
_file_name_pattern = "reddit_%s_%s_%s_album_%s_%s_%s"
def __init__(self, url, post, image_file):
self.post_id = post.id
self.url = url
self.sub_display_name = post.subreddit.display_name
self.image_file = limit_file_name(image_file)
self.domain = post.domain
self.created = datetime.datetime.fromtimestamp(post.created).strftime("%y%m%d")
if "/a/" in post.url:
self.album_id = post.url[post.url.index("/a/") + 3:]
elif "/gallery/" in post.url:
self.album_id = post.url[post.url.index("/gallery/") + 9:]
else:
self.album_id = None
self.local_file_name = self._file_name_pattern % (
self.created, self.sub_display_name, self.post_id, self.album_id, self.domain, self.image_file)
| import datetime
from utils.utils import limit_file_name
class Image():
_file_name_pattern = "reddit_%s_%s_%s_album_%s_%s_%s"
def __init__(self, url, post, image_file):
self.post_id = post.id
self.url = url
self.sub_display_name = post.subreddit.display_name
self.image_file = limit_file_name(image_file)
self.domain = post.domain
self.created = datetime.datetime.fromtimestamp(post.created).strftime("%y%m%d")
if "/a/" in post.url:
self.album_id = post.url[post.url.index("/a/") + 3:]
elif "/gallery/" in post.url:
self.album_id = post.url[post.url.index("/gallery/") + 9:]
else:
self.album_id = None
self.local_file_name = self._file_name_pattern % (
self.created, self.sub_display_name, self.post_id, self.album_id, self.domain, self.image_file)
|
chore(admin): Rename docs actions source file chunk to `docs-actions`
Refs: TOCDEV-3113 | import React, {lazy, Suspense} from 'react'
import {connect} from 'react-redux'
import PropTypes from 'prop-types'
import {actionEmitter} from 'tocco-app-extensions'
import {LoadMask} from 'tocco-ui'
import {consoleLogger} from 'tocco-util'
const actions = {
'create-folder': lazy(() => import(/* webpackChunkName: "docs-actions" */'./actions/CreateFolder')),
'delete': lazy(() => import(/* webpackChunkName: "docs-actions" */'./actions/Delete'))
}
const renderLoader = () => <LoadMask/>
const LazyAction = props => {
const {appId} = props
const LazyAction = actions[appId]
if (!LazyAction) {
consoleLogger.logError(`no action found with id: ${appId}`)
return null
}
const ActionComponent = connect(null, {
emitAction: action => actionEmitter.dispatchEmittedAction(action)
})(LazyAction)
return <Suspense fallback={renderLoader()}>
<ActionComponent {...props}/>
</Suspense>
}
LazyAction.propTypes = {
appId: PropTypes.string.isRequired
}
export default LazyAction
| import React, {lazy, Suspense} from 'react'
import {connect} from 'react-redux'
import PropTypes from 'prop-types'
import {actionEmitter} from 'tocco-app-extensions'
import {LoadMask} from 'tocco-ui'
import {consoleLogger} from 'tocco-util'
const actions = {
'create-folder': lazy(() => import(/* webpackChunkName: "actions" */'./actions/CreateFolder')),
'delete': lazy(() => import(/* webpackChunkName: "actions" */'./actions/Delete'))
}
const renderLoader = () => <LoadMask/>
const LazyAction = props => {
const {appId} = props
const LazyAction = actions[appId]
if (!LazyAction) {
consoleLogger.logError(`no action found with id: ${appId}`)
return null
}
const ActionComponent = connect(null, {
emitAction: action => actionEmitter.dispatchEmittedAction(action)
})(LazyAction)
return <Suspense fallback={renderLoader()}>
<ActionComponent {...props}/>
</Suspense>
}
LazyAction.propTypes = {
appId: PropTypes.string.isRequired
}
export default LazyAction
|
Make sure users can edit their signature | <?php namespace App\Data;
use UserPresenter;
use App\Authorization;
use Illuminate\Notifications\Notifiable;
use Laracasts\Presenter\PresentableTrait;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Authorizable, Authorization, Notifiable, PresentableTrait;
protected $connection = 'users';
protected $fillable = ['points', 'signature'];
protected $hidden = ['password', 'remember_token'];
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $presenter = UserPresenter::class;
//--------------------------------------------------------------------------
// Relationships
//--------------------------------------------------------------------------
public function discussions()
{
return $this->hasMany(Discussion::class)->latest();
}
public function replies()
{
return $this->hasMany(Reply::class);
}
//--------------------------------------------------------------------------
// Model Scopes
//--------------------------------------------------------------------------
public function scopeUsername($query, $username)
{
$query->where('username', $username);
}
//--------------------------------------------------------------------------
// Model Methods
//--------------------------------------------------------------------------
public function getRouteKeyName()
{
return 'username';
}
}
| <?php namespace App\Data;
use UserPresenter;
use App\Authorization;
use Illuminate\Notifications\Notifiable;
use Laracasts\Presenter\PresentableTrait;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Authorizable, Authorization, Notifiable, PresentableTrait;
protected $connection = 'users';
protected $fillable = ['points'];
protected $hidden = ['password', 'remember_token'];
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $presenter = UserPresenter::class;
//--------------------------------------------------------------------------
// Relationships
//--------------------------------------------------------------------------
public function discussions()
{
return $this->hasMany(Discussion::class)->latest();
}
public function replies()
{
return $this->hasMany(Reply::class);
}
//--------------------------------------------------------------------------
// Model Scopes
//--------------------------------------------------------------------------
public function scopeUsername($query, $username)
{
$query->where('username', $username);
}
//--------------------------------------------------------------------------
// Model Methods
//--------------------------------------------------------------------------
public function getRouteKeyName()
{
return 'username';
}
}
|
Test grails app with all non-relational services | /*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gopivotal.cloudfoundry.test.buildpack;
import com.gopivotal.cloudfoundry.test.support.runner.ExcludedApplications;
import com.gopivotal.cloudfoundry.test.support.service.ServicesHolder;
import org.springframework.beans.factory.annotation.Autowired;
@ExcludedApplications({"groovy", "java-main", "java-main-with-web-inf", "spring-boot-cli", "web", "play"})
public abstract class AbstractAutoReconfigurationTest extends AbstractTest {
@Autowired
protected volatile ServicesHolder servicesHolder;
}
| /*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gopivotal.cloudfoundry.test.buildpack;
import com.gopivotal.cloudfoundry.test.support.runner.ExcludedApplications;
import com.gopivotal.cloudfoundry.test.support.service.ServicesHolder;
import org.springframework.beans.factory.annotation.Autowired;
@ExcludedApplications({"grails", "groovy", "java-main", "java-main-with-web-inf", "spring-boot-cli", "web", "play"})
public abstract class AbstractAutoReconfigurationTest extends AbstractTest {
@Autowired
protected volatile ServicesHolder servicesHolder;
}
|
Fix errors with Free version. | package com.antew.redditinpictures;
import com.antew.redditinpictures.library.service.RedditService;
import com.antew.redditinpictures.library.ui.ImageDetailFragment;
import com.antew.redditinpictures.ui.ImageDetailActivityFree;
import com.antew.redditinpictures.ui.ImageDetailFragmentFree;
import com.antew.redditinpictures.ui.ImgurAlbumActivityFree;
import com.antew.redditinpictures.ui.ImgurAlbumFragmentFree;
import com.antew.redditinpictures.ui.RedditFragmentActivityFree;
import com.antew.redditinpictures.ui.RedditImageGridFragmentFree;
import com.antew.redditinpictures.ui.RedditImageListFragmentFree;
import dagger.Module;
/**
* Dagger module for setting up provides statements.
* Register all of your entry points below.
*/
@Module(
complete = false,
overrides = true,
injects = {
RedditImageGridFragmentFree.class, RedditImageListFragmentFree.class, RedditFragmentActivityFree.class,
ImageDetailActivityFree.class, ImageDetailFragmentFree.class, ImgurAlbumActivityFree.class, ImgurAlbumFragmentFree.class,
ImageDetailFragment.class,
RedditService.GetNewPostsIfNeededTask.class
}, library = true)
// TODO: Figure out why this isn't using ImageDetailFragmentFree, but instead only using ImageDetailFragment.
public class ApplicationModuleFree {
} | package com.antew.redditinpictures;
import com.antew.redditinpictures.library.service.RedditService;
import com.antew.redditinpictures.ui.ImageDetailActivityFree;
import com.antew.redditinpictures.ui.ImageDetailFragmentFree;
import com.antew.redditinpictures.ui.ImgurAlbumActivityFree;
import com.antew.redditinpictures.ui.ImgurAlbumFragmentFree;
import com.antew.redditinpictures.ui.RedditFragmentActivityFree;
import com.antew.redditinpictures.ui.RedditImageGridFragmentFree;
import com.antew.redditinpictures.ui.RedditImageListFragmentFree;
import dagger.Module;
/**
* Dagger module for setting up provides statements.
* Register all of your entry points below.
*/
@Module(
complete = false,
overrides = true,
injects = {
RedditImageGridFragmentFree.class, RedditImageListFragmentFree.class, RedditFragmentActivityFree.class,
ImageDetailActivityFree.class, ImageDetailFragmentFree.class, ImgurAlbumActivityFree.class, ImgurAlbumFragmentFree.class,
RedditService.GetNewPostsIfNeededTask.class,
}, library = true)
public class ApplicationModuleFree {
} |
Send email to Blink gardeners when tree closes.
R=eseidel@chromium.org,iannucci@chromium.org
BUG=323059
Review URL: https://codereview.chromium.org/84973002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@237359 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from master import gatekeeper
from master import master_utils
# This is the list of the builder categories and the corresponding critical
# steps. If one critical step fails, gatekeeper will close the tree
# automatically.
# Note: don't include 'update scripts' since we can't do much about it when
# it's failing and the tree is still technically fine.
categories_steps = {
'': ['update', 'runhooks', 'compile'],
}
exclusions = {
'WebKit XP': ['runhooks'], # crbug.com/262577
}
forgiving_steps = ['update_scripts', 'update', 'gclient_revert']
def Update(config, active_master, c):
c['status'].append(gatekeeper.GateKeeper(
fromaddr=active_master.from_address,
categories_steps=categories_steps,
exclusions=exclusions,
relayhost=config.Master.smtp,
subject='buildbot %(result)s in %(projectName)s on %(builder)s, '
'revision %(revision)s',
extraRecipients=active_master.tree_closing_notification_recipients,
lookup=master_utils.FilterDomain(),
forgiving_steps=forgiving_steps,
public_html='../master.chromium/public_html',
tree_status_url=active_master.tree_status_url,
use_getname=True,
sheriffs=['sheriff_webkit']))
| # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from master import gatekeeper
from master import master_utils
# This is the list of the builder categories and the corresponding critical
# steps. If one critical step fails, gatekeeper will close the tree
# automatically.
# Note: don't include 'update scripts' since we can't do much about it when
# it's failing and the tree is still technically fine.
categories_steps = {
'': ['update', 'runhooks', 'compile'],
}
exclusions = {
'WebKit XP': ['runhooks'], # crbug.com/262577
}
forgiving_steps = ['update_scripts', 'update', 'gclient_revert']
def Update(config, active_master, c):
c['status'].append(gatekeeper.GateKeeper(
fromaddr=active_master.from_address,
categories_steps=categories_steps,
exclusions=exclusions,
relayhost=config.Master.smtp,
subject='buildbot %(result)s in %(projectName)s on %(builder)s, '
'revision %(revision)s',
extraRecipients=active_master.tree_closing_notification_recipients,
lookup=master_utils.FilterDomain(),
forgiving_steps=forgiving_steps,
public_html='../master.chromium/public_html',
tree_status_url=active_master.tree_status_url,
use_getname=True,
sheriffs=[]))
|
Read from MemoryStream as output for console | <?php
namespace Generics\Logger;
use Psr\Log\LogLevel;
/**
* This class is a standard reference implementation of the PSR LoggerInterface.
*
* It logs everything to console. Depending on level it is written to stdout or stderr.
*
* @author Maik Greubel <greubel@nkey.de>
*/
class ConsoleLogger extends BasicLogger
{
protected function logImpl($level, $message, array $context = array())
{
$channel = STDOUT;
if($level === LogLevel::ALERT || $level === LogLevel::CRITICAL || $level === LogLevel::EMERGENCY ||
$level === LogLevel::ERROR || $level === LogLevel::WARNING) {
$channel = STDERR;
}
fwrite($channel, $this->getMessage($level, $message, $context)->read(4096));
}
}
| <?php
namespace Generics\Logger;
use Psr\Log\LogLevel;
/**
* This class is a standard reference implementation of the PSR LoggerInterface.
*
* It logs everything to console. Depending on level it is written to stdout or stderr.
*
* @author Maik Greubel <greubel@nkey.de>
*/
class ConsoleLogger extends BasicLogger
{
protected function logImpl($level, $message, array $context = array())
{
$channel = STDOUT;
if($level === LogLevel::ALERT || $level === LogLevel::CRITICAL || $level === LogLevel::EMERGENCY ||
$level === LogLevel::ERROR || $level === LogLevel::WARNING) {
$channel = STDERR;
}
fwrite($channel, $this->getMessage($level, $message, $context));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.