text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix error handling in lexer | "use strict";
var Class = require("./Class");
var CompileError = exports.CompileError = Class.extend({
initialize: function () {
switch (arguments.length) {
case 2: // token, text
this._filename = arguments[0].filename;
this._pos = arguments[0].pos;
this._message = arguments[1];
break;
case 3: // filename, pos, text
this._filename = arguments[0];
this._pos = arguments[1];
this._message = arguments[2];
break;
default:
throw new Error("Unrecognized arguments for CompileError: " + JSON.stringify( Array.prototype.slice.call(arguments) ));
}
},
getFilename: function () {
return this._filename;
},
getPosition: function () {
return this._pos;
},
toString: function () {
return this._filename + "(" + this._pos + "):" + this._message;
}
});
var Util = exports.Util = Class.extend({
$serializeArray: function (a) {
if (a == null)
return null;
var ret = [];
for (var i = 0; i < a.length; ++i)
ret[i] = a[i].serialize();
return ret;
},
$serializeNullable: function (v) {
if (v == null)
return null;
return v.serialize();
}
});
// vim: set noexpandtab:
| "use strict";
var Class = require("./Class");
var CompileError = exports.CompileError = Class.extend({
initialize: function () {
switch (arguments.length) {
case 2: // token, text
this._filename = arguments[0].filename;
this._pos = arguments[0].pos;
this._message = arguments[1];
break;
case 3: // filename, pos, text
this._filename = arguments[0];
this._pos = arguments[1];
this._message = arguments[2];
default:
throw new Error();
}
},
getFilename: function () {
return this._filename;
},
getPosition: function () {
return this._pos;
},
toString: function () {
return this._filename + "(" + this._pos + "):" + this._message;
}
});
var Util = exports.Util = Class.extend({
$serializeArray: function (a) {
if (a == null)
return null;
var ret = [];
for (var i = 0; i < a.length; ++i)
ret[i] = a[i].serialize();
return ret;
},
$serializeNullable: function (v) {
if (v == null)
return null;
return v.serialize();
}
});
|
Switch amazon-product-api to use promises | 'use strict';
var amazon = require('amazon-product-api');
var client = amazon.createClient({
awsId: process.env.AWS_ID,
awsSecret: process.env.AWS_SECRET,
awsTag: process.env.AWS_TAG
});
module.exports = function(title, cb) {
client.itemSearch({
keywords: title,
searchIndex: 'Books',
responseGroup: 'ItemAttributes'
})
.then(function(results) {
var originalUrl = results[0].DetailPageURL[0];
var fullTitle = results[0].ItemAttributes[0].Title[0];
var authors = results[0].ItemAttributes[0].Author;
var url = originalUrl.split('%3FSubscriptionId')[0].trim();
var hasSubtitle = (fullTitle.indexOf(':') !== -1);
var title = hasSubtitle ? fullTitle.split(':')[0].trim() : fullTitle;
var subtitle = hasSubtitle ? fullTitle.split(':')[1].trim() : void 0;
var markdownString = ['[', title, '](', url, ')'];
if(subtitle){
markdownString.push(' - *', subtitle, '*');
}
cb(null, {
url: url,
authors: authors,
title: title,
subtitle: subtitle,
markdown: markdownString.join('')
});
})
.catch(cb);
};
| 'use strict';
var amazon = require('amazon-product-api');
var client = amazon.createClient({
awsId: process.env.AWS_ID,
awsSecret: process.env.AWS_SECRET,
awsTag: process.env.AWS_TAG
});
module.exports = function(title, cb) {
client.itemSearch({
keywords: title,
searchIndex: 'Books',
responseGroup: 'ItemAttributes'
}, function(err, results) {
if(err) {
return cb(err);
}
var originalUrl = results[0].DetailPageURL[0];
var fullTitle = results[0].ItemAttributes[0].Title[0];
var authors = results[0].ItemAttributes[0].Author;
var url = originalUrl.split('%3FSubscriptionId')[0].trim();
var hasSubtitle = (fullTitle.indexOf(':') !== -1);
var title = hasSubtitle ? fullTitle.split(':')[0].trim() : fullTitle;
var subtitle = hasSubtitle ? fullTitle.split(':')[1].trim() : void 0;
var markdownString = ['[', title, '](', url, ')'];
if(subtitle){
markdownString.push(' - *', subtitle, '*');
}
cb(null, {
url: url,
authors: authors,
title: title,
subtitle: subtitle,
markdown: markdownString.join('')
});
});
};
|
Use custom header color in emails | <tr>
<td class="header"{!! ($snipeSettings->header_color!='') ? ' style="background-color: '.e($snipeSettings->header_color).'"' : '' !!}>
@if (($snipeSettings->show_images_in_email=='1' ) && ($snipeSettings::setupCompleted()))
@if ($snipeSettings->brand == '3')
@if ($snipeSettings->logo!='')
<img class="navbar-brand-img logo" src="{{ url('/') }}/uploads/{{ $snipeSettings->logo }}">
@endif
{{ $snipeSettings->site_name }}
@elseif ($snipeSettings->brand == '2')
@if ($snipeSettings->logo!='')
<img class="navbar-brand-img logo" src="{{ url('/') }}/uploads/{{ $snipeSettings->logo }}">
@endif
@else
{{ $snipeSettings->site_name }}
@endif
@else
Snipe-IT
@endif
</td>
</tr>
| <tr>
<td class="header">
@if (($snipeSettings->show_images_in_email=='1' ) && ($snipeSettings::setupCompleted()))
@if ($snipeSettings->brand == '3')
@if ($snipeSettings->logo!='')
<img class="navbar-brand-img logo" src="{{ url('/') }}/uploads/{{ $snipeSettings->logo }}">
@endif
{{ $snipeSettings->site_name }}
@elseif ($snipeSettings->brand == '2')
@if ($snipeSettings->logo!='')
<img class="navbar-brand-img logo" src="{{ url('/') }}/uploads/{{ $snipeSettings->logo }}">
@endif
@else
{{ $snipeSettings->site_name }}
@endif
@else
Snipe-IT
@endif
</td>
</tr>
|
Fix overview page col headers | import React from 'react'
import GamesContainer from './containers/GamesContainer'
export default (props) => {
return (
<div className='container overview'>
<div className='row'>
<div className='col-md-6'>
<div className='page-header'>
<h3>Mens</h3>
</div>
<GamesContainer filter={{gender: 'male'}} />
</div>
<div className='col-md-6'>
<div className='page-header'>
<h3>Womans</h3>
</div>
<GamesContainer filter={{gender: 'female'}} />
</div>
</div>
</div>
)
}
| import React from 'react'
import GamesContainer from './containers/GamesContainer'
export default (props) => {
return (
<div className='container overview'>
<div className='page-header'>
<div className='row'>
<div className='col-md-6'>
<h3>Mens</h3>
</div>
<div className='col-md-6'>
<h3>Womans</h3>
</div>
</div>
</div>
<div className='row'>
<div className='col-md-6'>
<GamesContainer filter={{gender: 'male'}} />
</div>
<div className='col-md-6'>
<GamesContainer filter={{gender: 'female'}} />
</div>
</div>
</div>
)
}
|
Fix conflict with test function newsfeed | var fs = require("fs");
var path = require("path");
var chai = require("chai");
var expect = chai.expect;
var vm = require("vm");
describe("Functions into modules/default/calendar/calendar.js", function() {
// Fake for use by calendar.js
Module = {}
Module.definitions = {};
Module.register = function (name, moduleDefinition) {
Module.definitions[name] = moduleDefinition;
};
before(function() {
// load calendar.js
require("../../../modules/default/calendar/calendar.js");
});
describe("capFirst", function() {
words = {
"rodrigo": "Rodrigo",
"123m": "123m",
"magic mirror": "Magic mirror",
",a": ",a",
"ñandú": "Ñandú"
};
Object.keys(words).forEach(word => {
it(`for ${word} should return ${words[word]}`, function() {
expect(Module.definitions.calendar.capFirst(word)).to.equal(words[word]);
});
});
});
});
| var fs = require("fs");
var path = require("path");
var chai = require("chai");
var expect = chai.expect;
var vm = require("vm");
describe("Functions into modules/default/calendar/calendar.js", function() {
// Fake for use by calendar.js
Module = {}
Module.definitions = {};
Module.register = function (name, moduleDefinition) {
Module.definitions[name] = moduleDefinition;
};
// load calendar.js
require("../../../modules/default/calendar/calendar.js");
describe("capFirst", function() {
words = {
"rodrigo": "Rodrigo",
"123m": "123m",
"magic mirror": "Magic mirror",
",a": ",a",
"ñandú": "Ñandú"
};
Object.keys(words).forEach(word => {
it(`for ${word} should return ${words[word]}`, function() {
expect(Module.definitions.calendar.capFirst(word)).to.equal(words[word]);
});
});
});
});
|
CDK-237: Add utility to nicely indent and format a morphline config file | /*
* Copyright 2013 Cloudera 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.cloudera.cdk.morphline.api;
import org.junit.Assert;
import org.junit.Test;
import com.cloudera.cdk.morphline.base.PrettyPrinter;
public class PrettyPrinterTest extends Assert {
@Test
public void testBasic() throws Exception {
PrettyPrinter.main(new String[] {"target/test-classes/test-morphlines/grokSyslogNgCisco.conf"});
PrettyPrinter.main(new String[] {"target/test-classes/test-morphlines/parseComplexConfig.conf"});
PrettyPrinter.main(new String[0]);
}
}
| /*
* Copyright 2013 Cloudera 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.cloudera.cdk.morphline.api;
import org.junit.Assert;
import org.junit.Test;
import com.cloudera.cdk.morphline.base.PrettyPrinter;
public class PrettyPrinterTest extends Assert {
@Test
public void testBasic() throws Exception {
PrettyPrinter.main(new String[] {"target/test-classes/test-morphlines/grokSyslogNgCisco.conf"});
PrettyPrinter.main(new String[] {"target/test-classes/test-morphlines/parseComplexConfig.conf"});
}
}
|
Change to private test webhook | /*
* Copyright (c) 2014-2021 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const chai = require('chai')
const expect = chai.expect
const chaiAsPromised = require('chai-as-promised')
chai.use(chaiAsPromised)
describe('webhook', () => {
const webhook = require('../../lib/webhook')
const challenge = {
key: 'key',
name: 'name'
}
describe('notify', () => {
it('fails when no webhook URL is provided via environment variable', () => {
expect(webhook.notify(challenge)).to.eventually.throw('options.uri is a required argument')
})
it('fails when supplied webhook is not a valid URL', () => {
expect(webhook.notify(challenge, 'localhorst')).to.eventually.throw('Invalid URI "localhorst"')
})
it('submits POST with payload to existing URL', () => {
expect(webhook.notify(challenge, 'https://enlm7zwniuyah.x.pipedream.net/')).to.eventually.not.throw()
})
})
})
| /*
* Copyright (c) 2014-2021 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const chai = require('chai')
const expect = chai.expect
const chaiAsPromised = require('chai-as-promised')
chai.use(chaiAsPromised)
describe('webhook', () => {
const webhook = require('../../lib/webhook')
const challenge = {
key: 'key',
name: 'name'
}
describe('notify', () => {
it('fails when no webhook URL is provided via environment variable', () => {
expect(webhook.notify(challenge)).to.eventually.throw('options.uri is a required argument')
})
it('fails when supplied webhook is not a valid URL', () => {
expect(webhook.notify(challenge, 'localhorst')).to.eventually.throw('Invalid URI "localhorst"')
})
it('submits POST with payload to existing URL', () => {
expect(webhook.notify(challenge, 'https://enmmrmqnft1o.x.pipedream.net')).to.eventually.not.throw()
})
})
})
|
Fix issue with gulp-jscs not using options in .jscsrc | var gulp = require('gulp');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var babel = require('gulp-babel');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var header = require('gulp-header');
var pkg = require('./package.json');
var banner = '/*! <%= pkg.name %> - v<%= pkg.version %> | <%= new Date().getFullYear() %> */\n';
gulp.task('build', function() {
return gulp.src('./src/d3-funnel/d3-funnel.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter('fail'))
.pipe(jscs({
configPath: './.jscsrc'
}))
.pipe(babel())
.pipe(gulp.dest('./dist/'))
.pipe(rename({
extname: '.min.js'}
))
.pipe(uglify())
.pipe(header(banner, {
pkg: pkg
}))
.pipe(gulp.dest('./dist/'));
});
gulp.task('default', ['build']);
| var gulp = require('gulp');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var babel = require('gulp-babel');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var header = require('gulp-header');
var pkg = require('./package.json');
var banner = '/*! <%= pkg.name %> - v<%= pkg.version %> | <%= new Date().getFullYear() %> */\n';
gulp.task('build', function() {
return gulp.src('./src/d3-funnel/d3-funnel.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter('fail'))
.pipe(jscs({
esnext: true,
verbose: true
}))
.pipe(babel())
.pipe(gulp.dest('./dist/'))
.pipe(rename({
extname: '.min.js'}
))
.pipe(uglify())
.pipe(header(banner, {
pkg: pkg
}))
.pipe(gulp.dest('./dist/'));
});
gulp.task('default', ['build']);
|
Update aur package to 2.4.1 | #
# Biicode Arch Linux package settings.
#
# Check PKGBUILD_template docs for those settings and
# what they mean.
#
def settings():
return { "version": "2.4.1",
"release_number": "1",
"arch_deps": ["cmake>=3.0.2",
"zlib",
"glibc",
"sqlite",
"wget",
"python2-pmw"
],
"debian_deps": ["zlib1g",
"libc-bin",
"libsqlite3-0",
"wget",
"lib32z1",
"python-tk"
]
}
if __name__ == '__main__':
print(settings())
| #
# Biicode Arch Linux package settings.
#
# Check PKGBUILD_template docs for those settings and
# what they mean.
#
def settings():
return { "version": "2.4",
"release_number": "1",
"arch_deps": ["cmake>=3.0.2",
"zlib",
"glibc",
"sqlite",
"wget",
"python2-pmw"
],
"debian_deps": ["zlib1g",
"libc-bin",
"libsqlite3-0",
"wget",
"lib32z1",
"python-tk"
]
}
if __name__ == '__main__':
print(settings())
|
Tweak the height of the popup box. Meetup varies the height of their box based on which permissions are requested. | (function () {
Meteor.loginWithMeetup = function (options, callback) {
// support both (options, callback) and (callback).
if (!callback && typeof options === 'function') {
callback = options;
options = {};
}
var config = Accounts.loginServiceConfiguration.findOne({service: 'meetup'});
if (!config) {
callback && callback(new Accounts.ConfigError("Service not configured"));
return;
}
var state = Random.id();
var scope = (options && options.requestPermissions) || [];
var flatScope = _.map(scope, encodeURIComponent).join('+');
var loginUrl =
'https://secure.meetup.com/oauth2/authorize' +
'?client_id=' + config.clientId +
'&response_type=code' +
'&scope=' + flatScope +
'&redirect_uri=' + Meteor.absoluteUrl('_oauth/meetup?close') +
'&state=' + state;
// meetup box gets taller when permissions requested.
var height = 620;
if (_.without(scope, 'basic').length)
height += 130;
Accounts.oauth.initiateLogin(state, loginUrl, callback,
{width: 900, height: height});
};
}) ();
| (function () {
Meteor.loginWithMeetup = function (options, callback) {
// support both (options, callback) and (callback).
if (!callback && typeof options === 'function') {
callback = options;
options = {};
}
var config = Accounts.loginServiceConfiguration.findOne({service: 'meetup'});
if (!config) {
callback && callback(new Accounts.ConfigError("Service not configured"));
return;
}
var state = Random.id();
var scope = (options && options.requestPermissions) || [];
var flatScope = _.map(scope, encodeURIComponent).join('+');
var loginUrl =
'https://secure.meetup.com/oauth2/authorize' +
'?client_id=' + config.clientId +
'&response_type=code' +
'&scope=' + flatScope +
'&redirect_uri=' + Meteor.absoluteUrl('_oauth/meetup?close') +
'&state=' + state;
Accounts.oauth.initiateLogin(state, loginUrl, callback, {width: 900, height: 450});
};
}) ();
|
Fix comment for response class | // Copyright 2019 Google LLC
//
// 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
//
// https://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.sps.data;
import com.google.common.collect.ImmutableList;
/** Wrapper class for information sent on a search servlet doGet response. */
public class SearchServletResponse {
private final ImmutableList<Receipt> matchingReceipts;
private final String encodedCursor;
public SearchServletResponse(ImmutableList<Receipt> matchingReceipts, String encodedCursor) {
this.matchingReceipts = ImmutableList.copyOf(matchingReceipts);
this.encodedCursor = encodedCursor;
}
} | // Copyright 2019 Google LLC
//
// 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
//
// https://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.sps.data;
import com.google.common.collect.ImmutableList;
/** Wrapper class for infromation sent on a search servlet doGet request. */
public class SearchServletResponse {
private final ImmutableList<Receipt> matchingReceipts;
private final String encodedCursor;
public SearchServletResponse(ImmutableList<Receipt> matchingReceipts, String encodedCursor) {
this.matchingReceipts = ImmutableList.copyOf(matchingReceipts);
this.encodedCursor = encodedCursor;
}
} |
Fix compile errors relating to the change of interface of errorHandler | package sysdep
import (
bs_core "bitbucket.org/yyuu/bs/core"
bs_ir "bitbucket.org/yyuu/bs/ir"
)
type X86CodeGenerator struct {
errorHandler *bs_core.ErrorHandler
}
func NewX86CodeGenerator(errorHandler *bs_core.ErrorHandler) *X86CodeGenerator {
return &X86CodeGenerator { errorHandler }
}
func (self *X86CodeGenerator) Generate(ir *bs_ir.IR) IAssemblyCode {
self.errorHandler.Debug("starting code generator.")
self.locateSymbols(ir)
x := self.generateAssemblyCode(ir)
self.errorHandler.Debug("finished code generator.")
return x
}
func (self *X86CodeGenerator) locateSymbols(ir *bs_ir.IR) {
self.errorHandler.Warn("FIXME* X86CodeGenerater#localSymbols not implemented")
}
func (self *X86CodeGenerator) generateAssemblyCode(ir *bs_ir.IR) IAssemblyCode {
file := NewX86AssemblyCode()
return file
}
| package sysdep
import (
bs_core "bitbucket.org/yyuu/bs/core"
bs_ir "bitbucket.org/yyuu/bs/ir"
)
type X86CodeGenerator struct {
errorHandler *bs_core.ErrorHandler
}
func NewX86CodeGenerator(errorHandler *bs_core.ErrorHandler) *X86CodeGenerator {
return &X86CodeGenerator { errorHandler }
}
func (self *X86CodeGenerator) Generate(ir *bs_ir.IR) IAssemblyCode {
self.errorHandler.Debugln("starting code generator.")
self.locateSymbols(ir)
x := self.generateAssemblyCode(ir)
self.errorHandler.Debugln("finished code generator.")
return x
}
func (self *X86CodeGenerator) locateSymbols(ir *bs_ir.IR) {
self.errorHandler.Warnln("FIXME* X86CodeGenerater#localSymbols not implemented")
}
func (self *X86CodeGenerator) generateAssemblyCode(ir *bs_ir.IR) IAssemblyCode {
file := NewX86AssemblyCode()
return file
}
|
Fix case of command name | 'use strict';
var Subscript = require('./Subscript');
var SubscriptHTMLConverter = require('./SubscriptHTMLConverter');
var SubscriptXMLConverter = require('./SubscriptXMLConverter');
var AnnotationCommand = require('../../ui/AnnotationCommand');
var AnnotationComponent = require('../../ui/AnnotationComponent');
var AnnotationTool = require('../../ui/AnnotationTool');
module.exports = {
name: 'subscript',
configure: function(config) {
config.addNode(Subscript);
config.addConverter('html', SubscriptHTMLConverter);
config.addConverter('xml', SubscriptXMLConverter);
config.addComponent('subscript', AnnotationComponent);
config.addCommand('subscript', AnnotationCommand, { nodeType: 'subscript' });
config.addTool('subscript', AnnotationTool);
config.addIcon('subscript', { 'fontawesome': 'fa-subscript' });
config.addStyle(__dirname, '_subscript.scss');
config.addLabel('subscript', {
en: 'Subscript',
de: 'Tiefgestellt'
});
}
};
| 'use strict';
var Subscript = require('./Subscript');
var SubscriptHTMLConverter = require('./SubscriptHTMLConverter');
var SubscriptXMLConverter = require('./SubscriptXMLConverter');
var AnnotationCommand = require('../../ui/AnnotationCommand');
var AnnotationComponent = require('../../ui/AnnotationComponent');
var AnnotationTool = require('../../ui/AnnotationTool');
module.exports = {
name: 'subscript',
configure: function(config) {
config.addNode(Subscript);
config.addConverter('html', SubscriptHTMLConverter);
config.addConverter('xml', SubscriptXMLConverter);
config.addComponent('subscript', AnnotationComponent);
config.addCommand('Subscript', AnnotationCommand, { nodeType: 'subscript' });
config.addTool('subscript', AnnotationTool);
config.addIcon('subscript', { 'fontawesome': 'fa-subscript' });
config.addStyle(__dirname, '_subscript.scss');
config.addLabel('subscript', {
en: 'Subscript',
de: 'Tiefgestellt'
});
}
};
|
[Tests] Test trivia answer with wrong encoding |
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_parentheses_with_article_prefix(self):
self.assertTrue(
check_answer(
"the ISS (the International Space Station)",
"International Space Station"
)
)
self.assertTrue(
check_answer("Holland (The Netherlands)", "Netherlands")
)
def test_wrong_encoding(self):
self.assertTrue(check_answer("a résumé", "resume"))
if __name__ == "__main__":
unittest.main()
|
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_parentheses_with_article_prefix(self):
self.assertTrue(
check_answer(
"the ISS (the International Space Station)",
"International Space Station"
)
)
self.assertTrue(
check_answer("Holland (The Netherlands)", "Netherlands")
)
if __name__ == "__main__":
unittest.main()
|
Revert "Stop AJAX updater consuming ever-increasing memory" | (function(Modules) {
"use strict";
var queues = {};
var dd = new diffDOM();
var getRenderer = $component => response => dd.apply(
$component.get(0),
dd.diff($component.get(0), $(response[$component.data('key')]).get(0))
);
var getQueue = resource => (
queues[resource] = queues[resource] || []
);
var flushQueue = function(queue, response) {
while(queue.length) queue.shift()(response);
};
var clearQueue = queue => (queue.length = 0);
var poll = function(renderer, resource, queue, interval) {
if (queue.push(renderer) === 1) $.ajax(
resource
).done(
response => flushQueue(queue, response)
).fail(
() => clearQueue(queue)
);
setTimeout(
() => poll(...arguments), interval
);
};
Modules.UpdateContent = function() {
this.start = component => poll(
getRenderer($(component)),
$(component).data('resource'),
getQueue($(component).data('resource')),
($(component).data('interval-seconds') || 1.5) * 1000
);
};
})(window.GOVUK.Modules);
| (function(Modules) {
"use strict";
var queues = {};
var dd = new diffDOM();
var timer;
var getRenderer = $component => response => function() {
var component = $component.get(0);
var updated = $(response[$component.data('key')]).get(0);
var diff = dd.diff(component, updated);
dd.apply(
component, diff
);
};
var getQueue = resource => (
queues[resource] = queues[resource] || []
);
var flushQueue = function(queue, response) {
while(queue.length) queue.shift()(response);
};
var clearQueue = queue => (queue.length = 0);
var poll = function(renderer, resource, queue, interval) {
if (queue.push(renderer) === 1) $.ajax(
resource
).done(
response => flushQueue(queue, response)
).fail(
() => clearQueue(queue)
);
timer = setTimeout(
() => poll(...arguments), interval
);
};
Modules.UpdateContent = function() {
this.start = component => poll(
getRenderer($(component)),
$(component).data('resource'),
getQueue($(component).data('resource')),
($(component).data('interval-seconds') || 1.5) * 1000
);
};
})(window.GOVUK.Modules);
|
Change S3 full name to Amazon S3 | import os
from . import model
from . import routes
from . import views
MODELS = [model.AddonS3UserSettings, model.AddonS3NodeSettings, model.S3GuidFile]
USER_SETTINGS_MODEL = model.AddonS3UserSettings
NODE_SETTINGS_MODEL = model.AddonS3NodeSettings
ROUTES = [routes.settings_routes]
SHORT_NAME = 's3'
FULL_NAME = 'Amazon S3'
OWNERS = ['user', 'node']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user', 'node']
CATEGORIES = ['storage']
INCLUDE_JS = {}
INCLUDE_CSS = {
'widget': [],
'page': [],
}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.hgrid.s3_hgrid_data
# 1024 ** 1024 # There really shouldnt be a limit...
MAX_FILE_SIZE = 128 # MB
HERE = os.path.dirname(os.path.abspath(__file__))
NODE_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 's3_node_settings.mako')
USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 's3_user_settings.mako')
| import os
from . import model
from . import routes
from . import views
MODELS = [model.AddonS3UserSettings, model.AddonS3NodeSettings, model.S3GuidFile]
USER_SETTINGS_MODEL = model.AddonS3UserSettings
NODE_SETTINGS_MODEL = model.AddonS3NodeSettings
ROUTES = [routes.settings_routes]
SHORT_NAME = 's3'
FULL_NAME = 'Amazon Simple Storage Service'
OWNERS = ['user', 'node']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user', 'node']
CATEGORIES = ['storage']
INCLUDE_JS = {}
INCLUDE_CSS = {
'widget': [],
'page': [],
}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.hgrid.s3_hgrid_data
# 1024 ** 1024 # There really shouldnt be a limit...
MAX_FILE_SIZE = 128 # MB
HERE = os.path.dirname(os.path.abspath(__file__))
NODE_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 's3_node_settings.mako')
USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 's3_user_settings.mako')
|
Use CLI for arguments in client | package mafiaclient;
/**
* MafiaClient.java
* Contains the MafiaClient class
* @author Cory Gehr (cmg5573)
*/
public class MafiaClient {
public static String HOST_NAME;
public static int PORT_NUMBER = 65004;
/**
* main()
* Entry point for the MafiaClient application
* @param args Command Line arguments
*/
public static void main(String[] args) {
if(args.length == 2) {
// Host name set
HOST_NAME = args[0];
PORT_NUMBER = Integer.parseInt(args[1]);
} else {
// Host name not set, run on localhost
HOST_NAME = "localhost";
PORT_NUMBER = 65004;
}
// Start client connection
ClientServerConnectionStarter connection =
new ClientServerConnectionStarter(HOST_NAME, PORT_NUMBER);
connection.start();
}
}
| package mafiaclient;
/**
* MafiaClient.java
* Contains the MafiaClient class
* @author Cory Gehr (cmg5573)
*/
public class MafiaClient {
public static String HOST_NAME;
public static int PORT_NUMBER = 65004;
/**
* main()
* Entry point for the MafiaClient application
* @param args Command Line arguments
*/
public static void main(String[] args) {
if(args.length > 0) {
// Host name set
HOST_NAME = args[0];
} else {
// Host name not set, run on localhost
HOST_NAME = "localhost";
}
// Start client connection
ClientServerConnectionStarter connection =
new ClientServerConnectionStarter(HOST_NAME, PORT_NUMBER);
connection.start();
}
}
|
Add JSCS and JSHint to default task | var gulp = require('gulp');
var javascripts = [
'Gulpfile.js',
'index.js',
'lib/**/*.js',
'test/**/*.js'
];
gulp.task('jscs', function () {
var jscs = require('gulp-jscs');
return gulp.src(javascripts)
.pipe(jscs({
preset: 'yandex',
disallowMultipleVarDecl: 'exceptUndefined'
}));
});
gulp.task('lint', function () {
var jshint = require('gulp-jshint');
return gulp.src(javascripts)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(jshint.reporter('fail'));
});
gulp.task('test', function () {
var mocha = require('gulp-mocha');
return gulp.src('test/**/*.js', {
read: false
})
.pipe(mocha({
bail: true
}));
});
gulp.task('watch', function () {
return gulp.watch(javascripts, ['default']);
});
gulp.task('default', ['lint', 'jscs', 'test']);
| var gulp = require('gulp');
var javascripts = [
'Gulpfile.js',
'index.js',
'lib/**/*.js',
'test/**/*.js'
];
gulp.task('jscs', function () {
var jscs = require('gulp-jscs');
return gulp.src(javascripts)
.pipe(jscs({
preset: 'yandex',
disallowMultipleVarDecl: 'exceptUndefined'
}));
});
gulp.task('lint', function () {
var jshint = require('gulp-jshint');
return gulp.src(javascripts)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(jshint.reporter('fail'));
});
gulp.task('test', function () {
var mocha = require('gulp-mocha');
return gulp.src('test/**/*.js', {
read: false
})
.pipe(mocha({
bail: true
}));
});
gulp.task('watch', function () {
return gulp.watch(javascripts, ['default']);
});
gulp.task('default', ['test']);
|
Revert "Update kernel version of ubuntu microkernel to 3.16.0-25-generic." | // Copyright 2015, EMC, Inc.
'use strict';
module.exports = {
friendlyName: 'Bootstrap Ubuntu',
injectableName: 'Task.Linux.Bootstrap.Ubuntu',
implementsTask: 'Task.Base.Linux.Bootstrap',
options: {
kernelFile: 'vmlinuz-3.13.0-32-generic',
initrdFile: 'initrd.img-3.13.0-32-generic',
kernelUri: '{{ api.server }}/common/{{ options.kernelFile }}',
initrdUri: '{{ api.server }}/common/{{ options.initrdFile }}',
basefs: 'common/base.trusty.3.13.0-32-generic.squashfs.img',
overlayfs: 'common/discovery.overlay.cpio.gz',
profile: 'linux.ipxe',
comport: 'ttyS0'
},
properties: {
os: {
linux: {
distribution: 'ubuntu',
release: 'trusty',
kernel: '3.13.0-32-generic'
}
}
}
};
| // Copyright 2015, EMC, Inc.
'use strict';
module.exports = {
friendlyName: 'Bootstrap Ubuntu',
injectableName: 'Task.Linux.Bootstrap.Ubuntu',
implementsTask: 'Task.Base.Linux.Bootstrap',
options: {
kernelFile: 'vmlinuz-3.16.0-25-generic',
initrdFile: 'initrd.img-3.16.0-25-generic',
kernelUri: '{{ api.server }}/common/{{ options.kernelFile }}',
initrdUri: '{{ api.server }}/common/{{ options.initrdFile }}',
basefs: 'common/base.trusty.3.16.0-25-generic.squashfs.img',
overlayfs: 'common/discovery.overlay.cpio.gz',
profile: 'linux.ipxe',
comport: 'ttyS0'
},
properties: {
os: {
linux: {
distribution: 'ubuntu',
release: 'trusty',
kernel: '3.16.0-25-generic'
}
}
}
};
|
Use dot reporter for server tests
Further noise reductions | import Gulp from 'gulp';
import istanbul from 'gulp-istanbul';
import mocha from 'gulp-mocha';
import {Server as KarmaServer} from 'karma';
import plumber from '@kpdecker/linoleum/src/plumber';
import {BUILD_TARGET, COVERAGE_TARGET} from '@kpdecker/linoleum/config';
// This task hierarchy is to hack around
// https://github.com/sindresorhus/gulp-mocha/issues/112
Gulp.task('cover:server:run', function() {
global.__coverage__ = {};
return Gulp.src(`${BUILD_TARGET}/$cover$/*.js`)
.pipe(plumber())
.pipe(mocha({reporter: 'dot'}));
});
Gulp.task('cover:server', ['cover:server:run'], function() {
return Gulp.src(`${BUILD_TARGET}/$cover$/*.js`)
.pipe(istanbul.writeReports({
coverageVariable: '__coverage__',
dir: COVERAGE_TARGET,
reporters: [ 'json' ],
reportOpts: { dir: `${COVERAGE_TARGET}/webpack` }
}));
});
Gulp.task('cover:web', function(done) {
new KarmaServer({
configFile: `${__dirname}/../src/karma.js`,
singleRun: true
}, done).start();
});
| import Gulp from 'gulp';
import istanbul from 'gulp-istanbul';
import mocha from 'gulp-mocha';
import {Server as KarmaServer} from 'karma';
import plumber from '@kpdecker/linoleum/src/plumber';
import {BUILD_TARGET, COVERAGE_TARGET} from '@kpdecker/linoleum/config';
// This task hierarchy is to hack around
// https://github.com/sindresorhus/gulp-mocha/issues/112
Gulp.task('cover:server:run', function() {
global.__coverage__ = {};
return Gulp.src(`${BUILD_TARGET}/$cover$/*.js`)
.pipe(plumber())
.pipe(mocha());
});
Gulp.task('cover:server', ['cover:server:run'], function() {
return Gulp.src(`${BUILD_TARGET}/$cover$/*.js`)
.pipe(istanbul.writeReports({
coverageVariable: '__coverage__',
dir: COVERAGE_TARGET,
reporters: [ 'json' ],
reportOpts: { dir: `${COVERAGE_TARGET}/webpack` }
}));
});
Gulp.task('cover:web', function(done) {
new KarmaServer({
configFile: `${__dirname}/../src/karma.js`,
singleRun: true
}, done).start();
});
|
Fix to allow setting IDs for newly created records
Previously, saving a new record would trigger a POST request to
the FHIR server. In the FHIR specification, the only way to create
a new record and assign it an ID is by using a PUT request. This
fix causes the adapter to use a PUT request when saving a new
record that has an ID that has been manually set. If no ID is set,
it defaults to a POST request which will auto-generate an ID. | import Ember from 'ember';
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
defaultSerializer: '-fhir',
pathForType: function(type){
return Ember.String.capitalize(Ember.String.camelize(type));
},
createRecord: function (store, type, snapshot) {
if (snapshot.id) {
// if we have set an ID on this record, use "update" instead of "create"
// (triggers a PUT instead of POST)
return this.updateRecord(store, type, snapshot);
}
return this._super(store, type, snapshot);
},
buildURL: function(modelName, id, snapshot, requestType, query) {
if(requestType === "fhirQuery"){
return this.urlForFHIRQuery(query, modelName);
}
return this._super(modelName, id, snapshot, requestType, query);
},
urlForFHIRQuery: function(query, modelName){
var queryString = Object.keys(query).map(function(key){
return key+"="+query[key];
}).join("&");
return "/" + Ember.String.singularize(this.pathForType(modelName)) + "?" + queryString;
}
});
| import Ember from 'ember';
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
defaultSerializer: '-fhir',
pathForType: function(type){
return Ember.String.capitalize(Ember.String.camelize(type));
},
buildURL: function(modelName, id, snapshot, requestType, query) {
if(requestType === "fhirQuery"){
return this.urlForFHIRQuery(query, modelName);
}
return this._super(modelName, id, snapshot, requestType, query);
},
urlForFHIRQuery: function(query, modelName){
var queryString = Object.keys(query).map(function(key){
return key+"="+query[key];
}).join("&");
return "/" + Ember.String.singularize(this.pathForType(modelName)) + "?" + queryString;
}
});
|
Use the correct index name. | package dai
import (
r "github.com/dancannon/gorethink"
"github.com/materials-commons/mcstore/pkg/db/model"
"github.com/materials-commons/mcstore/pkg/db/schema"
)
type rProjects struct {
session *r.Session
}
func NewRProjects(session *r.Session) rProjects {
return rProjects{
session: session,
}
}
func (p rProjects) ByID(id string) (*schema.Project, error) {
var project schema.Project
if err := model.Projects.Qs(p.session).ByID(id, &project); err != nil {
return nil, err
}
return &project, nil
}
func (p rProjects) HasDirectory(projectID, dirID string) bool {
rql := model.ProjectDirs.T().GetAllByIndex("datadir_id", dirID)
var proj2dir []schema.Project2DataDir
if err := model.ProjectDirs.Qs(p.session).Rows(rql, &proj2dir); err != nil {
return false
}
// Look for matching projectID
for _, entry := range proj2dir {
if entry.ProjectID == projectID {
return true
}
}
return false
}
| package dai
import (
r "github.com/dancannon/gorethink"
"github.com/materials-commons/mcstore/pkg/db/model"
"github.com/materials-commons/mcstore/pkg/db/schema"
)
type rProjects struct {
session *r.Session
}
func NewRProjects(session *r.Session) rProjects {
return rProjects{
session: session,
}
}
func (p rProjects) ByID(id string) (*schema.Project, error) {
var project schema.Project
if err := model.Projects.Qs(p.session).ByID(id, &project); err != nil {
return nil, err
}
return &project, nil
}
func (p rProjects) HasDirectory(projectID, dirID string) bool {
rql := model.ProjectDirs.T().GetAllByIndex("directory_id", dirID)
var proj2dir []schema.Project2DataDir
if err := model.ProjectDirs.Qs(p.session).Rows(rql, &proj2dir); err != nil {
return false
}
// Look for matching projectID
for _, entry := range proj2dir {
if entry.ProjectID == projectID {
return true
}
}
return false
}
|
Remove calls to begin, end edit object. | import sublime
import sublime_plugin
class TrimmerCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
trailing_white_space = view.find_all("[\t ]+$")
trailing_white_space.reverse()
for r in trailing_white_space:
view.erase(edit, r)
sublime.set_timeout(lambda: self.save(view), 10)
def save(self, view):
if view.file_name() is None:
view.run_command('prompt_save_as')
else:
view.run_command('save')
sublime.status_message('Trimmer: Removed trailing whitespace and saved.')
| import sublime
import sublime_plugin
class TrimmerCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
trailing_white_space = view.find_all("[\t ]+$")
trailing_white_space.reverse()
edit = view.begin_edit()
for r in trailing_white_space:
view.erase(edit, r)
view.end_edit(edit)
sublime.set_timeout(lambda: self.save(view), 10)
def save(self, view):
if view.file_name() is None:
view.run_command('prompt_save_as')
else:
view.run_command('save')
sublime.status_message('Trimmer: Removed trailing whitespace and saved.')
|
Test commit : remove CR | package com.gettyimages.connectsdk;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Map;
public class Download {
private String MustSpecifyAtLeastOneImageIdMessage = "Must specify at least one image id.";
private String AutoDownloadString = "auto_download";
private String DownloadsPathString = "/downloads/";
private String FalseString = "false";
private String baseUrl;
private Credentials credentials;
private String assetId;
private Download(Credentials credentials, String baseUrl)
{
this.credentials = credentials;
this.baseUrl = baseUrl;
}
public static Download GetInstance(Credentials credentials, String baseUrl)
{
return new Download(credentials, baseUrl);
}
public Download WithId(String val)
{
assetId = val;
return this;
}
public String ExecuteAsync() throws SdkException {
if (assetId == null || assetId.length() == 0)
{
throw new SdkException(MustSpecifyAtLeastOneImageIdMessage);
}
WebHelper helper = new WebHelper(credentials, baseUrl);
Map<String,String> queryParameters = new Hashtable<String, String>();
queryParameters.put(AutoDownloadString, FalseString);
return (helper.PostQuery(queryParameters, DownloadsPathString + assetId));
}
}
| package com.gettyimages.connectsdk;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Map;
public class Download {
private String MustSpecifyAtLeastOneImageIdMessage = "Must specify at least one image id.";
private String AutoDownloadString = "auto_download";
private String DownloadsPathString = "/downloads/";
private String FalseString = "false";
private String baseUrl;
private Credentials credentials;
private String assetId;
private Download(Credentials credentials, String baseUrl)
{
this.credentials = credentials;
this.baseUrl = baseUrl;
}
public static Download GetInstance(Credentials credentials, String baseUrl)
{
return new Download(credentials, baseUrl);
}
public Download WithId(String val)
{
assetId = val;
return this;
}
public String ExecuteAsync() throws SdkException {
if (assetId == null || assetId.length() == 0)
{
throw new SdkException(MustSpecifyAtLeastOneImageIdMessage);
}
WebHelper helper = new WebHelper(credentials, baseUrl);
Map<String,String> queryParameters = new Hashtable<String, String>();
queryParameters.put(AutoDownloadString, FalseString);
return (helper.PostQuery(queryParameters, DownloadsPathString + assetId));
}
}
|
Add missing PYGMENTS_STYLES list to pyqode.core.api | """
This package contains the bases classes of pyqode and some utility
functions.
"""
from .code_edit import CodeEdit
from .decoration import TextDecoration
from .encodings import ENCODINGS_MAP, convert_to_codec_key
from .manager import Manager
from .mode import Mode
from .panel import Panel
from .syntax_highlighter import ColorScheme
from .syntax_highlighter import PYGMENTS_STYLES
from .syntax_highlighter import SyntaxHighlighter
from .syntax_highlighter import TextBlockUserData
from .utils import TextHelper, TextBlockHelper
from .utils import get_block_symbol_data
from .utils import DelayJobRunner
from .folding import FoldDetector
from .folding import IndentFoldDetector
from .folding import CharBasedFoldDetector
from .folding import FoldScope
__all__ = [
'convert_to_codec_key',
'get_block_symbol_data',
'CharBasedFoldDetector',
'CodeEdit',
'ColorScheme',
'DelayJobRunner',
'ENCODINGS_MAP',
'FoldDetector',
'IndentFoldDetector',
'FoldScope',
'Manager',
'Mode',
'Panel',
'PYGMENTS_STYLES',
'SyntaxHighlighter',
'TextBlockUserData',
'TextDecoration',
'TextHelper',
'TextBlockHelper'
]
| """
This package contains the bases classes of pyqode and some utility
functions.
"""
from .code_edit import CodeEdit
from .decoration import TextDecoration
from .encodings import ENCODINGS_MAP, convert_to_codec_key
from .manager import Manager
from .mode import Mode
from .panel import Panel
from .syntax_highlighter import SyntaxHighlighter
from .syntax_highlighter import ColorScheme
from .syntax_highlighter import TextBlockUserData
from .utils import TextHelper, TextBlockHelper
from .utils import get_block_symbol_data
from .utils import DelayJobRunner
from .folding import FoldDetector
from .folding import IndentFoldDetector
from .folding import CharBasedFoldDetector
from .folding import FoldScope
__all__ = [
'convert_to_codec_key',
'get_block_symbol_data',
'CharBasedFoldDetector',
'CodeEdit',
'ColorScheme',
'DelayJobRunner',
'ENCODINGS_MAP',
'FoldDetector',
'IndentFoldDetector',
'FoldScope',
'Manager',
'Mode',
'Panel',
'SyntaxHighlighter',
'TextBlockUserData',
'TextDecoration',
'TextHelper',
'TextBlockHelper'
]
|
Remove unneeded $FlowFixMe, it was fixed | /* @flow */
import React from 'react';
// Unpack TW.
const { settings } = chrome.extension.getBackgroundPage().TW;
export default function PauseButton() {
const [paused, setPaused] = React.useState(settings.get('paused'));
function pause() {
chrome.browserAction.setIcon({ path: 'img/icon-paused.png' });
settings.set('paused', true);
setPaused(true);
}
function play() {
chrome.browserAction.setIcon({ path: 'img/icon.png' });
settings.set('paused', false);
setPaused(false);
}
return (
<button className="btn btn-outline-dark btn-sm" onClick={paused ? play : pause} type="button">
{paused ? (
<>
<i className="fas fa-play" /> {chrome.i18n.getMessage('extension_resume')}
</>
) : (
<>
<i className="fas fa-pause" /> {chrome.i18n.getMessage('extension_pause')}
</>
)}
</button>
);
}
| /* @flow */
import React from 'react';
// Unpack TW.
const { settings } = chrome.extension.getBackgroundPage().TW;
export default function PauseButton() {
// $FlowFixMe Upgrade Flow to get latest React types
const [paused, setPaused] = React.useState(settings.get('paused'));
function pause() {
chrome.browserAction.setIcon({ path: 'img/icon-paused.png' });
settings.set('paused', true);
setPaused(true);
}
function play() {
chrome.browserAction.setIcon({ path: 'img/icon.png' });
settings.set('paused', false);
setPaused(false);
}
return (
<button className="btn btn-outline-dark btn-sm" onClick={paused ? play : pause} type="button">
{paused ? (
<>
<i className="fas fa-play" /> {chrome.i18n.getMessage('extension_resume')}
</>
) : (
<>
<i className="fas fa-pause" /> {chrome.i18n.getMessage('extension_pause')}
</>
)}
</button>
);
}
|
Move path logic out of switch statements | import undoable from 'redux-undo-immutable';
import { fromJS } from 'immutable';
import { findPathByNodeId } from '../utils/vertTreeUtils';
const defaultState = fromJS([{ value: undefined, children: [], _id: 1000 }]);
const verticalTreeData = (
state = defaultState,
action
) => {
let path = findPathByNodeId(action.nodeId, state);
if (path) {
path.push('highlighted');
}
switch (action.type) {
case 'UPDATE_VERT_STRUCTURE':
return action.newState;
case 'HIGHLIGHT_NODE':
return path ? state.setIn(path, true) : state;
case 'UNHIGHLIGHT_NODE':
return path ? state.setIn(path, false) : state;
case 'RESET_TO_DEFAULT':
return defaultState;
default:
return state;
}
};
const undoableVerticalTreeData = undoable(
verticalTreeData,
{ limit: 20 }
);
export default {
verticalTreeData: undoableVerticalTreeData,
testableVerticalTreeData: verticalTreeData
};
| import undoable from 'redux-undo-immutable';
import { fromJS } from 'immutable';
import { findPathByNodeId } from '../utils/vertTreeUtils';
const defaultState = fromJS([{ value: undefined, children: [], _id: 1000 }]);
const verticalTreeData = (
state = defaultState,
action
) => {
let path = findPathByNodeId(action.nodeId, state);
switch (action.type) {
case 'UPDATE_VERT_STRUCTURE':
return action.newState;
case 'HIGHLIGHT_NODE':
path.push('highlighted');
return state.setIn(path, true);
case 'UNHIGHLIGHT_NODE':
path.push('highlighted');
return state.setIn(path, false);
case 'RESET_TO_DEFAULT':
return defaultState;
default:
return state;
}
};
const undoableVerticalTreeData = undoable(
verticalTreeData,
{ limit: 20 }
);
export default {
verticalTreeData: undoableVerticalTreeData,
testableVerticalTreeData: verticalTreeData
};
|
Use default schema id for empty articles. | import { DefaultDOMElement } from 'substance'
import { DEFAULT_JATS_SCHEMA_ID, DEFAULT_JATS_DTD } from '../../ArticleConstants'
// TODO: we need a way to specify which namespaces should be declared
const EMPTY_JATS = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE article PUBLIC "${DEFAULT_JATS_SCHEMA_ID}" "${DEFAULT_JATS_DTD}">
<article xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ali="http://www.niso.org/schemas/ali/1.0">
<front>
<article-meta>
<title-group>
<article-title></article-title>
</title-group>
<abstract>
</abstract>
</article-meta>
</front>
<body>
</body>
<back>
</back>
</article>`
export default function createEmptyJATS () {
return DefaultDOMElement.parseXML(EMPTY_JATS)
}
| import { DefaultDOMElement } from 'substance'
const EMPTY_JATS = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving DTD v1.0 20120330//EN" "JATS-journalarchiving.dtd">
<article xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ali="http://www.niso.org/schemas/ali/1.0">
<front>
<article-meta>
<title-group>
<article-title></article-title>
</title-group>
<abstract>
</abstract>
</article-meta>
</front>
<body>
</body>
<back>
</back>
</article>`
export default function createEmptyJATS () {
return DefaultDOMElement.parseXML(EMPTY_JATS)
}
|
Use array factory in tests | <?php
/*
* This file is part of php-cache\adapter-bundle package.
*
* (c) 2015-2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Cache\Adapter\DoctrineAdapterBundle\Tests\DependencyInjection;
use Cache\AdapterBundle\DependencyInjection\CacheAdapterExtension;
use Cache\AdapterBundle\DummyAdapter;
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase;
class DoctrineCacheExtensionTest extends AbstractExtensionTestCase
{
protected function getContainerExtensions()
{
return [
new CacheAdapterExtension(),
];
}
public function testThatProvidersExists()
{
$providers = ['foo' => ['factory' => 'cache.factory.array']];
$this->load(['providers' => $providers]);
$this->assertContainerBuilderHasService('cache.provider.foo', DummyAdapter::class);
$this->assertContainerBuilderHasAlias('cache', 'cache.provider.foo');
}
}
| <?php
/*
* This file is part of php-cache\adapter-bundle package.
*
* (c) 2015-2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Cache\Adapter\DoctrineAdapterBundle\Tests\DependencyInjection;
use Cache\AdapterBundle\DependencyInjection\CacheAdapterExtension;
use Cache\AdapterBundle\DummyAdapter;
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase;
class DoctrineCacheExtensionTest extends AbstractExtensionTestCase
{
protected function getContainerExtensions()
{
return [
new CacheAdapterExtension(),
];
}
public function testThatProvidersExists()
{
$providers = ['foo' => ['factory' => 'cache.factory.redis']];
$this->load(['providers' => $providers]);
$this->assertContainerBuilderHasService('cache.provider.foo', DummyAdapter::class);
$this->assertContainerBuilderHasAlias('cache', 'cache.provider.foo');
}
}
|
Simplify the dependencies and wait on the chooseTemplate service (modal) to return the process to create. | (function (module) {
module.controller('ProjectHomeController', ProjectHomeController);
ProjectHomeController.$inject = ["project", "modalInstance", "templates", "$state"];
function ProjectHomeController(project, modalInstance, templates, $state) {
var ctrl = this;
ctrl.project = project;
ctrl.chooseTemplate = chooseTemplate;
ctrl.createSample = createSample;
/////////////////////////
function chooseTemplate() {
modalInstance.chooseTemplate(ctrl.project, templates).then(function(processTemplateName) {
$state.go('projects.project.processes.create', {process: processTemplateName});
});
}
function createSample() {
$state.go('projects.project.processes.create', {process: 'As Received'});
}
}
}(angular.module('materialscommons')));
| (function (module) {
module.controller('ProjectHomeController', ProjectHomeController);
ProjectHomeController.$inject = ["project", "modalInstance", "processTemplates", "$state"];
function ProjectHomeController(project, modalInstance, processTemplates, $state) {
var ctrl = this;
ctrl.project = project;
ctrl.chooseTemplate = chooseTemplate;
ctrl.createSample = createSample;
/////////////////////////
function chooseTemplate() {
modalInstance.chooseTemplate(ctrl.project);
}
function createSample() {
var template = processTemplates.getTemplateByName('As Received');
processTemplates.setActiveTemplate(template);
$state.go('projects.project.processes.create');
}
}
}(angular.module('materialscommons')));
|
Add a link for a new post | import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchPosts } from '../actions';
class PostsIndex extends Component {
componentDidMount() {
this.props.fetchPosts();
}
renderPosts() {
return _.map(this.props.posts, post => {
return (
<li className="list-group-item" key={post.id}>
{post.title}
</li>
);
})
}
render() {
return (
<div>
<div className="text-xs-right">
<Link className="btn btn-primary" to="/posts/new">
Add a Post
</Link>
</div>
<h3>Posts</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
);
}
}
function mapStateToProps(state) {
return { posts: state.posts }
}
export default connect(mapStateToProps, { fetchPosts })(PostsIndex);
| import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
class PostsIndex extends Component {
componentDidMount() {
this.props.fetchPosts();
}
renderPosts() {
return _.map(this.props.posts, post => {
return (
<li className="list-group-item" key={post.id}>
{post.title}
</li>
);
})
}
render() {
return (
<div>
<h3>Posts</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
);
}
}
function mapStateToProps(state) {
return { posts: state.posts }
}
export default connect(mapStateToProps, { fetchPosts })(PostsIndex);
|
Adjust doc strings in Fibonacci numbers implementation | """Implementations calculation of Fibonacci numbers."""
def fib1(amount):
"""
Calculate Fibonacci numbers.
The second variable is used to store the result.
:param amount: Amount of numbers to produce.
:return: Generator.
>>> list(fib1(0))
[]
>>> list(fib1(1))
[0]
>>> list(fib1(3))
[0, 1, 1]
>>> list(fib1(9))
[0, 1, 1, 2, 3, 5, 8, 13, 21]
"""
first, second = 0, 1
for _ in range(amount):
yield first
first, second = second + first, first
def fib2(amount):
"""
Calculate Fibonacci numbers.
The first variable is used to store the result.
:param amount: Amount of numbers to produce.
:return: Generator.
>>> list(fib2(0))
[]
>>> list(fib2(1))
[0]
>>> list(fib2(3))
[0, 1, 1]
>>> list(fib2(9))
[0, 1, 1, 2, 3, 5, 8, 13, 21]
"""
first, second = 1, 0
for _ in range(amount):
first, second = second, first + second
yield first
if __name__ == '__main__':
import doctest
doctest.testmod()
| def fib1(amount):
"""
Fibonacci generator example. The second variable is used to store
the result.
:param amount: Amount of numbers to produce.
:return: Generator.
>>> list(fib1(0))
[]
>>> list(fib1(1))
[0]
>>> list(fib1(3))
[0, 1, 1]
>>> list(fib1(9))
[0, 1, 1, 2, 3, 5, 8, 13, 21]
"""
first, second = 0, 1
for _ in range(amount):
yield first
first, second = second + first, first
def fib2(amount):
"""
Fibonacci generator example. The first variable is used to store
the result.
:param amount: Amount of numbers to produce.
:return: Generator.
>>> list(fib2(0))
[]
>>> list(fib2(1))
[0]
>>> list(fib2(3))
[0, 1, 1]
>>> list(fib2(9))
[0, 1, 1, 2, 3, 5, 8, 13, 21]
"""
first, second = 1, 0
for _ in range(amount):
first, second = second, first + second
yield first
if __name__ == '__main__':
import doctest
doctest.testmod()
|
Add csurf to protect against CSRF attacks | const express = require('express');
const redis = require("redis");
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const passport = require('passport');
const path = require('path');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const csrf = require('csurf');
require('dotenv').config();
const secret = require('./config/secrets');
const routes = require('./routes');
// Config
require('./config/passport')(passport);
const client = redis.createClient();
client.on("error", err => console.log(`Error: ${err} - Are you running redis?`)); // eslint-disable-line
app.use(session({
store: new RedisStore({ client }),
secret: secret.sessionSecret,
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(csrf()); // Inject CSRF token to req.session
// Use dirs appropriately, with a separation of concerns for the public & dist dirs
app.use('/public', express.static(path.join(__dirname, '../public')));
app.use('/dist', express.static(path.join(__dirname, '../dist')));
// Routes
routes(app, passport, io);
// Server
const port = process.env.PORT || 8080;
server.listen(port, function() {
console.log(`Email service live on port ${port}`); // eslint-disable-line
});
| const express = require('express');
const redis = require("redis");
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const passport = require('passport');
const path = require('path');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
require('dotenv').config();
const secret = require('./config/secrets');
const routes = require('./routes');
// Config
require('./config/passport')(passport);
const client = redis.createClient();
client.on("error", err => console.log(`Error: ${err} - Are you running redis?`));
app.use(session({
store: new RedisStore({ client }),
secret: secret.sessionSecret,
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
// Use dirs appropriately, with a separation of concerns for the public & dist dirs
app.use('/public', express.static(path.join(__dirname, '../public')));
app.use('/dist', express.static(path.join(__dirname, '../dist')));
// Routes
routes(app, passport, io);
// Server
const port = process.env.PORT || 8080;
server.listen(port, function() {
console.log(`Email service live on port ${port}`);
});
|
Make compatible with Bleach v2.0 and html5lib v1.0 | import bleach
from markdown.postprocessors import Postprocessor
from markdown import Extension
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
| import bleach
from html5lib.sanitizer import HTMLSanitizer
from markdown.postprocessors import Postprocessor
from markdown import Extension
class MyTokenizer(HTMLSanitizer):
def sanitize_token(self, token):
return token
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks,
tokenizer=MyTokenizer)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
|
Add validation in category and get_slug in post | from django.db import models
from django.core.exceptions import ValidationError
from django.template.defaultfilters import slugify
from django.core.urlresolvers import reverse_lazy
def validate_no_commas(value):
if ',' in value:
raise ValidationError('%s contains commas' % value)
class Category(models.Model):
title = models.CharField(max_length=80, validators=[validate_no_commas])
class Meta:
verbose_name_plural = 'categories'
def __unicode__(self):
return self.title
class Post(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(editable=False, unique=True)
image = models.ImageField(upload_to='posts', blank=True, null=False)
created_on = models.DateTimeField(auto_now_add=True)
content = models.TextField()
categories = models.ManyToManyField(Category)
class Meta:
ordering = ('created_on',)
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = self.get_slug()
super(Post, self).save(*args, **kwargs)
def get_slug(self):
return self.slug or slugify(self.title)
def get_absolute_url(self):
return reverse_lazy('blog:show_post', kwargs={'slug': self.slug})
| from django.db import models
from django.template.defaultfilters import slugify
from django.core.urlresolvers import reverse_lazy
class Category(models.Model):
title = models.CharField(max_length=80)
class Meta:
verbose_name_plural = 'categories'
def __unicode__(self):
return self.title
class Post(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(editable=False, unique=True)
image = models.ImageField(upload_to='posts', blank=True, null=False)
created_on = models.DateTimeField(auto_now_add=True)
content = models.TextField()
categories = models.ManyToManyField(Category)
class Meta:
ordering = ('created_on',)
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse_lazy('blog:show_post', kwargs={'slug': self.slug})
|
Enable Odoo blog for UCW | # -*- coding: utf-8 -*-
{
'name': "Bestja: UCW",
'summary': "Installation configuration for UCW",
'description': "Installation configuration for Uniwersyteckie Centrum Wolontariatu",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific Industry Applications',
'depends': [
'base',
'website_blog',
'bestja_base',
'bestja_volunteer',
'bestja_volunteer_notes',
'bestja_account_deletion',
'bestja_organization',
'bestja_project',
'bestja_offers',
'bestja_offers_moderation',
'bestja_offers_invitations',
'bestja_offers_categorization',
'bestja_files',
'bestja_application_moderation',
'bestja_ucw_permissions',
],
'data': [
'data.xml',
],
'application': True,
}
| # -*- coding: utf-8 -*-
{
'name': "Bestja: UCW",
'summary': "Installation configuration for UCW",
'description': "Installation configuration for Uniwersyteckie Centrum Wolontariatu",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific Industry Applications',
'depends': [
'base',
'bestja_base',
'bestja_volunteer',
'bestja_volunteer_notes',
'bestja_account_deletion',
'bestja_organization',
'bestja_project',
'bestja_offers',
'bestja_offers_moderation',
'bestja_offers_invitations',
'bestja_offers_categorization',
'bestja_files',
'bestja_application_moderation',
'bestja_ucw_permissions',
],
'data': [
'data.xml',
],
'application': True,
}
|
Sort files before hashing to ensure consistency | import os
import hashlib
class Hasher(object):
def __init__(self):
self._hash = hashlib.sha1()
def update(self, arg):
self._hash.update(_sha1(arg))
def update_with_dir(self, dir_path):
for file_path in _all_files(dir_path):
self.update(os.path.relpath(file_path, dir_path))
self.update(open(file_path).read())
def hexdigest(self):
return self._hash.hexdigest()
def _all_files(top):
all_files = []
for root, dirs, files in os.walk(top):
for name in files:
all_files.append(os.path.join(root, name))
return sorted(all_files)
def _sha1(str):
return hashlib.sha1(str).hexdigest()
| import os
import hashlib
class Hasher(object):
def __init__(self):
self._hash = hashlib.sha1()
def update(self, arg):
self._hash.update(_sha1(arg))
def update_with_dir(self, dir_path):
for file_path in _all_files(dir_path):
self.update(os.path.relpath(file_path, dir_path))
self.update(open(file_path).read())
def hexdigest(self):
return self._hash.hexdigest()
def _all_files(top):
all_files = []
for root, dirs, files in os.walk(top):
for name in files:
all_files.append(os.path.join(root, name))
return all_files
def _sha1(str):
return hashlib.sha1(str).hexdigest()
|
vim: Allow mixed-use-of-spaces-and-tabs in specific line of the spec file. | from Config import *
# Not sure what this number does, but we need some threshold that we'd like to
# avoid crossing.
setOption("BadnessThreshold", 42)
# Ignore all lint warnings in submodules:
addFilter('third_party/submodules/')
# Ignore all lint warnings in symlinks from submodules.
addFilter('SPECS/cmake.spec')
addFilter('SPECS/gdb.spec')
addFilter('SPECS/gperftools.spec')
addFilter('SPECS/libcomps.spec')
addFilter('SPECS/nginx.spec')
addFilter('SPECS/perl.spec')
addFilter('perl.src')
addFilter('SPECS/python-iniparse.spec')
addFilter('SPECS/os-prober.spec')
addFilter('SPECS/yum.spec')
# Python is mostly third-party and has lots of warnings.
addFilter('SPECS/python.spec')
addFilter('SPECS/python3.spec')
addFilter('third_party/subtrees/python/python.spec')
addFilter('third_party/subtrees/python3/python3.spec')
# RPM is special, let's ignore warnings from it.
addFilter('SPECS/rpm.spec')
addFilter('third_party/subtrees/rpm/rpm.spec')
# DNF have a lot of weird stuff:
addFilter('dnf.spec.*libdir-macro-in-noarch-package')
# VIM: allow mixed space/tab usage in specific line.
addFilter('vim.spec:218: W: mixed-use-of-spaces-and-tabs')
| from Config import *
# Not sure what this number does, but we need some threshold that we'd like to
# avoid crossing.
setOption("BadnessThreshold", 42)
# Ignore all lint warnings in submodules:
addFilter('third_party/submodules/')
# Ignore all lint warnings in symlinks from submodules.
addFilter('SPECS/cmake.spec')
addFilter('SPECS/gdb.spec')
addFilter('SPECS/gperftools.spec')
addFilter('SPECS/libcomps.spec')
addFilter('SPECS/nginx.spec')
addFilter('SPECS/perl.spec')
addFilter('perl.src')
addFilter('SPECS/python-iniparse.spec')
addFilter('SPECS/os-prober.spec')
addFilter('SPECS/yum.spec')
# Python is mostly third-party and has lots of warnings.
addFilter('SPECS/python.spec')
addFilter('SPECS/python3.spec')
addFilter('third_party/subtrees/python/python.spec')
addFilter('third_party/subtrees/python3/python3.spec')
# RPM is special, let's ignore warnings from it.
addFilter('SPECS/rpm.spec')
addFilter('third_party/subtrees/rpm/rpm.spec')
# DNF have a lot of weird stuff:
addFilter('dnf.spec.*libdir-macro-in-noarch-package')
|
Comment Token from future errors | <?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
//\App\Http\Middleware\VerifyCsrfToken::class,
];
/**
* The application's route middleware.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
];
}
| <?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
];
/**
* The application's route middleware.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
];
}
|
Fix function test to work on both Py 2 + 3 | import instana.http_propagator as ihp
import opentracing as ot
from instana import tracer, options, util
from nose.tools import assert_equals
import inspect
def test_basics():
inspect.isclass(ihp.HTTPPropagator)
inject_func = getattr(ihp.HTTPPropagator, "inject", None)
assert inject_func
assert callable(inject_func)
extract_func = getattr(ihp.HTTPPropagator, "extract", None)
assert extract_func
assert callable(extract_func)
def test_inject():
opts = options.Options()
ot.global_tracer = tracer.InstanaTracer(opts)
carrier = {}
span = ot.global_tracer.start_span("nosetests")
ot.global_tracer.inject(span.context, ot.Format.HTTP_HEADERS, carrier)
assert 'X-Instana-T' in carrier
assert_equals(carrier['X-Instana-T'], util.id_to_header(span.context.trace_id))
assert 'X-Instana-S' in carrier
assert_equals(carrier['X-Instana-S'], util.id_to_header(span.context.span_id))
assert 'X-Instana-L' in carrier
assert_equals(carrier['X-Instana-L'], "1")
| import instana.http_propagator as ihp
import opentracing as ot
from instana import tracer, options, util
from nose.tools import assert_equals
import inspect
def test_basics():
inspect.isclass(ihp.HTTPPropagator)
inject_func = getattr(ihp.HTTPPropagator, "inject", None)
assert inject_func
assert inspect.ismethod(inject_func)
extract_func = getattr(ihp.HTTPPropagator, "extract", None)
assert extract_func
assert inspect.ismethod(extract_func)
def test_inject():
opts = options.Options()
ot.global_tracer = tracer.InstanaTracer(opts)
carrier = {}
span = ot.global_tracer.start_span("nosetests")
ot.global_tracer.inject(span.context, ot.Format.HTTP_HEADERS, carrier)
assert 'X-Instana-T' in carrier
assert_equals(carrier['X-Instana-T'], util.id_to_header(span.context.trace_id))
assert 'X-Instana-S' in carrier
assert_equals(carrier['X-Instana-S'], util.id_to_header(span.context.span_id))
assert 'X-Instana-L' in carrier
assert_equals(carrier['X-Instana-L'], "1")
|
Clarify argument name in build. | import os
from .repository import require_repo, presentation_files
from .helpers import copy_files, remove_directory
default_out_directory = '_site'
def build(content_directory=None, out_directory=None):
"""Builds the site from its content and presentation repository."""
content_directory = content_directory or '.'
out_directory = os.path.abspath(out_directory or default_out_directory)
repo = require_repo(content_directory)
# Prevent user mistakes
if out_directory == '.':
raise ValueError('Output directory must be different than the source directory: ' + repr(out_directory))
if os.path.basename(os.path.relpath(out_directory, content_directory)) == '..':
raise ValueError('Output directory must not contain the source directory: ' + repr(out_directory))
# TODO: read config
# TODO: use virtualenv
# TODO: init and run plugins
# TODO: process with active theme
# Collect and copy static files
files = presentation_files(repo)
remove_directory(out_directory)
copy_files(files, out_directory, repo)
return out_directory
| import os
from .repository import require_repo, presentation_files
from .helpers import copy_files, remove_directory
default_out_directory = '_site'
def build(directory=None, out_directory=None):
"""Builds the site from its content and presentation repository."""
directory = directory or '.'
out_directory = os.path.abspath(out_directory or default_out_directory)
repo = require_repo(directory)
# Prevent user mistakes
if out_directory == '.':
raise ValueError('Output directory must be different than the source directory: ' + repr(out_directory))
if os.path.basename(os.path.relpath(out_directory, directory)) == '..':
raise ValueError('Output directory must not contain the source directory: ' + repr(out_directory))
# TODO: read config
# TODO: use virtualenv
# TODO: init and run plugins
# TODO: process with active theme
# Collect and copy static files
files = presentation_files(repo)
remove_directory(out_directory)
copy_files(files, out_directory, repo)
return out_directory
|
Add `transition` to always convert list | /**
* Consider:
*
* .a {
* margin: 0 5px 0 0;
* }
*
* .a {
* margin: 0;
* }
*
* Would be converted to:
*
* html[dir='ltr'] .a {
* margin: 0 5px 0 0;
* }
*
* html[dir='rtl'] .a {
* margin: 0 0 0 5px;
* }
*
* .a {
* margin: 0;
* }
*
* As the "html[dir] .a" will have more specificity,
* "margin: 0" will be ignored. That's why we must
* convert the following properties *always*, regardless
* of the value.
*
*
*/
module.exports = [
'background',
'background-position',
'background-position-x',
'border',
'border-color',
'border-radius',
'border-style',
'border-width',
'border-top',
'border-right',
'border-bottom',
'border-left',
'box-shadow',
'margin',
'padding',
'text-shadow',
'text-align',
'transform',
'transform-origin',
'transition'
].join('|');
| /**
* Consider:
*
* .a {
* margin: 0 5px 0 0;
* }
*
* .a {
* margin: 0;
* }
*
* Would be converted to:
*
* html[dir='ltr'] .a {
* margin: 0 5px 0 0;
* }
*
* html[dir='rtl'] .a {
* margin: 0 0 0 5px;
* }
*
* .a {
* margin: 0;
* }
*
* As the "html[dir] .a" will have more specificity,
* "margin: 0" will be ignored. That's why we must
* convert the following properties *always*, regardless
* of the value.
*
*
*/
module.exports = [
'background',
'background-position',
'background-position-x',
'border',
'border-color',
'border-radius',
'border-style',
'border-width',
'border-top',
'border-right',
'border-bottom',
'border-left',
'box-shadow',
'margin',
'padding',
'text-shadow',
'text-align',
'transform',
'transform-origin'
].join('|');
|
Remove explicit installation of LeakCanary
As of version 2, it should now auto-install itself | /*
* Copyright (c) 2016 Armel Soro
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.rm3l.maoni.sample;
import android.app.Application;
import com.facebook.stetho.Stetho;
public class MaoniSampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
Stetho.initializeWithDefaults(this);
}
}
}
| /*
* Copyright (c) 2016 Armel Soro
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.rm3l.maoni.sample;
import android.app.Application;
import com.facebook.stetho.Stetho;
import com.squareup.leakcanary.LeakCanary;
public class MaoniSampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
LeakCanary.install(this);
Stetho.initializeWithDefaults(this);
}
}
}
|
XDC: Add verbosity on JSON compare fail
Signed-off-by: Tomasz Michalak <a2fdaa543b4cc5e3d6cd8672ec412c0eb393b86e@antmicro.com> | #!/usr/bin/env python3
"""
This script extracts the top module cells and their corresponding parameters
from json files produced by Yosys.
The return code of this script is used to check if the output is equivalent.
"""
import sys
import json
parameters = ["IOSTANDARD", "DRIVE", "SLEW", "IN_TERM"]
def read_cells(json_file):
with open(json_file) as f:
data = json.load(f)
f.close()
cells = data['modules']['top']['cells']
cells_parameters = dict()
for cell, opts in cells.items():
attributes = opts['parameters']
if len(attributes.keys()):
if any([x in parameters for x in attributes.keys()]):
cells_parameters[cell] = attributes
return cells_parameters
def main():
if len(sys.argv) < 3:
print("Incorrect number of arguments")
exit(1)
cells1 = read_cells(sys.argv[1])
cells2 = read_cells(sys.argv[2])
if cells1 == cells2:
exit(0)
else:
print(json.dumps(cells1, indent=4))
print("VS")
print(json.dumps(cells2, indent=4))
exit(1)
if __name__ == "__main__":
main()
| #!/usr/bin/env python3
"""
This script extracts the top module cells and their corresponding parameters
from json files produced by Yosys.
The return code of this script is used to check if the output is equivalent.
"""
import sys
import json
def read_cells(json_file):
with open(json_file) as f:
data = json.load(f)
f.close()
cells = data['modules']['top']['cells']
cells_parameters = dict()
for cell, opts in cells.items():
cells_parameters[cell] = opts['parameters']
return cells_parameters
def main():
if len(sys.argv) < 3:
print("Incorrect number of arguments")
exit(1)
cells1 = read_cells(sys.argv[1])
cells2 = read_cells(sys.argv[2])
if cells1 == cells2:
exit(0)
else:
exit(1)
if __name__ == "__main__":
main()
|
Add test for shortened save command | package guitests;
import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import org.junit.Test;
import seedu.ezdo.logic.commands.SaveCommand;
public class SaveCommandTest extends EzDoGuiTest {
private final String validDirectory = "./";
private final String inexistentDirectory = "data/COWABUNGA";
@Test
public void save_validDirectory_success() {
commandBox.runCommand("save " + validDirectory);
assertResultMessage(String.format(SaveCommand.MESSAGE_SAVE_TASK_SUCCESS,
validDirectory + SaveCommand.DATA_FILE_NAME));
}
@Test
public void save_shortCommand_success() {
commandBox.runCommand("s " + validDirectory);
assertResultMessage(String.format(SaveCommand.MESSAGE_SAVE_TASK_SUCCESS,
validDirectory + SaveCommand.DATA_FILE_NAME));
}
@Test
public void save_invalidFormat_failure() {
commandBox.runCommand("save");
assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveCommand.MESSAGE_USAGE));
}
@Test
public void save_inexistentDirectory_failure() {
commandBox.runCommand("save " + inexistentDirectory);
assertResultMessage(String.format(SaveCommand.MESSAGE_DIRECTORY_PATH_DOES_NOT_EXIST));
}
}
| package guitests;
import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import org.junit.Test;
import seedu.ezdo.logic.commands.SaveCommand;
public class SaveCommandTest extends EzDoGuiTest {
private final String validDirectory = "./";
private final String inexistentDirectory = "data/COWABUNGA";
@Test
public void save_validDirectory_success() {
commandBox.runCommand("save " + validDirectory);
assertResultMessage(String.format(SaveCommand.MESSAGE_SAVE_TASK_SUCCESS,
validDirectory + SaveCommand.DATA_FILE_NAME));
}
@Test
public void save_invalidFormat_failure() {
commandBox.runCommand("save");
assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveCommand.MESSAGE_USAGE));
}
@Test
public void save_inexistentDirectory_failure() {
commandBox.runCommand("save " + inexistentDirectory);
assertResultMessage(String.format(SaveCommand.MESSAGE_DIRECTORY_PATH_DOES_NOT_EXIST));
}
}
|
Remove unecessary try.. except.. block from PublisherMiddleware.process_response().
The key should always be set by process_request(), which should always be called
before process_response(). | from threading import current_thread
class PublisherMiddleware(object):
_draft_status = {}
@staticmethod
def is_draft(request):
authenticated = request.user.is_authenticated() and request.user.is_staff
is_draft = 'edit' in request.GET and authenticated
return is_draft
def process_request(self, request):
PublisherMiddleware._draft_status[current_thread()] = self.is_draft(request)
@staticmethod
def process_response(request, response):
del PublisherMiddleware._draft_status[current_thread()]
return response
@staticmethod
def get_draft_status():
try:
return PublisherMiddleware._draft_status[current_thread()]
except KeyError:
return False
def get_draft_status():
return PublisherMiddleware.get_draft_status()
| from threading import current_thread
class PublisherMiddleware(object):
_draft_status = {}
@staticmethod
def is_draft(request):
authenticated = request.user.is_authenticated() and request.user.is_staff
is_draft = 'edit' in request.GET and authenticated
return is_draft
def process_request(self, request):
PublisherMiddleware._draft_status[current_thread()] = self.is_draft(request)
@staticmethod
def process_response(request, response):
try:
del PublisherMiddleware._draft_status[current_thread()]
except KeyError:
pass
return response
@staticmethod
def get_draft_status():
try:
return PublisherMiddleware._draft_status[current_thread()]
except KeyError:
return False
def get_draft_status():
return PublisherMiddleware.get_draft_status()
|
Set knob min range to 0 instead of 1 | import React from 'react';
import { storiesOf } from '@storybook/react';
import { number, select } from '@storybook/addon-knobs/react';
import { Box, TextBody } from '../components';
const displayValues = ['inline', 'inline-block', 'block', 'flex', 'inline-flex'];
const justifyContentValues = ['center', 'flex-start', 'flex-end', 'space-around', 'space-between', 'space-evenly'];
const spacingOptions = {
range: true,
min: 0,
max: 8,
step: 1,
};
storiesOf('Box', module)
.addParameters({
info: {
propTablesExclude: [TextBody],
},
})
.add('Basic', () => (
<Box
style={{ backgroundColor: '#fafafa' }}
display={select('display', displayValues, 'block')}
justifyContent={select('justifyContent', justifyContentValues, 'flex-start')}
margin={number('margin', 0, spacingOptions)}
padding={number('padding', 3, spacingOptions)}
>
<TextBody>I'm body text inside a Box component</TextBody>
</Box>
));
| import React from 'react';
import { storiesOf } from '@storybook/react';
import { number, select } from '@storybook/addon-knobs/react';
import { Box, TextBody } from '../components';
const displayValues = ['inline', 'inline-block', 'block', 'flex', 'inline-flex'];
const justifyContentValues = ['center', 'flex-start', 'flex-end', 'space-around', 'space-between', 'space-evenly'];
const spacingOptions = {
range: true,
min: 1,
max: 8,
step: 1,
};
storiesOf('Box', module)
.addParameters({
info: {
propTablesExclude: [TextBody],
},
})
.add('Basic', () => (
<Box
style={{ backgroundColor: '#fafafa' }}
display={select('display', displayValues, 'block')}
justifyContent={select('justifyContent', justifyContentValues, 'flex-start')}
margin={number('margin', 0, spacingOptions)}
padding={number('padding', 3, spacingOptions)}
>
<TextBody>I'm body text inside a Box component</TextBody>
</Box>
));
|
Set PWD env var when customizing Terminal plugin working directory.
PiperOrigin-RevId: 359567768 | /*
* Copyright 2017 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.terminal;
import com.google.idea.blaze.base.model.primitives.WorkspaceRoot;
import com.intellij.openapi.project.Project;
import java.util.Map;
import javax.annotation.Nullable;
import org.jetbrains.plugins.terminal.LocalTerminalCustomizer;
/** Set the default terminal path to the workspace root. */
public class DefaultTerminalLocationCustomizer extends LocalTerminalCustomizer {
@Override
@Nullable
protected String getDefaultFolder(Project project) {
return getWorkspaceRootPath(project);
}
@Override
public String[] customizeCommandAndEnvironment(
Project project, String[] command, Map<String, String> envs) {
String workspaceRootPath = getWorkspaceRootPath(project);
if (workspaceRootPath != null) {
envs.put("PWD", workspaceRootPath);
}
return super.customizeCommandAndEnvironment(project, command, envs);
}
@Nullable
private static String getWorkspaceRootPath(Project project) {
WorkspaceRoot root = WorkspaceRoot.fromProjectSafe(project);
return root != null ? root.toString() : null;
}
}
| /*
* Copyright 2017 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.terminal;
import com.google.idea.blaze.base.model.primitives.WorkspaceRoot;
import com.intellij.openapi.project.Project;
import javax.annotation.Nullable;
import org.jetbrains.plugins.terminal.LocalTerminalCustomizer;
/** Set the default terminal path to the workspace root. */
public class DefaultTerminalLocationCustomizer extends LocalTerminalCustomizer {
@Override
@Nullable
protected String getDefaultFolder(Project project) {
WorkspaceRoot root = WorkspaceRoot.fromProjectSafe(project);
return root != null ? root.toString() : null;
}
}
|
Use activated and deactivated event to ensure that overriding those methods doesn't conflict | import Ember from 'ember';
export function initialize(instance) {
const config = instance.container.lookupFactory('config:environment');
// Default to true when not set
const _includeRouteName = !(config['ember-body-class'].includeRouteName === false);
Ember.Route.reopen({
bodyClasses: [],
addClasses: Ember.on('activate', function() {
const $body = Ember.$('body');
this.get('bodyClasses').forEach(function(klass) {
$body.addClass(klass);
});
if (_includeRouteName) {
$body.addClass(this.get('routeName'));
}
}),
removeClasses: Ember.on('deactivate', function() {
const $body = Ember.$('body');
this.get('bodyClasses').forEach(function(klass) {
$body.removeClass(klass);
});
if (_includeRouteName) {
$body.removeClass(this.get('routeName'));
}
}),
});
}
export default {
name: 'body-class',
initialize: initialize
};
| import Ember from 'ember';
export function initialize(instance) {
const config = instance.container.lookupFactory('config:environment');
// Default to true when not set
const _includeRouteName = !(config['ember-body-class'].includeRouteName === false);
Ember.Route.reopen({
bodyClasses: [],
activate: function() {
const $body = Ember.$('body');
this.get('bodyClasses').forEach(function(klass) {
$body.addClass(klass);
});
if (_includeRouteName) {
$body.addClass(this.get('routeName'));
}
},
deactivate: function() {
const $body = Ember.$('body');
this.get('bodyClasses').forEach(function(klass) {
$body.removeClass(klass);
});
if (_includeRouteName) {
$body.removeClass(this.get('routeName'));
}
},
});
}
export default {
name: 'body-class',
initialize: initialize
};
|
Add in the http module | var config = require("../../shared/config");
var http = require("http");
var observableModule = require("data/observable");
function User() {}
User.prototype = new observableModule.Observable();
User.prototype.login = function() {
};
User.prototype.register = function() {
var that = this;
return new Promise(function(resolve, reject) {
http.request({
url: config.apiUrl + "Users",
method: "POST",
content: JSON.stringify({
Username: that.get("email_address"),
Email: that.get("email_address"),
Password: that.get("password")
}),
headers: {
"Content-Type": "application/json"
}
}).then(function() {
resolve();
}).catch(function() {
reject();
});
});
};
module.exports = User; | var config = require("../../shared/config");
var observableModule = require("data/observable");
function User() {}
User.prototype = new observableModule.Observable();
User.prototype.login = function() {
};
User.prototype.register = function() {
var that = this;
return new Promise(function(resolve, reject) {
http.request({
url: config.apiUrl + "Users",
method: "POST",
content: JSON.stringify({
Username: that.get("email_address"),
Email: that.get("email_address"),
Password: that.get("password")
}),
headers: {
"Content-Type": "application/json"
}
}).then(function() {
resolve();
}).catch(function() {
reject();
});
});
};
module.exports = User; |
Use config helper & update config key | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateRoleUserTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table)
{
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on(config('trusty.model.user'))->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateRoleUserTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table)
{
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on(Config::get('auth.table'))->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
|
FIX - MongoDB warning msgs | /**
* Created by javascript on 24/09/2016.
*/
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
// Create the database connection
mongoose.connect(process.env.MONGO_DB_URL, { useMongoClient: true });
// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', () => {
console.log(`Mongoose connection open to ${process.env.MONGO_DB_URL}`);
});
// If the connection throws an error
mongoose.connection.on('error', (err) => {
console.log(`Mongoose connection error: ${err}`);
});
// When the connection is disconnected
mongoose.connection.on('disconnected', () => {
console.log('Mongoose connection disconnected');
});
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', () => {
mongoose.connection.close(() => {
console.log('Mongoose connection disconnected through app termination');
process.exit(0);
});
});
mongoose.pro;
| /**
* Created by javascript on 24/09/2016.
*/
const mongoose = require('mongoose');
// Create the database connection
mongoose.connect(process.env.MONGO_DB_URL);
// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', function () {
console.log('Mongoose connection open to ' + process.env.MONGO_DB_URL);
});
// If the connection throws an error
mongoose.connection.on('error',function (err) {
console.log('Mongoose connection error: ' + err);
});
// When the connection is disconnected
mongoose.connection.on('disconnected', function () {
console.log('Mongoose connection disconnected');
});
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose connection disconnected through app termination');
process.exit(0);
});
});
|
Remove bad import of sun.NotImplementedException | package com.codingchili.core.storage;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Robin Duda
* <p>
* parses a query in string format.
* <p>
* Implementation is pluggable.
*/
public class QueryParser<T extends Storable> implements StringQueryParser<T> {
private AsyncStorage<T> store;
public QueryParser(AsyncStorage<T> store) {
this.store = store;
}
@Override
public Handler<AsyncResult<Collection<T>>> parse(String expression) {
throw new RuntimeException("NOT IMPLEMENTED");
}
private static String name(String expression) {
Pattern pattern = Pattern.compile("([a-zA-Z ])+(?::)");
Matcher matcher = pattern.matcher(expression);
matcher.group();
if (matcher.groupCount() > 0) {
return matcher.group(0);
} else {
return QueryParser.class.getSimpleName();
}
}
}
| package com.codingchili.core.storage;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Robin Duda
* <p>
* parses a query in string format.
* <p>
* Implementation is pluggable.
*/
public class QueryParser<T extends Storable> implements StringQueryParser<T> {
private AsyncStorage<T> store;
public QueryParser(AsyncStorage<T> store) {
this.store = store;
}
@Override
public Handler<AsyncResult<Collection<T>>> parse(String expression) {
throw new NotImplementedException();
}
private static String name(String expression) {
Pattern pattern = Pattern.compile("([a-zA-Z ])+(?::)");
Matcher matcher = pattern.matcher(expression);
matcher.group();
if (matcher.groupCount() > 0) {
return matcher.group(0);
} else {
return QueryParser.class.getSimpleName();
}
}
}
|
Remove TODO -- handlers have been cleaned up. | #!/usr/bin/env python
#
# Copyright 2010 Hunter Freyer and Michael Kelly
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import html_handlers
import models
def main():
application = webapp.WSGIApplication([
("/", html_handlers.MainPageHandler),
("/about", html_handlers.AboutHandler),
("/make", html_handlers.MakeHandler),
("/make.do", html_handlers.MakeSubmitHandler),
("/mymfks", html_handlers.MyMfksHandler),
("/vote/(.*)", html_handlers.VoteHandler),
("/vote.do", html_handlers.VoteSubmitHandler),
("/i/(.*)", html_handlers.EntityImageHandler),
("/.*", html_handlers.CatchAllHandler),
])
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| #!/usr/bin/env python
#
# Copyright 2010 Hunter Freyer and Michael Kelly
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import html_handlers
import models
def main():
# TODO(mjkelly): Clean up these handlers.
application = webapp.WSGIApplication([
("/", html_handlers.MainPageHandler),
("/about", html_handlers.AboutHandler),
("/make", html_handlers.MakeHandler),
("/make.do", html_handlers.MakeSubmitHandler),
("/mymfks", html_handlers.MyMfksHandler),
("/vote/(.*)", html_handlers.VoteHandler),
("/vote.do", html_handlers.VoteSubmitHandler),
("/i/(.*)", html_handlers.EntityImageHandler),
("/.*", html_handlers.CatchAllHandler),
])
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
|
Add timeout in hope to catch stdout on travis | var expect = require('expect.js');
var helpers = require('../helpers');
describe('bower', function () {
var oldStdout;
var text;
before(function() {
oldStdout = process.stdout.write;
text = '';
process.stdout.write = function(args) {
text += args;
};
});
it('runs bower installation', function (done) {
helpers.require('bin/bower');
setTimeout(function() {
done();
}, 250);
});
after(function() {
process.stdout.write = oldStdout;
expect(text).to.contain('Usage:');
expect(text).to.contain('Commands:');
});
});
| var expect = require('expect.js');
var helpers = require('../helpers');
describe('bower', function () {
var oldStdout;
var text;
before(function() {
oldStdout = process.stdout.write;
text = '';
process.stdout.write = function(args) {
text += args;
};
});
it('runs bower installation', function (done) {
helpers.require('bin/bower');
done();
});
after(function() {
process.stdout.write = oldStdout;
expect(text).to.contain('Usage:');
expect(text).to.contain('Commands:');
});
});
|
Fix for a wrong router path when clicking on a table row. | Template.TableReportView.events({
'click .row-item': function(event, tmpl) {
Router.go(Router.path('Report', {_id: this._id}));
},
'click .checkbox': function(event, tmpl) {
var that = this;
//unchecked fører til at vi må svarteliste rapporten globalt
if($(event.target).prop("checked") == false) {
var blacklist = Session.get('uncheckedReportIds');
blacklist.push(that._id);
Session.set('uncheckedReportIds', blacklist);
}
//hvis ikke må vi fjerne rapporten fra svartelisten
else{
var result = _.reject(Session.get('uncheckedReportIds'), function(id) {
if(id === that._id)
return true;
return false;
});
Session.set('uncheckedReportIds', result);
}
}
});
Template.TableReportView.isChecked = function() {
var blacklist = Session.get('uncheckedReportIds');
if(!_.contains(blacklist, this._id))
return true;
return false;
}
| Template.TableReportView.events({
'click .row-item': function(event, tmpl) {
Router.go('/reports/' + this._id);
},
'click .checkbox': function(event, tmpl) {
var that = this;
//unchecked fører til at vi må svarteliste rapporten globalt
if($(event.target).prop("checked") == false) {
var blacklist = Session.get('uncheckedReportIds');
blacklist.push(that._id);
Session.set('uncheckedReportIds', blacklist);
}
//hvis ikke må vi fjerne rapporten fra svartelisten
else{
var result = _.reject(Session.get('uncheckedReportIds'), function(id) {
if(id === that._id)
return true;
return false;
});
Session.set('uncheckedReportIds', result);
}
}
});
Template.TableReportView.isChecked = function() {
var blacklist = Session.get('uncheckedReportIds');
if(!_.contains(blacklist, this._id))
return true;
return false;
}
|
Change juliet_module to load before other modules for dependency reasons | import os
import imp
modules = {}
def load_modules(path="./modules/"): # Consider adding recursive searching at some point in the future
modules['juliet_module'] = imp.load_source('juliet_module', path + "juliet_module.py")
names = os.listdir(path)
for name in names:
if not name.endswith(".py"): continue
print("Importing module {0}".format(name))
try:
modules[name.split('.')[0]] = imp.load_source(name.split('.')[0], path + name)
except ImportError as e:
print("Error importing module {0} from directory {1}".format(name,os.getcwd()))
print(e)
continue
print("Success")
load_modules()
| import os
import imp
modules = {}
def load_modules(path="./modules/"): # Consider adding recursive sorting at some point in the future
names = os.listdir(path)
for name in names:
if not name.endswith(".py"): continue
print("Importing module {0}".format(name))
name = name.split('.')[0]
try:
new_module = imp.load_source(name, path)
modules[name] = new_module
except ImportError as e:
print("Error importing module {0} from directory {1}".format(name,os.getcwd()))
print(e)
continue
print("Success")
load_modules()
|
Fix Unified previous track request | export const sendText = ({ value }) => JSON.stringify({
ID: 'Relmtech.Keyboard',
Action: 7,
Request: 7,
Run: {
Extras: {
Values:
[{ Value: value }]
},
Name: 'toggle'
}
});
export const launchGoogleMusic = () => JSON.stringify({
ID: 'Unified.GoogleMusic',
Action: 7,
Request: 7,
Run: {
Name: 'launch'
}
});
export const focusAddress = () => JSON.stringify({
ID: 'Unified.Chrome',
Action: 7,
Request: 7,
Run: {
Name: 'address'
}
});
export const triggerCommand = ({ value }) => JSON.stringify({
ID: 'Examples.CustomRun',
Action: 7,
Request: 7,
Run: {
Name: `command${value}`
}
});
export const spotifyPlayPause = () => JSON.stringify({
ID: 'Unified.Spotify',
Action: 7,
Request: 7,
Run: { Name: 'play_pause' }
});
export const spotifyNextTrack = () => JSON.stringify({
ID: 'Unified.Spotify',
Action: 7,
Request: 7,
Run: { Name: 'next' }
});
export const spotifyPrevTrack = () => JSON.stringify({
ID: 'Unified.Spotify',
Action: 7,
Request: 7,
Run: { Name: 'previous' }
});
| export const sendText = ({ value }) => JSON.stringify({
ID: 'Relmtech.Keyboard',
Action: 7,
Request: 7,
Run: {
Extras: {
Values:
[{ Value: value }]
},
Name: 'toggle'
}
});
export const launchGoogleMusic = () => JSON.stringify({
ID: 'Unified.GoogleMusic',
Action: 7,
Request: 7,
Run: {
Name: 'launch'
}
});
export const focusAddress = () => JSON.stringify({
ID: 'Unified.Chrome',
Action: 7,
Request: 7,
Run: {
Name: 'address'
}
});
export const triggerCommand = ({ value }) => JSON.stringify({
ID: 'Examples.CustomRun',
Action: 7,
Request: 7,
Run: {
Name: `command${value}`
}
});
export const spotifyPlayPause = () => JSON.stringify({
ID: 'Unified.Spotify',
Action: 7,
Request: 7,
Run: { Name: 'play_pause' }
});
export const spotifyNextTrack = () => JSON.stringify({
ID: 'Unified.Spotify',
Action: 7,
Request: 7,
Run: { Name: 'next' }
});
export const spotifyPrevTrack = () => JSON.stringify({
ID: 'Unified.Spotify',
Action: 7,
Request: 7,
Run: { Name: 'prev' }
});
|
Set new minimum django-appconf version | from setuptools import setup, find_packages
import account
setup(
name="django-user-accounts",
version=account.__version__,
author="Brian Rosner",
author_email="brosner@gmail.com",
description="a Django user account app",
long_description=open("README.rst").read(),
license="MIT",
url="http://github.com/pinax/django-user-accounts",
packages=find_packages(),
install_requires=[
"django-appconf>=1.0.1",
"pytz>=2015.6"
],
zip_safe=False,
package_data={
"account": [
"locale/*/LC_MESSAGES/*",
],
},
test_suite="runtests.runtests",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Framework :: Django",
]
)
| from setuptools import setup, find_packages
import account
setup(
name="django-user-accounts",
version=account.__version__,
author="Brian Rosner",
author_email="brosner@gmail.com",
description="a Django user account app",
long_description=open("README.rst").read(),
license="MIT",
url="http://github.com/pinax/django-user-accounts",
packages=find_packages(),
install_requires=[
"django-appconf>=0.6",
"pytz>=2015.6"
],
zip_safe=False,
package_data={
"account": [
"locale/*/LC_MESSAGES/*",
],
},
test_suite="runtests.runtests",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Framework :: Django",
]
)
|
BAP-3115: Create handler for merge result data
- updated metadata | <?php
namespace Oro\Bundle\EntityMergeBundle\Metadata;
class DoctrineMetadata extends Metadata implements MetadataInterface
{
/**
* @var string
*/
protected $className;
/**
* @param string $className
* @param array $options
*/
public function __construct($className, array $options = [])
{
$this->className = $className;
parent::__construct($options);
}
/**
* Checks if this field represents simple doctrine field
*
* @return bool
*/
public function isField()
{
return !$this->isAssociation();
}
/**
* Checks if this field represents doctrine association
*
* @return bool
*/
public function isAssociation()
{
return $this->has('targetEntity') && $this->has('joinColumns');
}
/**
* Checks if this metadata relates to field that is mapped in entity
*
* @return bool
*/
public function isMappedBySourceEntity()
{
return $this->isField() || $this->className == $this->get('sourceEntity');
}
}
| <?php
namespace Oro\Bundle\EntityMergeBundle\Metadata;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
class DoctrineMetadata extends Metadata implements MetadataInterface
{
/**
* @var string
*/
protected $className;
/**
* @param string $className
* @param array $options
*/
public function __construct($className, array $options = [])
{
$this->className = $className;
parent::__construct($options);
}
/**
* Checks if this field represents simple doctrine field
*
* @return bool
*/
public function isField()
{
return !$this->isAssociation();
}
/**
* Checks if this field represents doctrine association
*
* @return bool
*/
public function isAssociation()
{
return $this->has('targetEntity') && $this->has('joinColumns');
}
/**
* Checks if this metadata relates to field that is mapped in entity
*
* @return bool
*/
public function isMappedBySourceEntity()
{
return $this->isField() || $this->className == $this->get('sourceEntity');
}
}
|
Clean up the area of study headings | var _ = require('lodash');
var React = require('react');
var RequirementSet = require("./requirementSet");
var AreaOfStudy = React.createClass({
render: function() {
console.log('area-of-study render')
var areaDetails = this.props;//getAreaOfStudy(this.props.name, this.props.type);
var requirementSets = _.map(areaDetails.sets, function(reqset) {
return RequirementSet({
key:reqset.description,
name: reqset.description,
needs: reqset.needs,
count: reqset.count,
requirements: reqset.reqs,
courses: this.props.courses
});
}, this);
return React.DOM.article( {id:areaDetails.id, className:"area-of-study"},
React.DOM.details(null,
React.DOM.summary(null, React.DOM.h1(null, areaDetails.title)),
requirementSets
)
);
}
});
module.exports = AreaOfStudy
| var _ = require('lodash');
var React = require('react');
var RequirementSet = require("./requirementSet");
var AreaOfStudy = React.createClass({
render: function() {
console.log('area-of-study render')
var areaDetails = []//getAreaOfStudy(this.props.name, this.props.type);
var requirementSets = _.map(areaDetails.sets, function(reqset) {
return RequirementSet( {key:reqset.description,
name: reqset.description,
needs: reqset.needs,
count: reqset.count,
requirements: reqset.reqs,
courses: this.props.courses});
}, this);
return React.DOM.article( {id:areaDetails.id, className:"area-of-study"},
React.DOM.details(null,
React.DOM.summary(null, React.DOM.h1(null, areaDetails.title)),
requirementSets
)
);
}
});
module.exports = AreaOfStudy
|
:new: Use the new compile and watch API in cli | #!/usr/bin/env node
'use strict'
process.title = 'ucompiler'
require('debug').enable('UCompiler:*')
var UCompiler = require('..')
var knownCommands = ['go', 'watch']
var parameters = process.argv.slice(2)
if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
console.log('Usage: ucompiler go|watch [path]')
process.exit(0)
}
if (parameters[0] === 'go') {
UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}, function(e) {
console.error(e)
}).then(function(result) {
if (!result.status) {
process.exit(1)
}
})
} else if (parameters[0] === 'watch') {
if (!parameters[1]) {
console.error('You must specify a path to watch')
process.exit(1)
}
UCompiler.watch(parameters[1], {}, function(e) {
console.error(e)
})
}
| #!/usr/bin/env node
'use strict'
process.title = 'ucompiler'
require('debug').enable('UCompiler:*')
var UCompiler = require('..')
var knownCommands = ['go', 'watch']
var parameters = process.argv.slice(2)
if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
console.log('Usage: ucompiler go|watch [path]')
process.exit(0)
}
if (parameters[0] === 'go') {
UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}).catch(function(e) {
console.error(e)
process.exit(1)
})
} else if (parameters[0] === 'watch') {
if (!parameters[1]) {
console.error('You must specify a path to watch')
process.exit(1)
}
UCompiler.watch(parameters[1])
}
|
eslint: Use regex literal instead of constructor | import { parse } from 'papaparse'
import {
compose, filter, find, flatten, identity,
join, map, match, not, skip, takeWhile
} from 'ramda'
const clean = compose(filter(identity), flatten)
const dataRegexp = match(/^(\\d{4}|Year)$/)
function isData (row) {
return !!find(dataRegexp, row)
}
function getRows (csv) {
const parsed = parse(csv, {
dynamicTyping: false,
header: false,
})
return parsed.data
}
function splitHeaders (rows) {
const header = takeWhile(not(isData), rows)
const content = takeWhile(isData, skip(header.length, rows))
const footer = skip(header.length + content.length, rows)
return {
content,
header: clean(header),
footer: clean(footer),
}
}
export function cleanup (rawData) {
const { header, content, footer } = splitHeaders(getRows(rawData))
const text = join('\n', map(join('\t'), content))
// Reparse data rows with dynamic typing
const reparsed = parse(text, {
header: true,
dynamicTyping: true,
})
if (reparsed.errors.length > 0) {
console.error('Errors while parsing raw data:', reparsed.errors)
}
return Object.assign(reparsed, { header, footer })
}
| import { parse } from 'papaparse'
import {
compose, filter, find, flatten, identity,
join, map, match, not, skip, takeWhile
} from 'ramda'
const clean = compose(filter(identity), flatten)
const dataRegexp = match(RegExp('^(\\d{4}|Year)$'))
function isData (row) {
return !!find(dataRegexp, row)
}
function getRows (csv) {
const parsed = parse(csv, {
dynamicTyping: false,
header: false,
})
return parsed.data
}
function splitHeaders (rows) {
const header = takeWhile(not(isData), rows)
const content = takeWhile(isData, skip(header.length, rows))
const footer = skip(header.length + content.length, rows)
return {
content,
header: clean(header),
footer: clean(footer),
}
}
export function cleanup (rawData) {
const { header, content, footer } = splitHeaders(getRows(rawData))
const text = join('\n', map(join('\t'), content))
// Reparse data rows with dynamic typing
const reparsed = parse(text, {
header: true,
dynamicTyping: true,
})
if (reparsed.errors.length > 0) {
console.error('Errors while parsing raw data:', reparsed.errors)
}
return Object.assign(reparsed, { header, footer })
}
|
Remove Python 2/2.7 because they are no longer supported | # -*- coding: utf-8 -*-
#
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from setuptools import setup, find_packages
setup(
name='pysteps',
version='1.0',
packages=find_packages(),
license='LICENSE',
description='Python framework for short-term ensemble prediction systems',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable', 'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Atmospheric Science',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Cython'],
)
| # -*- coding: utf-8 -*-
#
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from setuptools import setup, find_packages
setup(
name='pysteps',
version='1.0',
packages=find_packages(),
license='LICENSE',
description='Python framework for short-term ensemble prediction systems',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable', 'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Atmospheric Science',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Cython'],
)
|
Add body headings to the Example site component | import React from 'react'
import ReactDOMServer from 'react-dom/server'
import Prism from 'prismjs'
import PrismCode from 'react-prism'
import pretty from 'pretty'
import 'prismjs/themes/prism-coy.css'
import './styles.scss'
export default ({heading, description, children}) => {
const output = ReactDOMServer.renderToStaticMarkup(children)
const indentedOutput = pretty(output, { ocd: true })
return (
<div className="Example">
<h3 className="Example_heading">{heading}</h3>
<p className="Example_description">{description}</p>
<div className="Example__body">
<h4 className="Example__body_heading">Preview</h4>
<div className="Example__preview">
{children}
</div>
<h4 className="Example__body_heading">Code</h4>
<div className="Example__snippet">
<pre className="Example__snippet_pre">
<PrismCode className="language-html">
{indentedOutput}
</PrismCode>
</pre>
</div>
</div>
</div>
)
}
| import React from 'react'
import ReactDOMServer from 'react-dom/server'
import Prism from 'prismjs'
import PrismCode from 'react-prism'
import pretty from 'pretty'
import 'prismjs/themes/prism-coy.css'
import './styles.scss'
export default ({heading, description, children}) => {
const output = ReactDOMServer.renderToStaticMarkup(children)
const indentedOutput = pretty(output, { ocd: true })
return (
<div className="Example">
<h3 className="Example_heading">{heading}</h3>
<p className="Example_description">{description}</p>
<div className="Example__body">
<div className="Example__preview">
{children}
</div>
<div className="Example__snippet">
<pre className="Example__snippet_pre">
<PrismCode className="language-html">
{indentedOutput}
</PrismCode>
</pre>
</div>
</div>
</div>
)
}
|
refactoring: Test case name grammar fix. | <?php
namespace Doctrineum;
class EnumTest extends \PHPUnit_Framework_TestCase
{
/** @test */
public function can_create_instance()
{
$instance = Enum::get('foo');
$this->assertInstanceOf(Enum::class, $instance);
}
/** @test */
public function same_instance_for_same_name_is_returned()
{
$firstInstance = Enum::get('foo');
$secondInstance = Enum::get('bar');
$thirdInstance = Enum::get('foo');
$this->assertNotSame($firstInstance, $secondInstance);
$this->assertSame($firstInstance, $thirdInstance);
}
/** @test */
public function returns_same_value_as_created_with()
{
$enum = Enum::get('foo');
$this->assertSame('foo', $enum->getValue());
}
/** @test */
public function as_string_is_of_same_value_as_created_with()
{
$enum = Enum::get('foo');
$this->assertSame('foo', (string)$enum);
}
/**
* @test
* @expectedException \Doctrineum\Exceptions\Logic
*/
public function can_not_be_cloned()
{
$enum = Enum::get('foo');
clone $enum;
}
}
| <?php
namespace Doctrineum;
class EnumTest extends \PHPUnit_Framework_TestCase
{
/** @test */
public function can_create_instance()
{
$instance = Enum::get('foo');
$this->assertInstanceOf(Enum::class, $instance);
}
/** @test */
public function same_instance_for_same_name_is_returned()
{
$firstInstance = Enum::get('foo');
$secondInstance = Enum::get('bar');
$thirdInstance = Enum::get('foo');
$this->assertNotSame($firstInstance, $secondInstance);
$this->assertSame($firstInstance, $thirdInstance);
}
/** @test */
public function returns_same_value_as_created_with()
{
$enum = Enum::get('foo');
$this->assertSame('foo', $enum->getValue());
}
/** @test */
public function as_string_is_of_same_value_as_created_with()
{
$enum = Enum::get('foo');
$this->assertSame('foo', (string)$enum);
}
/**
* @test
* @expectedException \Doctrineum\Exceptions\Logic
*/
public function cant_not_be_cloned()
{
$enum = Enum::get('foo');
clone $enum;
}
}
|
Fix typos and use a better parameter name.
git-svn-id: cde5a1597f50f50feab6f72941f6b219c34291a1@1075403 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec;
/**
* Decodes a String into a String.
*
* @author Apache Software Foundation
* @version $Id$
*/
public interface StringDecoder extends Decoder {
/**
* Decodes a String and returns a String.
*
* @param source the String to decode
*
* @return the encoded String
*
* @throws DecoderException thrown if there is
* an error condition during the Encoding process.
*/
String decode(String source) throws DecoderException;
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec;
/**
* Decodes a String into a String.
*
* @author Apache Software Foundation
* @version $Id$
*/
public interface StringDecoder extends Decoder {
/**
* Decodes a String and returns a String.
*
* @param pString a String to encode
*
* @return the encoded String
*
* @throws DecoderException thrown if there is
* an error conidition during the Encoding process.
*/
String decode(String pString) throws DecoderException;
}
|
Remove bad INFO log "Starting Octavia API server"
This log is also display for health_manager and house_keeping service.
Api service already display "Starting API server on..." in INFO level.
Change-Id: I0a3ff91b556accdfadbad797488d17ae7a95d85b | # Copyright 2014 Rackspace
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_config import cfg
from oslo_log import log
from octavia.common import config
LOG = log.getLogger(__name__)
def prepare_service(argv=None):
"""Sets global config from config file and sets up logging."""
argv = argv or []
config.init(argv[1:])
log.set_defaults()
config.setup_logging(cfg.CONF)
| # Copyright 2014 Rackspace
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_config import cfg
from oslo_log import log
from octavia.common import config
from octavia.i18n import _LI
LOG = log.getLogger(__name__)
def prepare_service(argv=None):
"""Sets global config from config file and sets up logging."""
argv = argv or []
config.init(argv[1:])
LOG.info(_LI('Starting Octavia API server'))
log.set_defaults()
config.setup_logging(cfg.CONF)
|
Add listeners to Backbone question view that render and exit form
-rendering adds model attributes to template and posts them to the page after syncing
-exiting the form hides the form after submission | app = app || {};
app.QuestionView = Backbone.View.extend({
events: {
'submit .question_form': 'submitQuestion',
},
initializeTemplates: function(){
_.templateSettings = { interpolate: /\{\{(.+?)\}\}/g };
this.template = _.template( $('#question_template').html() )
},
initialize: function(){
this.initializeTemplates();
this.$title = $(".new_question");
this.$content = $(".new_content");
this.$form = $(".question_form");
this.$show = $(".formulated_question")
this.model = new app.Question();
this.listenTo(this.model, 'sync', this.render);
this.listenTo(this.model, 'sync', this.exitForm);
},
render: function(){
this.$show.html(this.template(this.model.attributes));
},
exitForm: function(){
this.$title = $(".new_question").val("");
this.$content = $(".new_content").val("");
this.$form.hide();
},
submitQuestion: function(e){
e.preventDefault()
this.model.save({title: this.$title.val(), content: this.$content.val()})
console.log('geez')
}
});
| app = app || {};
app.QuestionView = Backbone.View.extend({
events: {
'submit .question_form': 'submitQuestion',
},
initializeTemplates: function(){
_.templateSettings = { interpolate: /\{\{(.+?)\}\}/g };
this.template = _.template( $('#question_template').html() )
},
initialize: function(){
this.initializeTemplates();
this.$title = $(".new_question");
this.$content = $(".new_content");
this.$form = $(".question_form");
this.$show = $(".formulated_question")
this.model = new app.Question();
},
render: function(){},
submitQuestion: function(e){
e.preventDefault()
this.model.save({title: this.$title.val(), content: this.$content.val()})
console.log('geez')
}
});
|
Check for updates on start. | /* global $ */
/* global requirejs */
'use strict';
var request = require('request');
var ipc = require('electron-safe-ipc/guest');
var pjson = require('./package.json');
exports.init = function() {
ipc.on('checkForUpdates', exports.checkForUpdates);
exports.checkForUpdates(true);
}
exports.checkForUpdates = function(bSilentCheck) {
try {
request(pjson.config.versionCheckURL, function (error, response, body) {
if (!error && response.statusCode == 200) {
var json = JSON.parse(body);
if(json.version > pjson.version) {
$('#modalUpdateAvailable').modal('show');
} else if(!bSilentCheck) {
$('#modalNoUpdateAvailable').modal('show');
}
} else {
console.log(error.toString());
}
})
} catch(error) {
console.log(error.toString());
}
} | /* global $ */
/* global requirejs */
'use strict';
var request = require('request');
var ipc = require('electron-safe-ipc/guest');
var pjson = require('./package.json');
exports.init = function() {
ipc.on('checkForUpdates', exports.checkForUpdates);
}
exports.checkForUpdates = function(bSilentCheck) {
try {
request(pjson.config.versionCheckURL, function (error, response, body) {
if (!error && response.statusCode == 200) {
var json = JSON.parse(body);
if(json.version > pjson.version) {
$('#modalUpdateAvailable').modal('show');
} else if(!bSilentCheck) {
//$('#modalNoUpdateAvailable').modal('show');
$('#modalUpdateAvailable').modal('show');
}
} else {
console.log(error.toString());
}
})
} catch(error) {
console.log(error.toString());
}
} |
Replace exec with spawn for Electron apps | // var wincmd = require('./binaries')
var spawn = require('child_process').spawn
var DarwinEventLogger = require('./darwin')
/**
* EventLogger Constructor
*
* @param {Object|string} [config={}] Configuration
* @param {string} [config.source='NodeJS'] Source
* @param {string} [config.eventLog='APPLICATION'] Event Log
*/
function EventLogger (config) {
DarwinEventLogger.call(this, config)
}
EventLogger.prototype = Object.create(DarwinEventLogger.prototype)
/**
* Write
*
* @param {string} messageType Message Type
* @param {string} message Message
* @param {number} [code=1000] Code
* @param {Function} [callback] Callback
*/
EventLogger.prototype.write = function (messageType, message, code, callback) {
if (message == null) return
if (message.trim().length === 0) return
code = code || 1000
var cmd = [
'eventcreate',
'/L', this.eventLog,
'/T', messageType,
'/SO', this.source,
'/D', message,
'/ID', code
]
const eventcreate = spawn(cmd)
eventcreate.stdout.on('data', function (data) {
console.log('stdout: ' + data)
})
eventcreate.stderr.on('data', function (data) {
if (callback) {
console.log(data)
callback(data)
}
})
}
EventLogger.prototype.constructor = EventLogger
module.exports = EventLogger
| var wincmd = require('./binaries')
var exec = require('child_process').exec
var DarwinEventLogger = require('./darwin')
/**
* EventLogger Constructor
*
* @param {Object|string} [config={}] Configuration
* @param {string} [config.source='NodeJS'] Source
* @param {string} [config.eventLog='APPLICATION'] Event Log
*/
function EventLogger (config) {
DarwinEventLogger.call(this, config)
}
EventLogger.prototype = Object.create(DarwinEventLogger.prototype)
/**
* Write
*
* @param {string} messageType Message Type
* @param {string} message Message
* @param {number} [code=1000] Code
* @param {Function} [callback] Callback
*/
EventLogger.prototype.write = function (messageType, message, code, callback) {
if (message == null) return
if (message.trim().length === 0) return
code = code || 1000
var cmd = 'eventcreate /L ' + this.eventLog + ' /T ' + messageType + ' /SO "' + this.source + '" /D "' + message + '" /ID ' + code
exec(cmd, function (err) {
if (err && err.message.indexOf('Access is Denied')) wincmd.elevate(cmd, callback)
else if (callback) callback(err)
})
}
EventLogger.prototype.constructor = EventLogger
module.exports = EventLogger
|
Improve load more button style | import React from 'react'
import Stats from '../Stats'
import Hit from '../Hit'
import './style.scss'
function renderHasMore (refine) {
return (
<footer className='tc pv3'>
<a
onClick={refine}
style={{fontSize: '.8rem'}}
className='link ttu lh-solid ba br2 cb-ns db dib-l mb2 pv3 ph4 pointer sans-serif white normal bg-animate blue hover-bg-blue hover-white'>
Load More
</a>
</footer>
)
}
function CustomHits (props) {
const {toggle, get, hits, refine, hasMore} = props
const _props = { toggle, get }
return (
<div data-app='hits' className='ph3 ph4-l'>
<Stats />
<div className='pv3'>
{hits.map((item, key) => <Hit item={item} key={key} {..._props} />)}
</div>
{hasMore && renderHasMore(refine)}
</div>
)
}
export default CustomHits
| import React from 'react'
import Stats from '../Stats'
import Hit from '../Hit'
import './style.scss'
function renderHasMore (refine) {
return (
<footer className='tc pv3'>
<a
onClick={refine}
className='pointer f5 f6-l link br2 ba ph3 pv2-l pv3 mb2 db dib-l blue hover-bg-blue hover-white'>
Load more
</a>
</footer>
)
}
function CustomHits (props) {
const {toggle, get, hits, refine, hasMore} = props
const _props = { toggle, get }
return (
<div data-app='hits' className='ph3 ph4-l'>
<Stats />
<div className='pv3'>
{hits.map((item, key) => <Hit item={item} key={key} {..._props} />)}
</div>
{hasMore && renderHasMore(refine)}
</div>
)
}
export default CustomHits
|
Add a way to set map and path in factory | <?php
/**
*
* This file is part of Aura for PHP.
*
* @license http://opensource.org/licenses/bsd-license.php BSD
*
*/
namespace Aura\View;
/**
*
* Factory to create View objects.
*
* @package Aura.View
*
*/
class ViewFactory
{
/**
*
* Returns a new View instance.
*
* @param object $helpers An arbitrary helper manager for the View; if not
* specified, uses the HelperRegistry from this package.
*
* @return View
*
*/
public function newInstance(
$helpers = null,
$view_map = [],
$view_paths = [],
$layout_map = [],
$layout_paths = [],
) {
if (! $helpers) {
$helpers = new HelperRegistry;
}
return new View(
new TemplateRegistry($view_map, $view_paths),
new TemplateRegistry($layout_map, $layout_paths),
$helpers
);
}
}
| <?php
/**
*
* This file is part of Aura for PHP.
*
* @license http://opensource.org/licenses/bsd-license.php BSD
*
*/
namespace Aura\View;
/**
*
* Factory to create View objects.
*
* @package Aura.View
*
*/
class ViewFactory
{
/**
*
* Returns a new View instance.
*
* @param object $helpers An arbitrary helper manager for the View; if not
* specified, uses the HelperRegistry from this package.
*
* @return View
*
*/
public function newInstance($helpers = null)
{
if (! $helpers) {
$helpers = new HelperRegistry;
}
return new View(
new TemplateRegistry,
new TemplateRegistry,
$helpers
);
}
}
|
Fix issue accepting badge on behalf of ninja | 'use strict';
function cdAcceptBadgeCtrl($scope, $state, cdBadgesService, cdUsersService, alertService, $translate, auth) {
var userId = $state.params.userId;
var badgeSlug = $state.params.badgeSlug;
var parent = false;
auth.get_loggedin_user(function (user) {
if (user){
cdUsersService.userProfileData({userId: user.id}, function(profile){
_.each(profile.children, function(child){
if (child === userId) parent = true;
})
finish();
})
} else finish();
});
function finish(){
var badgeData = {
userId: userId,
parent: parent,
badgeSlug: badgeSlug
};
cdBadgesService.acceptBadge(badgeData, function (response) {
if(response.error) {
return alertService.showError($translate.instant(response.error), function () {
goToProfile();
});
}
return alertService.showAlert($translate.instant('Badge Accepted!'), function () {
goToProfile();
});
});
}
function goToProfile() {
$state.go('user-profile', {userId: userId});
}
}
angular.module('cpZenPlatform')
.controller('accept-badge-controller', ['$scope', '$state', 'cdBadgesService', 'cdUsersService', 'alertService', '$translate', 'auth', cdAcceptBadgeCtrl]); | 'use strict';
function cdAcceptBadgeCtrl($scope, $state, cdBadgesService, cdUsersService, alertService, $translate) {
var userId = $state.params.userId;
var badgeSlug = $state.params.badgeSlug;
var parent = false;
if ($scope.user){
cdUsersService.userProfileData({userId: $scope.user.id}, function(profile){
_.each(profile.children, function(child){
if (child === userId) parent = true;
})
finish();
})
} else finish();
function finish(){
var badgeData = {
userId: userId,
parent: parent,
badgeSlug: badgeSlug
};
cdBadgesService.acceptBadge(badgeData, function (response) {
if(response.error) {
return alertService.showError($translate.instant(response.error), function () {
goToProfile();
});
}
return alertService.showAlert($translate.instant('Badge Accepted!'), function () {
goToProfile();
});
});
}
function goToProfile() {
$state.go('user-profile', {userId: userId});
}
}
angular.module('cpZenPlatform')
.controller('accept-badge-controller', ['$scope', '$state', 'cdBadgesService', 'cdUsersService', 'alertService', '$translate', cdAcceptBadgeCtrl]); |
Change Sink to Source in license header | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.android.exoplayer2.upstream.cache;
import com.google.android.exoplayer2.upstream.DataSink;
/**
* A {@link DataSink.Factory} that produces {@link CacheDataSink}.
*/
public final class CacheDataSinkFactory implements DataSink.Factory {
private final Cache cache;
private final long maxCacheFileSize;
/**
* @see CacheDataSink#CacheDataSink(Cache, long)
*/
public CacheDataSinkFactory(Cache cache, long maxCacheFileSize) {
this.cache = cache;
this.maxCacheFileSize = maxCacheFileSize;
}
@Override
public DataSink createDataSink() {
return new CacheDataSink(cache, maxCacheFileSize);
}
}
| /*
* Copyright (C) 2016 The Android Open Sink Project
*
* 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.android.exoplayer2.upstream.cache;
import com.google.android.exoplayer2.upstream.DataSink;
/**
* A {@link DataSink.Factory} that produces {@link CacheDataSink}.
*/
public final class CacheDataSinkFactory implements DataSink.Factory {
private final Cache cache;
private final long maxCacheFileSize;
/**
* @see CacheDataSink#CacheDataSink(Cache, long)
*/
public CacheDataSinkFactory(Cache cache, long maxCacheFileSize) {
this.cache = cache;
this.maxCacheFileSize = maxCacheFileSize;
}
@Override
public DataSink createDataSink() {
return new CacheDataSink(cache, maxCacheFileSize);
}
}
|
[YouTrack] Fix project name fetch regression | /*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/
'use strict';
/* the first selector is required for youtrack-5 and the second for youtrack-6 */
togglbutton.render('.fsi-toolbar-content:not(.toggl), .toolbar_fsi:not(.toggl)', {observe: true}, function (elem) {
var link, description,
numElem = $('a.issueId'),
titleElem = $(".issue-summary"),
projectElem = $('.fsi-properties a[title^="Project"], .fsi-properties .disabled.bold');
description = titleElem.textContent;
description = numElem.firstChild.textContent.trim() + " " + description.trim();
link = togglbutton.createTimerLink({
className: 'youtrack',
description: description,
projectName: projectElem ? projectElem.textContent : ''
});
elem.insertBefore(link, titleElem);
});
// Agile board
togglbutton.render('#board .sb-task:not(.toggl)', {observe: true}, function (elem) {
var link,
container = $('.sb-task-title', elem),
description = $('.sb-task-summary', elem).textContent,
projectName = $('#selectAgile').value.split("(")[1].replace(")", "").trim();
link = togglbutton.createTimerLink({
className: 'youtrack',
description: description,
projectName: projectName
});
container.appendChild(link);
});
| /*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/
'use strict';
/* the first selector is required for youtrack-5 and the second for youtrack-6 */
togglbutton.render('.fsi-toolbar-content:not(.toggl), .toolbar_fsi:not(.toggl)', {observe: true}, function (elem) {
var link, description,
numElem = $('a.issueId'),
titleElem = $(".issue-summary"),
projectElem = $('.fsi-properties .disabled.bold');
description = titleElem.textContent;
description = numElem.firstChild.textContent.trim() + " " + description.trim();
link = togglbutton.createTimerLink({
className: 'youtrack',
description: description,
projectName: projectElem ? projectElem.textContent : ''
});
elem.insertBefore(link, titleElem);
});
// Agile board
togglbutton.render('#board .sb-task:not(.toggl)', {observe: true}, function (elem) {
var link,
container = $('.sb-task-title', elem),
description = $('.sb-task-summary', elem).textContent,
projectName = $('#selectAgile').value.split("(")[1].replace(")", "").trim();
link = togglbutton.createTimerLink({
className: 'youtrack',
description: description,
projectName: projectName
});
container.appendChild(link);
}); |
Add zoom support to chart | var selector = (document.getElementById("cf_crash_signature_edit_container")) ? "cf_crash_signature_edit_container" : "field-value-cf_crash_signature";
var querystring = "";
document.querySelectorAll("#" + selector + " a").forEach(function(element) {
var signature = element.innerText.substring(3,element.innerText.length-2);
if (element.innerText.indexOf("[@") != -1)
querystring = querystring + signature + "\\";
});
if (querystring.length > 0) {
querystring = querystring.substring(0,querystring.length-1);
var iframe = document.createElement('iframe');
iframe.src = 'https://ashughes1.github.io/bugzilla-socorro-lens/chart.htm?s=' + querystring;
iframe.setAttribute('style', 'border:0; height:150px');
iframe.setAttribute('id', 'iframe_chart');
var container = document.getElementById(selector);
if (container) container.appendChild(iframe);
}
| var selector = (document.getElementById("cf_crash_signature_edit_container")) ? "cf_crash_signature_edit_container" : "field-value-cf_crash_signature";
var querystring = "";
document.querySelectorAll("#" + selector + " a").forEach(function(element) {
var signature = element.innerText.substring(3,element.innerText.length-2);
if (element.innerText.indexOf("[@") != -1)
querystring = querystring + signature + "\\";
});
if (querystring.length > 0) {
querystring = querystring.substring(0,querystring.length-1);
var iframe = document.createElement('iframe');
iframe.src = 'https://ashughes1.github.io/bugzilla-socorro-lens/chart.htm?s=' + querystring;
//iframe.src = 'file:///home/ashughes/Development/bugzilla-socorro-lens/chart.htm?s=' + querystring;
iframe.setAttribute('style', 'border:0; height:190px');
var container = document.getElementById(selector);
if (container) container.appendChild(iframe);
}
|
Add styles to dropdown component | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getChannels, setChannel } from '../../actions/index';
/* component styles */
import { styles } from './styles.scss';
class ChannelDropdown extends Component {
componentWillMount() {
this.props.getChannels();
}
renderChannels(channelData) {
const name = channelData.channel.name;
return (
<li key={name} className="dropdown-menu-item" onClick={() => this.props.setChannel(name)}>{name}</li>
);
}
render() {
return (
<div className={`${styles}`}>
<div className="btn-group">
<button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Top Channels <span className="caret"></span>
</button>
<ul className="dropdown-menu">
{this.props.channels.list.map(this.renderChannels, this)}
</ul>
</div>
</div>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ getChannels, setChannel }, dispatch);
}
function mapStateToProps({ channels }) {
return { channels };
}
export default connect(mapStateToProps, mapDispatchToProps)(ChannelDropdown);
| import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getChannels, setChannel } from '../../actions/index';
class ChannelDropdown extends Component {
componentWillMount() {
this.props.getChannels();
}
renderChannels(channelData) {
const name = channelData.channel.name;
return (
<li key={name} onClick={() => this.props.setChannel(name)}>{name}</li>
);
}
render() {
return (
<div className="btn-group">
<button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Top Channels <span className="caret"></span>
</button>
<ul className="dropdown-menu">
{this.props.channels.list.map(this.renderChannels, this)}
</ul>
</div>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ getChannels, setChannel }, dispatch);
}
function mapStateToProps({ channels }) {
return { channels };
}
export default connect(mapStateToProps, mapDispatchToProps)(ChannelDropdown);
|
Fix empty object instead of no body for default audience
The ticket seemed to indicate that if there is no audience specified, then
the request was to have an empty body. However, that leads to a 500 from
the API. Reading the associated plugin show that an empty object is
expected in that case. | package api
import (
"errors"
"fmt"
)
var ErrAudienceTooLong = errors.New("the API only supports at most one element in the audience")
type OidcToken struct {
Token string `json:"token"`
}
func (c *Client) OidcToken(jobId string, audience ...string) (*OidcToken, *Response, error) {
type oidcTokenRequest struct {
Audience string `json:"audience,omitempty"`
}
m := &oidcTokenRequest{}
switch len(audience) {
case 0:
case 1:
m.Audience = audience[0]
default:
// While the spec supports multiple audiences in an Id JWT, our API does
// not support issuing them.
// See: https://openid.net/specs/openid-connect-core-1_0.html#IDToken.
return nil, nil, ErrAudienceTooLong
}
u := fmt.Sprintf("jobs/%s/oidc/tokens", jobId)
req, err := c.newRequest("POST", u, m)
if err != nil {
return nil, nil, err
}
t := &OidcToken{}
resp, err := c.doRequest(req, t)
return t, resp, err
}
| package api
import (
"errors"
"fmt"
)
var ErrAudienceTooLong = errors.New("the API only supports at most one element in the audience")
type OidcToken struct {
Token string `json:"token"`
}
func (c *Client) OidcToken(jobId string, audience ...string) (*OidcToken, *Response, error) {
type oidcTokenRequest struct {
Audience string `json:"audience"`
}
var m *oidcTokenRequest
switch len(audience) {
case 0:
m = nil
case 1:
m = &oidcTokenRequest{Audience: audience[0]}
default:
// While the spec supports multiple audiences in an Id JWT, our API does
// not support issuing them.
// See: https://openid.net/specs/openid-connect-core-1_0.html#IDToken.
return nil, nil, ErrAudienceTooLong
}
u := fmt.Sprintf("jobs/%s/oidc/tokens", jobId)
req, err := c.newRequest("POST", u, m)
if err != nil {
return nil, nil, err
}
t := &OidcToken{}
resp, err := c.doRequest(req, t)
return t, resp, err
}
|
Return the actual return code |
from plumbum import local
import subprocess
PY_ENV = 'py_env'
def install_environment():
assert local.path('setup.py').exists()
# Return immediately if we already have a virtualenv
if local.path(PY_ENV).exists():
return
# Install a virtualenv
local['virtualenv'][PY_ENV]()
local['bash']['-c', 'source {0}/bin/activate && pip install .'.format(PY_ENV)]()
def run_hook(hook, file_args):
# TODO: batch filenames
process = subprocess.Popen(
['bash', '-c', ' '.join(
['source {0}/bin/activate &&'.format(PY_ENV)] +
[hook['entry']] + hook.get('args', []) + list(file_args)
)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
ret = process.communicate()
return (process.returncode,) + ret
return local['bash'][
'-c', ' '.join(
['source {0}/bin/activate &&'.format(PY_ENV)] +
[hook['entry']] + hook.get('args', []) + list(file_args)
)
].run() |
from plumbum import local
import subprocess
PY_ENV = 'py_env'
def install_environment():
assert local.path('setup.py').exists()
# Return immediately if we already have a virtualenv
if local.path(PY_ENV).exists():
return
# Install a virtualenv
local['virtualenv'][PY_ENV]()
local['bash']['-c', 'source {0}/bin/activate && pip install .'.format(PY_ENV)]()
def run_hook(hook, file_args):
# TODO: batch filenames
process = subprocess.Popen(
['bash', '-c', ' '.join(
['source {0}/bin/activate &&'.format(PY_ENV)] +
[hook['entry']] + hook.get('args', []) + list(file_args)
)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
ret = process.communicate()
return (0,) + ret
return local['bash'][
'-c', ' '.join(
['source {0}/bin/activate &&'.format(PY_ENV)] +
[hook['entry']] + hook.get('args', []) + list(file_args)
)
].run() |
Update Edit Feature Form to use FormHelper service. Add validations and alerts. | angular
.module('app')
.controller('featureEditController', [
'$scope',
'$location',
'$routeParams',
'userService',
'featureService',
'actionKitService',
'FormHelper',
'$rootScope',
function($scope, $location, $routeParams, userAPI, Feature, actionKitService, FormHelper, $rootScope) {
$scope.feature = Feature.get({id: $routeParams.id}, function(feature) {
return feature;
});
$scope.showError = FormHelper.showError;
$scope.showSuccess = FormHelper.showSuccess;
$scope.update = function() {
// FormHelper.update(form, model, callback)
FormHelper.update($scope.EditFeatureForm, $scope.feature, function() {
alert("Feature updated successfully");
$location.path('/admin/features');
});
};
}]);
| angular
.module('app')
.controller('featureEditController', [
'$scope',
'$location',
'$routeParams',
'userService',
'featureService',
'actionKitService',
'$rootScope',
function($scope, $location, $routeParams, userAPI, Feature, actionKitService, $rootScope) {
$scope.feature = Feature.get({id: $routeParams.id}, function(feature) {
return feature;
});
$scope.update = function() {
$scope.feature.$update(function(response) {
alert("Feature updated successfully");
$location.path('/admin/features');
});
};
}]);
|
Revert "Make parser parameter required in the constructor as it is a hard dep"
Doing this will break the fallback PluginBroker behavior, as it tries to
instantiate the helper with no parameters to the constructor.
This reverts commit f368725d5742906cb0bf4130c290327adae1b08f. | <?php
namespace EdpMarkdown\View\Helper;
use Zend\View\Helper\AbstractHelper;
class Markdown extends AbstractHelper
{
protected $parser;
public function __construct()
{
}
public function setParser($parser)
{
$this->parser = $parser;
}
public function __invoke($string = null)
{
if (null === $this->parser) {
return $string;
}
if ($string === null) {
return $this;
}
return $this->parser->transform($string);
}
public function start()
{
ob_start();
}
public function end()
{
echo $this->parser->transform(ob_get_clean());
}
}
| <?php
namespace EdpMarkdown\View\Helper;
use Zend\View\Helper\AbstractHelper;
class Markdown extends AbstractHelper
{
protected $parser;
public function __construct($parser)
{
$this->setParser($parser);
}
public function setParser($parser)
{
$this->parser = $parser;
}
public function __invoke($string = null)
{
if (null === $this->parser) {
return $string;
}
if ($string === null) {
return $this;
}
return $this->parser->transform($string);
}
public function start()
{
ob_start();
}
public function end()
{
echo $this->parser->transform(ob_get_clean());
}
}
|
Update 0.6.4
- Fixed exception error |
import requests
import os
def get_apod():
os.makedirs("APODs", exist_ok=True)
try:
apod_data = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY").json()
image_url = apod_data["url"]
if image_url.endswith(".gif"):
raise TypeError
image_data = requests.get(image_url, stream=True)
except (requests.HTTPError or TypeError):
return
with open(os.path.join("APODs", os.path.basename(image_url)), "wb") as imagefile:
for chunk in image_data.iter_content(100000):
imagefile.write(chunk)
return os.path.abspath((os.path.join("APODs", os.path.basename(image_url))))
|
import requests
import os
def get_apod():
os.makedirs("APODs", exist_ok=True)
try:
apod_data = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY").json()
image_url = apod_data["url"]
if image_url.endswith(".gif"):
return
image_data = requests.get(image_url, stream=True)
except requests.HTTPError:
return
with open(os.path.join("APODs", os.path.basename(image_url)), "wb") as imagefile:
for chunk in image_data.iter_content(100000):
imagefile.write(chunk)
return os.path.abspath((os.path.join("APODs", os.path.basename(image_url))))
|
Remove id from required attributes, now new tags are saved | <?php
namespace common\models;
use Yii;
/**
* This is the model class for table "tags".
*
* @property integer $id
* @property integer $frequency
* @property string $name
*/
class Tags extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'tags';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['frequency', 'name'], 'required'], //id removed, new tags are not saved when it is required
[['id', 'frequency'], 'integer'],
[['name'], 'string']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'frequency' => 'Frequency',
'name' => 'Name',
];
}
}
| <?php
namespace common\models;
use Yii;
/**
* This is the model class for table "tags".
*
* @property integer $id
* @property integer $frequency
* @property string $name
*/
class Tags extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'tags';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'frequency', 'name'], 'required'],
[['id', 'frequency'], 'integer'],
[['name'], 'string']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'frequency' => 'Frequency',
'name' => 'Name',
];
}
}
|
Fix bug on get first word | const tjbot = require('./tjbotlib');
const config = require('./config/configs');
const credentials = config.credentials;
const WORKSPACEID = config.conversationWorkspaceId;
const hardware = ['microphone', 'speaker'];
const configuration = {
listen: {
microphoneDeviceId: 'plughw:1,0',
inactivityTimeout: 60,
language: 'pt-BR'
},
wave: {
servoPin: 7
},
speak: {
language: 'pt-BR'
},
verboseLogging: true
};
const tj = new tjbot(hardware, configuration, credentials);
tj.listen((msg) => {
// send to the conversation service
tj.converse(WORKSPACEID, turn, (response) => {
// speak the result
tj.speak(response.description);
});
console.log('Message logger', msg);
// check to see if they are talking to TJBot
const name = msg.split(' ')[0].join();
if (name) {
// remove our name from the message
const turn = msg.replace(/(sara,vara,sarah)*/i, '');
console.log('Turn logger', turn);
// send to the conversation service
tj.converse(WORKSPACEID, turn, (response) => {
// speak the result
tj.speak(response.description);
});
}
})
| const tjbot = require('./tjbotlib');
const config = require('./config/configs');
const credentials = config.credentials;
const WORKSPACEID = config.conversationWorkspaceId;
const hardware = ['microphone', 'speaker'];
const configuration = {
listen: {
microphoneDeviceId: 'plughw:1,0',
inactivityTimeout: 60,
language: 'pt-BR'
},
wave: {
servoPin: 7
},
speak: {
language: 'pt-BR'
},
verboseLogging: true
};
const tj = new tjbot(hardware, configuration, credentials);
tj.listen((msg) => {
// send to the conversation service
tj.converse(WORKSPACEID, turn, (response) => {
// speak the result
tj.speak(response.description);
});
console.log('Message logger', msg);
// check to see if they are talking to TJBot
if (msg.startsWith('Sara')) {
// remove our name from the message
var turn = msg.toLowerCase().replace('Sara'.toLowerCase(), "");
console.log('Turn logger', turn);
// send to the conversation service
tj.converse(WORKSPACEID, turn, (response) => {
// speak the result
tj.speak(response.description);
});
}
})
|
Allow configuration to set proxy directory. | <?php
use Doctrine\ORM\Tools\Setup;
$c = $container;
// Parameters
$c['isDevMode'] = true;
$c['isTestMode'] = false;
$c['isProductionMode'] = false;
$c['database.connection.production'] = array();
// Services
$c['database.connection'] = function($c) {
if ($c['isProductionMode']) {
return $c['database.connection.production'];
}
if ($c['isTestMode']) {
return array(
'driver' => 'pdo_sqlite',
'memory' => true
);
}
return array(
'driver' => 'pdo_sqlite',
'path' => __DIR__ . '/db.sqlite'
);
};
$c['doctrine.entityManager'] = function($c) {
return \Doctrine\ORM\EntityManager::create(
$c['database.connection'], $c['doctrine.config']
);
};
$c['doctrine.config'] = function($c) {
$config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(
array(__DIR__), $c['isDevMode']
);
if (isset($c['doctrine.proxyDir'])) {
$config->setProxyDir($c['doctrine.proxyDir']);
}
return $config;
}; | <?php
use Doctrine\ORM\Tools\Setup;
$c = $container;
// Parameters
$c['isDevMode'] = true;
$c['isTestMode'] = false;
$c['isProductionMode'] = false;
$c['database.connection.production'] = array();
// Services
$c['database.connection'] = function($c) {
if ($c['isProductionMode']) {
return $c['database.connection.production'];
}
if ($c['isTestMode']) {
return array(
'driver' => 'pdo_sqlite',
'memory' => true
);
}
return array(
'driver' => 'pdo_sqlite',
'path' => __DIR__ . '/db.sqlite'
);
};
$c['doctrine.entityManager'] = function($c) {
return \Doctrine\ORM\EntityManager::create(
$c['database.connection'], $c['doctrine.config']
);
};
$c['doctrine.config'] = function($c) {
return \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(
array(__DIR__), $c['isDevMode']
);
}; |
Print a list of aliases, if any exist.
git-svn-id: becfadaebdf67c7884f0d18099f2460615305e2e@921 c76caeb1-94fd-44dd-870f-0c9d92034fc1 | import java.util.*;
import org.xbill.DNS.*;
public class lookup {
public static void
printAnswer(String name, Lookup lookup) {
System.out.print(name + ":");
int result = lookup.getResult();
if (result != Lookup.SUCCESSFUL)
System.out.print(" " + lookup.getErrorString());
System.out.println();
Name [] aliases = lookup.getAliases();
if (aliases.length > 0) {
System.out.print("# aliases: ");
for (int i = 0; i < aliases.length; i++) {
System.out.print(aliases[i]);
if (i < aliases.length - 1)
System.out.print(" ");
}
System.out.println();
}
if (lookup.getResult() == Lookup.SUCCESSFUL) {
Record [] answers = lookup.getAnswers();
for (int i = 0; i < answers.length; i++)
System.out.println(answers[i]);
}
}
public static void
main(String [] args) throws Exception {
short type = Type.A;
int start = 0;
if (args.length > 2 && args[0].equals("-t")) {
type = Type.value(args[1]);
if (type < 0)
throw new IllegalArgumentException("invalid type");
start = 2;
}
for (int i = start; i < args.length; i++) {
Lookup l = new Lookup(args[i], type);
l.run();
printAnswer(args[i], l);
}
}
}
| import java.util.*;
import org.xbill.DNS.*;
public class lookup {
public static void
printAnswer(String name, Lookup lookup) {
System.out.print(name + ":");
int result = lookup.getResult();
if (result != Lookup.SUCCESSFUL)
System.out.print(" " + lookup.getErrorString());
System.out.println();
if (lookup.getResult() == Lookup.SUCCESSFUL) {
Record [] answers = lookup.getAnswers();
for (int i = 0; i < answers.length; i++)
System.out.println(answers[i]);
}
}
public static void
main(String [] args) throws Exception {
short type = Type.A;
int start = 0;
if (args.length > 2 && args[0].equals("-t")) {
type = Type.value(args[1]);
if (type < 0)
throw new IllegalArgumentException("invalid type");
start = 2;
}
for (int i = start; i < args.length; i++) {
Lookup l = new Lookup(args[i], type);
l.run();
printAnswer(args[i], l);
}
}
}
|
Fix a problem with a migration between master and stable branch | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-05-30 10:04
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('projects', '0040_remove_memberships_of_cancelled_users_acounts'),
]
operations = [
migrations.AlterField(
model_name='project',
name='owner',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owned_projects', to=settings.AUTH_USER_MODEL, verbose_name='owner'),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-05-30 10:04
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('projects', '0042_auto_20160525_0911'),
]
operations = [
migrations.AlterField(
model_name='project',
name='owner',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owned_projects', to=settings.AUTH_USER_MODEL, verbose_name='owner'),
),
]
|
Update env id generator test to handle hypenated lake names
[#121817095] | package helpers_test
import (
"crypto/rand"
"errors"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/pivotal-cf-experimental/bosh-bootloader/fakes"
"github.com/pivotal-cf-experimental/bosh-bootloader/helpers"
)
var _ = Describe("EnvIDGenerator", func() {
Describe("Generate", func() {
It("generates a env id with a lake and timestamp", func() {
generator := helpers.NewEnvIDGenerator(rand.Reader)
envID, err := generator.Generate()
Expect(err).NotTo(HaveOccurred())
Expect(envID).To(MatchRegexp(`bbl-env-([a-z]+-{1}){1,2}\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z`))
})
Context("when there are errors", func() {
It("it returns the error", func() {
anError := errors.New("banana")
badReader := fakes.Reader{}
badReader.ReadCall.Returns.Error = anError
generator := helpers.NewEnvIDGenerator(&badReader)
_, err := generator.Generate()
Expect(err).To(Equal(anError))
})
})
})
})
| package helpers_test
import (
"crypto/rand"
"errors"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/pivotal-cf-experimental/bosh-bootloader/fakes"
"github.com/pivotal-cf-experimental/bosh-bootloader/helpers"
)
var _ = Describe("EnvIDGenerator", func() {
Describe("Generate", func() {
It("generates a env id with a lake and timestamp", func() {
generator := helpers.NewEnvIDGenerator(rand.Reader)
envID, err := generator.Generate()
Expect(err).NotTo(HaveOccurred())
Expect(envID).To(MatchRegexp(`bbl-env-[a-z]+-\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z`))
})
Context("when there are errors", func() {
It("it returns the error", func() {
anError := errors.New("banana")
badReader := fakes.Reader{}
badReader.ReadCall.Returns.Error = anError
generator := helpers.NewEnvIDGenerator(&badReader)
_, err := generator.Generate()
Expect(err).To(Equal(anError))
})
})
})
})
|
Print exception when no other info on exception is available | #!/usr/bin/python
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)) +"/pypaswas")
from pacasus.pacasusall import Pacasus
import logging
if __name__ == '__main__':
try:
ppw = Pacasus()
ppw.run()
except Exception as exception:
# Show complete exception when running in DEBUG
if (hasattr(ppw.settings, 'loglevel') and
getattr(logging, 'DEBUG') == ppw.logger.getEffectiveLevel()):
ppw.logger.exception(str(exception))
else:
if len(exception.args) > 0:
print('Program ended. The message was: ' + ','.join(exception.args))
else:
print('Program ended. The message was: {}'.format(exception))
print("Please use the option --help for information on command line arguments.")
| #!/usr/bin/python
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)) +"/pypaswas")
from pacasus.pacasusall import Pacasus
import logging
if __name__ == '__main__':
try:
ppw = Pacasus()
ppw.run()
except Exception as exception:
# Show complete exception when running in DEBUG
if (hasattr(ppw.settings, 'loglevel') and
getattr(logging, 'DEBUG') == ppw.logger.getEffectiveLevel()):
ppw.logger.exception(str(exception))
else:
print('Program ended. The message was: ', ','.join(exception.args))
print("Please use the option --help for information on command line arguments.")
|
Add fail text on fail
refs #6 | #!/usr/bin/env node
const Table = require('tty-table');
const cliSpinners = require('cli-spinners');
const ora = require('ora');
const dailyMenu = require('.');
const spinner = ora('Napi menük letöltése');
spinner.spinner = cliSpinners.bouncingBar;
spinner.color = 'green';
spinner.start();
dailyMenu()
.then(results => {
const table = Table([
{
alias: 'Étterem',
align: 'left',
paddingTop: 1,
paddingRight: 1,
paddingBottom: 1,
paddingLft: 1,
width: 30
},
{
alias: 'Napi ajánlat',
align: 'left',
paddingTop: 1,
paddingRight: 1,
paddingBottom: 1,
paddingLeft: 1,
width: 70
}
]);
results.forEach(restaurant => {
table.push([restaurant.name, restaurant.items.join('\n')]);
});
spinner.succeed('Jóétvágyat!');
console.log(table.render());
})
.catch(err => {
spinner.fail('Valami hiba történt :(');
console.error(err);
});
| #!/usr/bin/env node
const Table = require('tty-table');
const cliSpinners = require('cli-spinners');
const ora = require('ora');
const dailyMenu = require('.');
const spinner = ora('Napi menük letöltése');
spinner.spinner = cliSpinners.bouncingBar;
spinner.color = 'green';
spinner.start();
dailyMenu()
.then(results => {
const table = Table([
{
alias: 'Étterem',
align: 'left',
paddingTop: 1,
paddingRight: 1,
paddingBottom: 1,
paddingLft: 1,
width: 30
},
{
alias: 'Napi ajánlat',
align: 'left',
paddingTop: 1,
paddingRight: 1,
paddingBottom: 1,
paddingLeft: 1,
width: 70
}
]);
results.forEach(restaurant => {
table.push([restaurant.name, restaurant.items.join('\n')]);
});
console.log(table.render());
})
.catch(err => {
console.error(err);
})
.then(() => {
spinner.succeed('Jóétvágyat!');
});
|
Revert those silly Intellij change | package nl.yacht.lakesideresort;
import nl.yacht.lakesideresort.domain.Trip;
public class Main {
public static void main(String[] args) {
/// Create Trip
// set tripnumber
int tripNumber = 1;
// create trip
Trip newTrip = new Trip(tripNumber);
// sleep for 4 seconds
Sleep();
// end the trip
newTrip.end();
// print results
System.out.println("Trip: " + newTrip.getTripNumber() + " has ended.");
System.out.println("Start: " + newTrip.getStartTime());
System.out.println("End: " + newTrip.getEndTime());
System.out.println("Duration: " + newTrip.getDuration());
System.out.println();
}
static void Sleep() {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| package nl.yacht.lakesideresort;
import nl.yacht.lakesideresort.domain.Trip;
public class Main {
public static void main(String[] args) {
/// Create nl.yacht.lakesideresort.domain.Trip
// set tripnumber
int tripNumber = 1;
// create trip
Trip newTrip = new Trip(tripNumber);
// sleep for 4 seconds
Sleep();
// end the trip
newTrip.end();
// print results
System.out.println("nl.yacht.lakesideresort.domain.Trip: " + newTrip.getTripNumber() + " has ended.");
System.out.println("Start: " + newTrip.getStartTime());
System.out.println("End: " + newTrip.getEndTime());
System.out.println("Duration: " + newTrip.getDuration());
System.out.println();
}
static void Sleep() {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
Revert of af99d4483acb36eda65b; Microplate subsets are special and important. | from .grid import GridContainer, GridItem
from .liquids import LiquidWell
class Microplate(GridContainer):
rows = 12
cols = 8
volume = 100
min_vol = 50
max_vol = 90
height = 14.45
length = 127.76
width = 85.47
diameter = 7.15
depth = 3.25
a1_x = 14.38
a1_y = 11.24
spacing = 9
child_class = LiquidWell
def well(self, position):
return self.get_child(position)
def calibrate(self, **kwargs):
"""
Coordinates should represent the center and near-bottom of well
A1 with the pipette tip in place.
"""
super(Microplate, self).calibrate(**kwargs)
class Microplate_96(Microplate):
pass
class Microplate_96_Deepwell(Microplate_96):
volume = 400
min_vol = 50
max_vol = 380
height = 14.6
depth = 10.8 | from .grid import GridContainer, GridItem
from .liquids import LiquidWell
class Microplate(GridContainer):
rows = 12
cols = 8
volume = 100
min_vol = 50
max_vol = 90
height = 14.45
length = 127.76
width = 85.47
diameter = 7.15
depth = 3.25
a1_x = 14.38
a1_y = 11.24
spacing = 9
child_class = LiquidWell
def well(self, position):
return self.get_child(position)
def calibrate(self, **kwargs):
"""
Coordinates should represent the center and near-bottom of well
A1 with the pipette tip in place.
"""
super(Microplate, self).calibrate(**kwargs) |
Use high-resolution timestamps in verbose mode only | package main
import (
"log"
"os"
"os/signal"
"github.com/ecc1/medtronic"
)
const (
verbose = true
)
var (
signalChan = make(chan os.Signal, 1)
)
func main() {
if verbose {
log.SetFlags(log.Ltime | log.Lmicroseconds | log.LUTC)
}
pump, err := medtronic.Open()
if err != nil {
log.Fatal(err)
}
signal.Notify(signalChan, os.Interrupt)
go catchInterrupt(pump)
for packet := range pump.Radio.Incoming() {
if verbose {
log.Printf("raw data: % X (RSSI = %d)\n", packet.Data, packet.Rssi)
}
data, err := pump.DecodePacket(packet)
if err != nil {
log.Printf("%v\n", err)
continue
}
if verbose {
log.Printf(" decoded: % X\n", data)
} else {
log.Printf("% X (RSSI = %d)\n", data, packet.Rssi)
}
}
}
func catchInterrupt(pump *medtronic.Pump) {
<-signalChan
pump.PrintStats()
os.Exit(0)
}
| package main
import (
"log"
"os"
"os/signal"
"github.com/ecc1/medtronic"
)
const (
verbose = false
)
var (
signalChan = make(chan os.Signal, 1)
)
func main() {
pump, err := medtronic.Open()
if err != nil {
log.Fatal(err)
}
signal.Notify(signalChan, os.Interrupt)
go catchInterrupt(pump)
log.SetFlags(log.Ltime | log.Lmicroseconds | log.LUTC)
for packet := range pump.Radio.Incoming() {
if verbose {
log.Printf("raw data: % X (RSSI = %d)\n", packet.Data, packet.Rssi)
}
data, err := pump.DecodePacket(packet)
if err != nil {
log.Printf("%v\n", err)
continue
}
if verbose {
log.Printf(" decoded: % X\n", data)
} else {
log.Printf("% X (RSSI = %d)\n", data, packet.Rssi)
}
}
}
func catchInterrupt(pump *medtronic.Pump) {
<-signalChan
pump.PrintStats()
os.Exit(0)
}
|
Fix core plugin using incorrect class names | package com.enderio.core.common.transform;
import java.util.Map;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion;
@SuppressWarnings("unused")
@MCVersion("1.7.10")
@IFMLLoadingPlugin.SortingIndex(Integer.MAX_VALUE) // we want deobf no matter what
public class EnderCorePlugin implements IFMLLoadingPlugin
{
public static boolean runtimeDeobfEnabled = false;
@Override
public String[] getASMTransformerClass()
{
return new String[] {
"com.enderio.core.common.transform.EnderCoreTransformer",
"com.enderio.core.common.transform.EnderCoreTransformerClient"
};
}
@Override
public String getModContainerClass()
{
return null;
}
@Override
public String getSetupClass()
{
return null;
}
@Override
public void injectData(Map<String, Object> data)
{
runtimeDeobfEnabled = (Boolean) data.get("runtimeDeobfuscationEnabled");
}
@Override
public String getAccessTransformerClass()
{
return null;
}
}
| package com.enderio.core.common.transform;
import java.util.Map;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion;
@SuppressWarnings("unused")
@MCVersion("1.7.10")
@IFMLLoadingPlugin.SortingIndex(Integer.MAX_VALUE) // we want deobf no matter what
public class EnderCorePlugin implements IFMLLoadingPlugin
{
public static boolean runtimeDeobfEnabled = false;
@Override
public String[] getASMTransformerClass()
{
return new String[] {
"com.enderio.core.common.transform.TTCoreTransformer",
"com.enderio.core.common.transform.TTCoreTransformerClient"
};
}
@Override
public String getModContainerClass()
{
return null;
}
@Override
public String getSetupClass()
{
return null;
}
@Override
public void injectData(Map<String, Object> data)
{
runtimeDeobfEnabled = (Boolean) data.get("runtimeDeobfuscationEnabled");
}
@Override
public String getAccessTransformerClass()
{
return null;
}
}
|
Make sure to copy appmanifest.json | const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const babelrcHelper = require('../../config/babelrcHelper').default;
module.exports = ({
directory = process.cwd(),
babel = path.join(directory, 'node_modules', 'babel-cli', 'bin', 'babel.js'),
webpack = path.join(directory, 'node_modules', 'webpack', 'bin', 'webpack.js'),
isIntegrationTest = false,
}) => {
// build for server, using babel
const srcFolder = path.join(directory, 'src');
const builtFolder = path.join(directory, 'build');
const babelrcSrc = path.join(directory, '.babelrc');
const config = babelrcHelper(true, directory, true);
fs.writeFileSync(babelrcSrc, JSON.stringify(config), 'utf8');
execSync(`${babel} ${srcFolder} -d ${builtFolder} --copy-files`);
execSync(`rm ${babelrcSrc}`);
// build for web, using webpack
const webpackConfig = path.join(__dirname, '../../../lib', 'config', 'webpack.prod.js');
const testEnv = (isIntegrationTest) ? 'integration' : 'null';
execSync(`cd ${directory}; TEST_ENV=${testEnv} ${webpack} --config ${webpackConfig}`);
};
| const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const babelrcHelper = require('../../config/babelrcHelper').default;
module.exports = ({
directory = process.cwd(),
babel = path.join(directory, 'node_modules', 'babel-cli', 'bin', 'babel.js'),
webpack = path.join(directory, 'node_modules', 'webpack', 'bin', 'webpack.js'),
isIntegrationTest = false,
}) => {
// build for server, using babel
const srcFolder = path.join(directory, 'src');
const builtFolder = path.join(directory, 'build');
const babelrcSrc = path.join(directory, '.babelrc');
const config = babelrcHelper(true, directory, true);
fs.writeFileSync(babelrcSrc, JSON.stringify(config), 'utf8');
execSync(`${babel} ${srcFolder} -d ${builtFolder}`);
execSync(`rm ${babelrcSrc}`);
// build for web, using webpack
const webpackConfig = path.join(__dirname, '../../../lib', 'config', 'webpack.prod.js');
const testEnv = (isIntegrationTest) ? 'integration' : 'null';
execSync(`cd ${directory}; TEST_ENV=${testEnv} ${webpack} --config ${webpackConfig}`);
};
|
partner_industry_Secondary: Make api constrains multi to avoid error when create a company with 2 contacts | # Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta
# Copyright 2016 Tecnativa S.L. - Vicent Cubells
# Copyright 2018 Eficent Business and IT Consulting Services, S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, exceptions, fields, models, _
class ResPartner(models.Model):
_inherit = 'res.partner'
industry_id = fields.Many2one(string='Main Industry')
secondary_industry_ids = fields.Many2many(
comodel_name='res.partner.industry', string="Secondary Industries",
domain="[('id', '!=', industry_id)]")
@api.constrains('industry_id', 'secondary_industry_ids')
def _check_industries(self):
for partner in self:
if partner.industry_id in partner.secondary_industry_ids:
raise exceptions.ValidationError(
_('The main industry must be different '
'from the secondary industries.'))
| # Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta
# Copyright 2016 Tecnativa S.L. - Vicent Cubells
# Copyright 2018 Eficent Business and IT Consulting Services, S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, exceptions, fields, models, _
class ResPartner(models.Model):
_inherit = 'res.partner'
industry_id = fields.Many2one(string='Main Industry')
secondary_industry_ids = fields.Many2many(
comodel_name='res.partner.industry', string="Secondary Industries",
domain="[('id', '!=', industry_id)]")
@api.constrains('industry_id', 'secondary_industry_ids')
def _check_industries(self):
if self.industry_id in self.secondary_industry_ids:
raise exceptions.ValidationError(
_('The main industry must be different '
'from the secondary industries.'))
|
Fix generateRelations field in model generator. | <?php
use dlds\giixer\generators\model\Generator;
/* @var $this yii\web\View */
/* @var $form yii\widgets\ActiveForm */
/* @var $generator dlds\giixer\generators\model\Generator */
echo $form->field($generator, 'tableName');
echo $form->field($generator, 'modelClass');
echo $form->field($generator, 'ns');
echo $form->field($generator, 'baseClass');
echo $form->field($generator, 'db');
echo $form->field($generator, 'useTablePrefix')->checkbox();
echo $form->field($generator, 'generateRelations')->dropDownList([
Generator::RELATIONS_NONE => 'No relations',
Generator::RELATIONS_ALL => 'All relations',
Generator::RELATIONS_ALL_INVERSE => 'All relations with inverse',
]);
echo $form->field($generator, 'generateLabelsFromComments')->checkbox();
echo $form->field($generator, 'generateQuery')->checkbox();
echo $form->field($generator, 'queryNs');
echo $form->field($generator, 'queryClass');
echo $form->field($generator, 'queryBaseClass');
echo $form->field($generator, 'enableI18N')->checkbox();
echo $form->field($generator, 'messageCategory');
?>
<?=
$form->field($generator, 'template')->sticky()
->label('Code Template')
->dropDownList($templates)->hint('
Please select which set of the templates should be used to generated the code.
')
?>
| <?php
/* @var $this yii\web\View */
/* @var $form yii\widgets\ActiveForm */
/* @var $generator yii\gii\generators\form\Generator */
echo $form->field($generator, 'tableName');
echo $form->field($generator, 'modelClass');
echo $form->field($generator, 'ns');
echo $form->field($generator, 'baseClass');
echo $form->field($generator, 'db');
echo $form->field($generator, 'useTablePrefix')->checkbox();
echo $form->field($generator, 'generateRelations')->checkbox();
echo $form->field($generator, 'generateLabelsFromComments')->checkbox();
echo $form->field($generator, 'generateQuery')->checkbox();
echo $form->field($generator, 'queryNs');
echo $form->field($generator, 'queryClass');
echo $form->field($generator, 'queryBaseClass');
echo $form->field($generator, 'enableI18N')->checkbox();
echo $form->field($generator, 'messageCategory');
?>
<?=
$form->field($generator, 'template')->sticky()
->label('Code Template')
->dropDownList($templates)->hint('
Please select which set of the templates should be used to generated the code.
')
?>
|
Extend supported python versions and some pep8 fixes | # coding: utf8
from distutils.core import setup
import trans
long_description = open('README.rst', 'r').read()
description = 'National characters transcription module.'
setup(
name='trans',
version=trans.__version__,
description=description,
long_description=long_description,
author='Zelenyak Aleksander aka ZZZ',
author_email='zzz.sochi@gmail.com',
url='https://github.com/zzzsochi/trans',
license='BSD',
platforms='any',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
py_modules=['trans'],
)
| # coding: utf8
from distutils.core import setup
import trans
long_description = open('README.rst', 'r').read()
description = 'National characters transcription module.'
setup(
name='trans',
version=trans.__version__,
description=description,
long_description=long_description,
author='Zelenyak Aleksandr aka ZZZ',
author_email='zzz.sochi@gmail.com',
url='https://github.com/zzzsochi/trans',
license='BSD',
platforms='any',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
],
py_modules=['trans'],
)
|
[FIX] Patch 300 et colonne potientiellement existante | <?php
/**
* list_patch_0300
* @package modules.list
*/
class list_patch_0300 extends patch_BasePatch
{
/**
* Entry point of the patch execution.
*/
public function execute()
{
try
{
$newPath = f_util_FileUtils::buildWebeditPath('modules/list/persistentdocument/editablelist.xml');
$newModel = generator_PersistentModel::loadModelFromString(f_util_FileUtils::read($newPath), 'list', 'editablelist');
$newProp = $newModel->getPropertyByName('useVoIfNotTranslated');
f_persistentdocument_PersistentProvider::getInstance()->addProperty('list', 'editablelist', $newProp);
}
catch (BaseException $e)
{
if ($e->getAttribute('sqlstate') != '42S21' || $e->getAttribute('errorcode') != '1060')
{
throw $e;
}
}
foreach (list_EditablelistService::getInstance()->createQuery()->find() as $list)
{
$list->setUseVoIfNotTranslated(true);
$list->save();
}
}
/**
* @return String
*/
protected final function getModuleName()
{
return 'list';
}
/**
* @return String
*/
protected final function getNumber()
{
return '0300';
}
} | <?php
/**
* list_patch_0300
* @package modules.list
*/
class list_patch_0300 extends patch_BasePatch
{
/**
* Entry point of the patch execution.
*/
public function execute()
{
/*$newPath = f_util_FileUtils::buildWebeditPath('modules/list/persistentdocument/editablelist.xml');
$newModel = generator_PersistentModel::loadModelFromString(f_util_FileUtils::read($newPath), 'list', 'editablelist');
$newProp = $newModel->getPropertyByName('useVoIfNotTranslated');
f_persistentdocument_PersistentProvider::getInstance()->addProperty('list', 'editablelist', $newProp);*/
foreach (list_EditablelistService::getInstance()->createQuery()->find() as $list)
{
$list->setUseVoIfNotTranslated(true);
$list->save();
}
}
/**
* @return String
*/
protected final function getModuleName()
{
return 'list';
}
/**
* @return String
*/
protected final function getNumber()
{
return '0300';
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.