text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix case in repo urls | #!/usr/bin/env php
<?php
set_time_limit(0);
$vendorDir = __DIR__;
$deps = array(
array('symfony', 'http://github.com/symfony/symfony', isset($_SERVER['SYMFONY_VERSION']) ? $_SERVER['SYMFONY_VERSION'] : 'origin/master'),
array('knp-menu', 'http://github.com/KnpLabs/KnpMenu.git', 'origin/master'),
);
foreach ($deps as $dep) {
list($name, $url, $rev) = $dep;
echo "> Installing/Updating $name\n";
$installDir = $vendorDir.'/'.$name;
if (!is_dir($installDir)) {
system(sprintf('git clone -q %s %s', escapeshellarg($url), escapeshellarg($installDir)));
}
system(sprintf('cd %s && git fetch -q origin && git reset --hard %s', escapeshellarg($installDir), escapeshellarg($rev)));
}
| #!/usr/bin/env php
<?php
set_time_limit(0);
$vendorDir = __DIR__;
$deps = array(
array('symfony', 'http://github.com/symfony/symfony', isset($_SERVER['SYMFONY_VERSION']) ? $_SERVER['SYMFONY_VERSION'] : 'origin/master'),
array('knp-menu', 'http://github.com/knplabs/KnpMenu.git', 'origin/master'),
);
foreach ($deps as $dep) {
list($name, $url, $rev) = $dep;
echo "> Installing/Updating $name\n";
$installDir = $vendorDir.'/'.$name;
if (!is_dir($installDir)) {
system(sprintf('git clone -q %s %s', escapeshellarg($url), escapeshellarg($installDir)));
}
system(sprintf('cd %s && git fetch -q origin && git reset --hard %s', escapeshellarg($installDir), escapeshellarg($rev)));
}
|
Update the example to j2c the new 0.8+ API.
`j2c.scoped` is gone, Class names are now localized unless `:global()` -ized | import React from 'react';
import j2c from 'j2c';
const styles = j2c.sheet({
'.container': {
'text-align': 'center'
},
'.button': {
'background-color': '#ff0000',
width: '320px',
padding: '20px',
'border-radius': '5px',
border: 'none',
outline: 'none',
':hover': {
color: '#fff',
},
':active': {
position: 'relative',
top: '2px'
},
'@media (max-width: 480px)': {
width: '160px'
}
}
});
const Button = React.createClass({
render() {
return (
<div>
<style>{styles.valueOf()}</style>
<div className={styles.container}>
<button className={styles.button}>Click me!</button>
</div>
</div>
);
}
});
React.render(<Button />, document.getElementById('content'));
| import React from 'react';
import j2c from 'j2c';
const styles = j2c.scoped({
container: {
'text-align': 'center'
},
button: {
'background-color': '#ff0000',
width: '320px',
padding: '20px',
'border-radius': '5px',
border: 'none',
outline: 'none',
':hover': {
color: '#fff',
},
':active': {
position: 'relative',
top: '2px'
},
'@media (max-width: 480px)': {
width: '160px'
}
}
});
const Button = React.createClass({
render() {
return (
<div>
<style>{styles.valueOf()}</style>
<div className={styles.container}>
<button className={styles.button}>Click me!</button>
</div>
</div>
);
}
});
React.render(<Button />, document.getElementById('content'));
|
Add site footer to each documentation generator | var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-font-weight/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-font-weight/tachyons-font-weight.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_font-weight.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8')
var template = fs.readFileSync('./templates/docs/font-weight/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs,
siteFooter: siteFooter
})
fs.writeFileSync('./docs/typography/font-weight/index.html', html)
| var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-font-weight/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-font-weight/tachyons-font-weight.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_font-weight.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/font-weight/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/typography/font-weight/index.html', html)
|
Move javadoc after package to avoid warnings | /**
* 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.rdf.simple;
/**
* A simple in-memory implementation of the Commons RDF API.
* <p>
* This package contains a simple (if not naive) implementation of the Commons RDF API
* using in-memory POJO objects.
* <p>
* Note that although this module fully implements the commons-rdf API,
* it should *not* be considered a reference implementation.
* It is not thread-safe nor scalable, but may be useful for testing
* and simple usage (e.g. output from an independent RDF parser).
* <p>
* To use this implementation, create an instance of {@link SimpleRDFTermFactory}
* and use methods like {@link SimpleRDFTermFactory#createGraph} and
* {@link SimpleRDFTermFactory#createIRI(String)}.
*
*/
| /**
* 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.
*/
/**
* A simple in-memory implementation of the Commons RDF API.
* <p>
* This package contains a simple (if not naive) implementation of the Commons RDF API
* using in-memory POJO objects.
* <p>
* Note that although this module fully implements the commons-rdf API,
* it should *not* be considered a reference implementation.
* It is not thread-safe nor scalable, but may be useful for testing
* and simple usage (e.g. output from an independent RDF parser).
* <p>
* To use this implementation, create an instance of {@link SimpleRDFTermFactory}
* and use methods like {@link SimpleRDFTermFactory#createGraph} and
* {@link SimpleRDFTermFactory#createIRI(String)}.
*
*/
package org.apache.commons.rdf.simple;
|
Remove unnecessary cast left over from netty 4 conversion. | package org.apollo.net.codec.game;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import java.util.List;
import org.apollo.game.event.Event;
import org.apollo.net.release.EventDecoder;
import org.apollo.net.release.Release;
/**
* A {@link OneToOneDecoder} that decodes {@link GamePacket}s into {@link Event}s.
*
* @author Graham
*/
public final class GameEventDecoder extends MessageToMessageDecoder<GamePacket> {
/**
* The current release.
*/
private final Release release;
/**
* Creates the game event decoder with the specified release.
*
* @param release The release.
*/
public GameEventDecoder(Release release) {
this.release = release;
}
@Override
protected void decode(ChannelHandlerContext ctx, GamePacket packet, List<Object> out) {
EventDecoder<?> decoder = release.getEventDecoder(packet.getOpcode());
if (decoder != null) {
out.add(decoder.decode(packet));
} else {
System.out.println("Unidentified packet received - opcode: " + packet.getOpcode() + ".");
}
}
} | package org.apollo.net.codec.game;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import java.util.List;
import org.apollo.game.event.Event;
import org.apollo.net.release.EventDecoder;
import org.apollo.net.release.Release;
/**
* A {@link OneToOneDecoder} that decodes {@link GamePacket}s into {@link Event}s.
*
* @author Graham
*/
public final class GameEventDecoder extends MessageToMessageDecoder<GamePacket> {
/**
* The current release.
*/
private final Release release;
/**
* Creates the game event decoder with the specified release.
*
* @param release The release.
*/
public GameEventDecoder(Release release) {
this.release = release;
}
@Override
protected void decode(ChannelHandlerContext ctx, GamePacket msg, List<Object> out) {
GamePacket packet = (GamePacket) msg;
EventDecoder<?> decoder = release.getEventDecoder(packet.getOpcode());
if (decoder != null) {
out.add(decoder.decode(packet));
} else {
System.out.println("Unidentified packet received - opcode: " + packet.getOpcode() + ".");
}
}
} |
Use weight terminology instead of karma
Signed-off-by: Paul de Wouters <a027184a55211cd23e3f3094f1fdc728df5e0500@hmn.md> | (function ( $ ) {
"use strict";
$(function () {
// catch the upvote/downvote action
$( 'div.comment-weight-container' ).on( 'click', 'span > a', function( e ){
e.preventDefault();
var value = 0;
var comment_id = $(this).data('commentId');
if ( $(this).hasClass( 'vote-up' ) ) {
value = 1;
} else if( $(this).hasClass( 'vote-down' ) ) {
value = -1;
}
$.post( comment_popularity.ajaxurl, {action: 'comment_vote', vote: value, comment_id: comment_id, hmn_vote_nonce: comment_popularity.hmn_vote_nonce}, function( data ){
// update karma
$( 'div#comment-' + data.data.comment_id + ' span.comment-weight' ).text( data.data.weight );
});
});
});
}(jQuery)); | (function ( $ ) {
"use strict";
$(function () {
// catch the upvote/downvote action
$( 'div.karma' ).on( 'click', 'span > a', function( e ){
e.preventDefault();
var value = 0;
var comment_id = $(this).data('commentId');
if ( $(this).hasClass( 'add-karma' ) ) {
value = 1;
} else if( $(this).hasClass( 'remove-karma' ) ) {
value = -1;
}
$.post( comment_popularity.ajaxurl, {action: 'comment_vote', vote: value, comment_id: comment_id, hmn_vote_nonce: comment_popularity.hmn_vote_nonce}, function( data ){
// update karma
$( 'div#comment-' + data.data.comment_id + ' span.comment-karma' ).text( data.data.karma );
});
});
});
}(jQuery)); |
Add a wait for component render to webdriver tests | package org.auraframework.perf.test.components;
import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.perf.core.ComponentPerfAbstractTestCase;
import org.openqa.selenium.By;
import java.net.URLEncoder;
import java.util.logging.Logger;
public final class PerfLoadComponentTest extends ComponentPerfAbstractTestCase {
private static final Logger logger = Logger.getLogger(PerfLoadComponentTest.class.getSimpleName());
public PerfLoadComponentTest(String name, DefDescriptor<ComponentDef> desc) {
super(name, desc);
}
@Override
public void testRun() throws Throwable {
String relativeUrl = "/perfTest/perf.app#" +
URLEncoder.encode("{\"componentDef\":\"" + descriptor + "\"}", "UTF-8");
String url = getAbsoluteURI(relativeUrl).toString();
logger.info("testRun: " + url);
openRaw(url);
String componentName = descriptor.getName();
waitForElementAppear("Container div[data-app-rendered-component] element for thecomponent not present",
By.cssSelector(String.format("[data-app-rendered-component='%s']", componentName)));
}
}
| package org.auraframework.perf.test.components;
import java.net.URLEncoder;
import java.util.logging.Logger;
import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.perf.core.ComponentPerfAbstractTestCase;
public final class PerfLoadComponentTest extends ComponentPerfAbstractTestCase {
private static final Logger logger = Logger.getLogger(PerfLoadComponentTest.class.getSimpleName());
public PerfLoadComponentTest(String name, DefDescriptor<ComponentDef> desc) {
super(name, desc);
}
@Override
public void testRun() throws Throwable {
String relativeUrl = "/perfTest/perf.app#" +
URLEncoder.encode("{\"componentDef\":\"" + descriptor + "\"}", "UTF-8");
String url = getAbsoluteURI(relativeUrl).toString();
logger.info("testRun: " + url);
openRaw(url);
}
}
|
Make sure delay/ttr are passed to the adapter | <?php
/**
* This file is part of PMG\Queue
*
* Copyright (c) 2013 PMG Worldwide
*
* @package PMGQueue
* @copyright 2013 PMG Worldwide
* @license http://opensource.org/licenses/MIT MIT
*/
namespace PMG\Queue\Test;
use PMG\Queue\Producer;
class ProducerTest extends \PHPUnit_Framework_TestCase
{
public function testSetGetAdapter()
{
$adapter = $this->getMock('PMG\\Queue\\Adapter\\AdapterInterface');
$producer = new Producer($adapter);
$this->assertSame($producer->getAdapter(), $adapter);
$new_adapt = $this->getMock('PMG\\Queue\\Adapter\\AdapterInterface');
$producer->setAdapter($new_adapt);
$this->assertSame($producer->getAdapter(), $new_adapt);
}
public function testSuccessfulPutReturnsTrue()
{
$adapter = $this->getMock('PMG\\Queue\\Adapter\\AdapterInterface');
$adapter->expects($this->once())
->method('put')
->with('say_hello', array('name' => 'Chris'), 1000, 10)
->will($this->returnValue(true));
$producer = new Producer($adapter);
$this->assertTrue($producer->addJob('say_hello', array('name' => 'Chris'), 1000, 10));
}
}
| <?php
/**
* This file is part of PMG\Queue
*
* Copyright (c) 2013 PMG Worldwide
*
* @package PMGQueue
* @copyright 2013 PMG Worldwide
* @license http://opensource.org/licenses/MIT MIT
*/
namespace PMG\Queue\Test;
use PMG\Queue\Producer;
class ProducerTest extends \PHPUnit_Framework_TestCase
{
public function testSetGetAdapter()
{
$adapter = $this->getMock('PMG\\Queue\\Adapter\\AdapterInterface');
$producer = new Producer($adapter);
$this->assertSame($producer->getAdapter(), $adapter);
$new_adapt = $this->getMock('PMG\\Queue\\Adapter\\AdapterInterface');
$producer->setAdapter($new_adapt);
$this->assertSame($producer->getAdapter(), $new_adapt);
}
public function testSuccessfulPutReturnsTrue()
{
$adapter = $this->getMock('PMG\\Queue\\Adapter\\AdapterInterface');
$adapter->expects($this->once())
->method('put')
->with('say_hello', array('name' => 'Chris'))
->will($this->returnValue(true));
$producer = new Producer($adapter);
$this->assertTrue($producer->addJob('say_hello', array('name' => 'Chris')));
}
}
|
Stop data flowing off graph | const chart = require('ascii-chart');
function pointsFromBandwidthData(values, numPoints) {
// Define vars
const len = values.length;
const points = [];
let i = 0;
let size;
// Split values into n points
if(numPoints < 2) {
points.push(values);
} else {
if(len % numPoints === 0) {
size = Math.floor(len / numPoints);
while (i < len) {
points.push(values.slice(i, i += size));
}
}
while (i < len) {
size = Math.ceil((len - i) / numPoints--);
points.push(values.slice(i, i += size));
}
}
// Return points
const result = points
// Calculate average value of each point
.map(point => Math.round(point.reduce((a,b) => a + b) / point.length))
// Convert bytes to megabytes
.map(bytes => Number((bytes / 1000000).toPrecision(3)));
return result;
}
module.exports = values => {
if(values && values.length) {
const points = pointsFromBandwidthData(values, 56);
return chart(points, {
width: 125,
height: 20,
padding: 0,
pointChar: '*',
negativePointChar: '.'
});
} else {
return '';
}
}
| const chart = require('ascii-chart');
function pointsFromBandwidthData(values, numPoints) {
// Define vars
const len = values.length;
const points = [];
let i = 0;
let size;
// Split values into n points
if(numPoints < 2) {
points.push(values);
} else {
if(len % numPoints === 0) {
size = Math.floor(len / numPoints);
while (i < len) {
points.push(values.slice(i, i += size));
}
}
while (i < len) {
size = Math.ceil((len - i) / numPoints--);
points.push(values.slice(i, i += size));
}
}
// Return points
const result = points
// Calculate average value of each point
.map(point => Math.round(point.reduce((a,b) => a + b) / point.length))
// Convert bytes to megabytes
.map(bytes => Number((bytes / 1000000).toPrecision(3)));
return result;
}
module.exports = values => {
if(values && values.length) {
const points = pointsFromBandwidthData(values, 57);
return chart(points, {
width: 125,
height: 20,
padding: 0,
pointChar: '*',
negativePointChar: '.'
});
} else {
return '';
}
}
|
[Android] Move content_browsertests to main waterfall/trybots.
It's passing consistently on android_fyi_dbg trybots and on FYI waterfall bots running ICS.
BUG=270144
NOTRY=True
Review URL: https://chromiumcodereview.appspot.com/22299007
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@216442 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Configuration file for android gtest suites."""
# Add new suites here before upgrading them to the stable list below.
EXPERIMENTAL_TEST_SUITES = [
]
# Do not modify this list without approval of an android owner.
# This list determines which suites are run by default, both for local
# testing and on android trybots running on commit-queue.
STABLE_TEST_SUITES = [
'android_webview_unittests',
'base_unittests',
'cc_unittests',
'components_unittests',
'content_unittests',
'gpu_unittests',
'ipc_tests',
'media_unittests',
'net_unittests',
'sql_unittests',
'sync_unit_tests',
'ui_unittests',
'unit_tests',
'webkit_compositor_bindings_unittests',
'webkit_unit_tests',
'breakpad_unittests',
'sandbox_linux_unittests',
'content_browsertests',
]
| # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Configuration file for android gtest suites."""
# Add new suites here before upgrading them to the stable list below.
EXPERIMENTAL_TEST_SUITES = [
'content_browsertests',
]
# Do not modify this list without approval of an android owner.
# This list determines which suites are run by default, both for local
# testing and on android trybots running on commit-queue.
STABLE_TEST_SUITES = [
'android_webview_unittests',
'base_unittests',
'cc_unittests',
'components_unittests',
'content_unittests',
'gpu_unittests',
'ipc_tests',
'media_unittests',
'net_unittests',
'sql_unittests',
'sync_unit_tests',
'ui_unittests',
'unit_tests',
'webkit_compositor_bindings_unittests',
'webkit_unit_tests',
'breakpad_unittests',
'sandbox_linux_unittests',
]
|
Remove unnessary comments and add author. | /*!
* jQuery Expandable Input Plugin v1.0
* https://github.com/armmer1/expandable-input
*
* Copyright 2014, Nattawat Nonsung
*/
/**
* Use immediately Invoked Function Expression to
* - Prevent conflicting with other libary on alias $
* - Scode varaible to be private
*/
(function( $ ) {
$.fn.expandable = function(options) {
// Define default setting
var settings = $.extend({
width: 150,
duration: 300
}, options );
var width = this.width();
this.on("focus", function(){
// $(this).css({width: settings.width});
$(this).animate({
width: settings.width
}, settings.duration, function(){
// callback function
});
});
this.on("blur", function(){
$(this).animate({
width: width
}, settings.duration, function(){
// callback function
});
});
if(settings.action && typeof(settings.action) == "function"){
this.on('keypress', function(e) {
if (e.which === 13) { // press enter
settings.action($(this).val());
}
});
}
// Return jQuery so that it's chainable
return this;
};
}( jQuery )); | /**
* Use immediately Invoked Function Expression to
* - Prevent conflicting with other libary on alias $
* - Scode varaible to be private
*/
(function( $ ) {
$.fn.expandable = function(options) {
// Define default setting
var settings = $.extend({
width: 150,
duration: 300
}, options );
var width = this.width();
// this.css({
// "-webkit-transition": ("width "+settings.duration+"s"),
// "-moz-transition": ("width "+settings.duration+"s"),
// "transition": ("width "+settings.duration+"s"),
// "width": width
// });
this.on("focus", function(){
// $(this).css({width: settings.width});
$(this).animate({
width: settings.width
}, settings.duration, function(){
// callback function
});
});
this.on("blur", function(){
$(this).animate({
width: width
}, settings.duration, function(){
// callback function
});
});
if(settings.action && typeof(settings.action) == "function"){
this.on('keypress', function(e) {
if (e.which === 13) { // press enter
settings.action($(this).val());
}
});
}
// Return jQuery so that it's chainable
return this;
};
}( jQuery )); |
Make NameTag available to modules | /*
* Copyright 2014 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.logic.nameTags;
import org.terasology.entitySystem.Component;
import org.terasology.module.sandbox.API;
import org.terasology.rendering.nui.Color;
/**
* Will make the entity have a name tag overhead in the 3D view.
*
* The text on name tag is based on the {@link org.terasology.logic.common.DisplayNameComponent} this entity.
*
* The color of the name tag is based on the {@link org.terasology.network.ColorComponent} of this entity
*/
@API
public class NameTagComponent implements Component {
public float yOffset = 0.3f;
public String text;
public Color textColor = Color.WHITE;
}
| /*
* Copyright 2014 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.logic.nameTags;
import org.terasology.entitySystem.Component;
import org.terasology.rendering.nui.Color;
/**
* Will make the entity have a name tag overhead in the 3D view.
*
* The text on name tag is based on the {@link org.terasology.logic.common.DisplayNameComponent} this entity.
*
* The color of the name tag is based on the {@link org.terasology.network.ColorComponent} of this entity
*/
public class NameTagComponent implements Component {
public float yOffset = 0.3f;
public String text;
public Color textColor = Color.WHITE;
}
|
Update file transfer example to match updates to filestream | var dropkick = require('dropkick');
var quickconnect = require('rtc-quickconnect');
var fileReader = require('filestream/read');
var fileReceiver = require('filestream/write');
var createDataStream = require('..');
var channels = [];
var peers = [];
var inbound = {};
function prepStream(dc, id) {
createDataStream(dc).pipe(fileReceiver(function(file, metadata) {
console.log('received file from: ' + id, file, metadata);
// get ready to receive another stream
setTimeout(function() {
prepStream(dc, id);
}, 50);
}));
}
quickconnect('http://rtc.io/switchboard', { room: 'filetx-test' })
.createDataChannel('files')
.on('channel:opened:files', function(id, dc) {
channels.push(dc);
peers.push(id);
prepStream(dc, id);
})
.on('peer:leave', function(id) {
var peerIdx = peers.indexOf(id);
if (peerIdx >= 0) {
peers.splice(peerIdx, 1);
channels.splice(peerIdx, 1);
}
})
dropkick(document.body).on('file', function(file) {
channels.map(createDataStream).forEach(function(stream) {
fileReader(file, { meta: true }).pipe(stream);
});
});
// give the document some size so we can drag and drop stuff
document.body.style.width = '100vw';
document.body.style.height = '100vw';
| var dropkick = require('dropkick');
var quickconnect = require('rtc-quickconnect');
var fileReader = require('filestream/read');
var fileReceiver = require('filestream/write');
var createDataStream = require('..');
var channels = [];
var peers = [];
var inbound = {};
function prepStream(dc, id) {
createDataStream(dc).pipe(fileReceiver(function(file, metadata) {
console.log('received file from: ' + id, file, metadata);
// get ready to receive another stream
setTimeout(function() {
prepStream(dc, id);
}, 50);
}));
}
quickconnect('http://rtc.io/switchboard', { room: 'filetx-test' })
.createDataChannel('files')
.on('channel:opened:files', function(id, dc) {
channels.push(dc);
peers.push(id);
prepStream(dc, id);
})
.on('peer:leave', function(id) {
var peerIdx = peers.indexOf(id);
if (peerIdx >= 0) {
peers.splice(peerIdx, 1);
channels.splice(peerIdx, 1);
}
})
dropkick(document.body).on('file', function(file) {
channels.map(createDataStream).forEach(function(stream) {
fileReader(file).pipe(stream);
});
});
// give the document some size so we can drag and drop stuff
document.body.style.width = '100vw';
document.body.style.height = '100vw';
|
Edit error message to include ✨ emoji. V important | 'use strict';
const characters = require('./characters');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json()); //support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true})); //support encoded bodies.
//must say {extended: true} because compressed bodies will be inflated and the default value of the extended option has been deprecated
const server = app.listen(3000, () => {
console.log('Express server is listening on part %d in %s mode', server.address().port, app.settings.env);
});
//HTTP POST route method
app.post('/', (req, res) => {
let text = req.body.text;
if(! /[A-z]/g.test(text)) { //if an Adventure Time Character's name contains integers
res.send("Please don't enter numbers, but rather please enter a character from Adventure Time, like Lumpy Space Princess.");
return;
}
let name = text.replace(/\s/g,'').toLowerCase();
if (!(name in characters)) {
res.send(`Sorry about that, "${name}" is not an Adventure Time character I recognize ⭐️ `);
return;
}
let data = {
response_type: 'in_channel', //public to channel
text: `${name} found ✨`,
attachments:[ {
image_url: characters[name]
} ]};
res.json(data);
}
)
| 'use strict';
const characters = require('./characters');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json()); //support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true})); //support encoded bodies.
//must say {extended: true} because compressed bodies will be inflated and the default value of the extended option has been deprecated
const server = app.listen(3000, () => {
console.log('Express server is listening on part %d in %s mode', server.address().port, app.settings.env);
});
//HTTP POST route method
app.post('/', (req, res) => {
let text = req.body.text;
if(! /[A-z]/g.test(text)) { //if an Adventure Time Character's name contains integers
res.send("Please don't enter numbers, but rather please enter a character from Adventure Time, like Lumpy Space Princess.");
return;
}
let name = text.replace(/\s/g,'').toLowerCase();
if (!(name in characters)) {
res.send(`Sorry about that, "${name}" is not an Adventure Time character I recognize ⭐️ `);
return;
}
let data = {
response_type: 'in_channel', //public to channel
text: `${name} Found`,
attachments:[ {
image_url: characters[name]
} ]};
res.json(data);
}
)
|
Change required privilege of QueryJobQueueAction (SERVER_OPERATION -> PROCESS_MANAGE) | <?php
class QueryJobQueueAction extends ApiActionBase
{
protected static $required_privileges = array(
Auth::PROCESS_MANAGE
);
protected function execute($params)
{
$jobs = Job::select(
array('status >=' => Job::JOB_NOT_ALLOCATED),
array('order' => array('registered_at'))
);
$job_list = array();
foreach($jobs as $job)
{
$item = $job->getData();
$plugin = $job->Plugin;
$item['plugin_name'] = $plugin->fullName();
$item['plugin_type'] = $plugin->pluginType();
Patient::$anonymizeMode = $this->currentUser->needsAnonymization();
if($plugin->type == Plugin::CAD_PLUGIN)
{
$series = $job->Series;
$primarySeries = $series[0];
$item['patient_id'] = $primarySeries->Study->Patient->patient_id;
$item['study_id'] = $primarySeries->Study->study_id;
$item['series_id'] = $primarySeries->series_number;
}
else
{
$item['patient_id'] = $item['study_id'] = $item['series_id'] = '-';
}
$job_list[] = $item;
}
return array('jobs' => $job_list);
}
} | <?php
class QueryJobQueueAction extends ApiActionBase
{
protected static $required_privileges = array(
Auth::SERVER_OPERATION
);
protected function execute($params)
{
$jobs = Job::select(
array('status >=' => Job::JOB_NOT_ALLOCATED),
array('order' => array('registered_at'))
);
$job_list = array();
foreach($jobs as $job)
{
$item = $job->getData();
$plugin = $job->Plugin;
$item['plugin_name'] = $plugin->fullName();
$item['plugin_type'] = $plugin->pluginType();
Patient::$anonymizeMode = $this->currentUser->needsAnonymization();
if($plugin->type == Plugin::CAD_PLUGIN)
{
$series = $job->Series;
$primarySeries = $series[0];
$item['patient_id'] = $primarySeries->Study->Patient->patient_id;
$item['study_id'] = $primarySeries->Study->study_id;
$item['series_id'] = $primarySeries->series_number;
}
else
{
$item['patient_id'] = $item['study_id'] = $item['series_id'] = '-';
}
$job_list[] = $item;
}
return array('jobs' => $job_list);
}
} |
Modify to pass args to the base class constructor | """
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import sqlite3
from typing import Optional
from tabledata import NameValidationError # noqa: W0611
class DatabaseError(sqlite3.DatabaseError):
"""
Exception raised for errors that are related to the database.
.. seealso::
- `sqlite3.DatabaseError <https://docs.python.org/3/library/sqlite3.html#sqlite3.DatabaseError>`__
"""
class NullDatabaseConnectionError(DatabaseError):
"""
Exception raised when executing an operation of
:py:class:`~simplesqlite.SimpleSQLite` instance without connection to
a SQLite database file.
"""
class TableNotFoundError(DatabaseError):
"""
Exception raised when accessed the table that not exists in the database.
"""
class AttributeNotFoundError(DatabaseError):
"""
Exception raised when accessed the attribute that not exists in the table.
"""
class SqlSyntaxError(Exception):
"""
Exception raised when a SQLite query syntax is invalid.
"""
class OperationalError(sqlite3.OperationalError):
"""
Exception raised when failed to execute a query.
"""
@property
def message(self) -> Optional[str]:
return self.__message
def __init__(self, *args, **kwargs) -> None:
self.__message = kwargs.pop("message", None)
super().__init__(*args)
| """
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import sqlite3
from typing import Optional
from tabledata import NameValidationError # noqa: W0611
class DatabaseError(sqlite3.DatabaseError):
"""
Exception raised for errors that are related to the database.
.. seealso::
- `sqlite3.DatabaseError <https://docs.python.org/3/library/sqlite3.html#sqlite3.DatabaseError>`__
"""
class NullDatabaseConnectionError(DatabaseError):
"""
Exception raised when executing an operation of
:py:class:`~simplesqlite.SimpleSQLite` instance without connection to
a SQLite database file.
"""
class TableNotFoundError(DatabaseError):
"""
Exception raised when accessed the table that not exists in the database.
"""
class AttributeNotFoundError(DatabaseError):
"""
Exception raised when accessed the attribute that not exists in the table.
"""
class SqlSyntaxError(Exception):
"""
Exception raised when a SQLite query syntax is invalid.
"""
class OperationalError(sqlite3.OperationalError):
"""
Exception raised when failed to execute a query.
"""
@property
def message(self) -> Optional[str]:
return self.__message
def __init__(self, *args, **kwargs) -> None:
self.__message = kwargs.pop("message", None)
super().__init__()
|
Put table into container on admin | <?php
$rank = 1;
include 'includes/sqllogin.php';
$result = mysqli_query($con,"SELECT * FROM `Top Player` ORDER BY Distance DESC");
echo "<div class='container'><table class='table table-striped'>
<tr>
<th>ID</th>
<th>Rank</th>
<th>Player Name</th>
<th>Distance</th>
<th>Edit</th>
<th>Delete</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['PlayerID'] . "</td>";
echo "<td>" . $rank++ . "</td>";
echo "<td>" . $row['PlayerName'] . "</td>";
echo "<td>" . $row['Distance'] . "</td>";
echo "<td><a href='edituser.php?id=". $row['PlayerID'] . "'>EDIT</a></td>";
echo "<td><a href='delete.php?id=". $row['PlayerID'] . "'>DELETE</a></td>";
echo "</tr>";
}
echo "</div></table>";
mysqli_close($con);
?> | <?php
$rank = 1;
include 'includes/sqllogin.php';
$result = mysqli_query($con,"SELECT * FROM `Top Player` ORDER BY Distance DESC");
echo "<table class='table table-striped'>
<tr>
<th>ID</th>
<th>Rank</th>
<th>Player Name</th>
<th>Distance</th>
<th>Edit</th>
<th>Delete</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['PlayerID'] . "</td>";
echo "<td>" . $rank++ . "</td>";
echo "<td>" . $row['PlayerName'] . "</td>";
echo "<td>" . $row['Distance'] . "</td>";
echo "<td><a href='edituser.php?id=". $row['PlayerID'] . "'>EDIT</a></td>";
echo "<td><a href='delete.php?id=". $row['PlayerID'] . "'>DELETE</a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?> |
Implement UpperCamelCase name check for protocols | from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import is_upper_camel_case
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase')
def enterEnumCaseName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Enum case names should be in UpperCamelCase')
def enterStructName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Struct names should be in UpperCamelCase')
def enterProtocolName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Protocol names should be in UpperCamelCase')
@staticmethod
def __verify_upper_camel_case(ctx, err_msg):
construct_name = ctx.getText()
if not is_upper_camel_case(construct_name):
print('Line', str(ctx.start.line) + ':', err_msg)
| from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import is_upper_camel_case
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase')
def enterEnumCaseName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Enum case names should be in UpperCamelCase')
def enterStructName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Struct names should be in UpperCamelCase')
@staticmethod
def __verify_upper_camel_case(ctx, err_msg):
construct_name = ctx.getText()
if not is_upper_camel_case(construct_name):
print('Line', str(ctx.start.line) + ':', err_msg)
|
Use getTableName() so it works with prefixes
Installs that use a table prefix like "mage_" do not work with the current code. It produces the following error...
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'core_config_data' doesn't exist | <?php
/**
* Amazon Payments
*
* @category Amazon
* @package Amazon_Payments
* @copyright Copyright (c) 2014 Amazon.com
* @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
*/
$installer = $this;
$installer->startSetup();
$db = $installer->getConnection();
// Encrypt keys
$select = $db->select()
->from(Mage::getSingleton('core/resource')->getTableName('core_config_data'))
->where('path IN (?)', array('payment/amazon_payments/access_secret', 'payment/amazon_payments/client_secret'));
foreach ($db->fetchAll($select) as $row) {
$db->update(Mage::getSingleton('core/resource')->getTableName('core_config_data'), array('value' => Mage::helper('core')->encrypt(trim($row['value']))), 'config_id=' . $row['config_id']);
}
$installer->endSetup();
| <?php
/**
* Amazon Payments
*
* @category Amazon
* @package Amazon_Payments
* @copyright Copyright (c) 2014 Amazon.com
* @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
*/
$installer = $this;
$installer->startSetup();
$db = $installer->getConnection();
// Encrypt keys
$select = $db->select()
->from('core_config_data')
->where('path IN (?)', array('payment/amazon_payments/access_secret', 'payment/amazon_payments/client_secret'));
foreach ($db->fetchAll($select) as $row) {
$db->update('core_config_data', array('value' => Mage::helper('core')->encrypt(trim($row['value']))), 'config_id=' . $row['config_id']);
}
$installer->endSetup();
|
Move getPrediction function to controller | const Model = require('../../database/models/model.js');
const Redis = require('../../database/redis/redis.js')
const axios = require('axios');
module.exports = {
getHistoricalData: (req, res) => {
Model.historicalGraphData.findOne({where: {currency: req.query[0]}})
.then(graph => {
const reformatted = graph.dataValues.data.map(x => {
const temp = [];
temp.push(Number(x[0]));
temp.push(Number(x[1]))
return temp;
})
res.send(reformatted);
})
},
getPredictionData: (req, res) => {
Model.Prediction.findOne({where: {currency: req.query[0]}})
.then(response => {
let data = JSON.parse(response)
res.send(data);
})
}
}
| const Model = require('../../database/models/model.js');
const Redis = require('../../database/redis/redis.js')
const axios = require('axios');
module.exports = {
getHistoricalData: (req, res) => {
Model.historicalGraphData.findOne({where: {currency: req.query[0]}})
.then(graph => {
const reformatted = graph.dataValues.data.map(x => {
const temp = [];
temp.push(Number(x[0]));
temp.push(Number(x[1]))
return temp;
})
res.send(reformatted);
})
},
getPredictionData: (req, res) => {
console.log(req.query)
Model.Prediction.findOne({where: {currency: req.query.currency}})
.then(response => {
res.send(response);
})
}
}
|
Fix hard coded site URL in @username mention | <?php
namespace Phosphorum\Markdown;
use Ciconia\Common\Text;
use Ciconia\Extension\ExtensionInterface;
use Ciconia\Markdown;
use Phalcon\DI\Injectable;
/**
* Class MentionExtension
*
* @package Phosphorum\Markdown
*/
class MentionExtension extends Injectable implements ExtensionInterface
{
/**
* {@inheritdoc}
*/
public function register(Markdown $markdown)
{
$markdown->on('inline', [$this, 'processMentions']);
}
/**
* @param Text $text
*/
public function processMentions(Text $text)
{
// Turn @username into [@username](http://example.com/user/username)
$text->replace('/(?:^|[^a-zA-Z0-9.])@([A-Za-z]+[A-Za-z0-9]+)/', function (Text $w, Text $username) {
return ' [@' . $username . '](' . $this->config->site->url . '/user/0/' . $username . ')';
});
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'mention';
}
}
| <?php
namespace Phosphorum\Markdown;
use Ciconia\Common\Text;
use Ciconia\Extension\ExtensionInterface;
use Ciconia\Markdown;
/**
* Class MentionExtension
*
* @package Phosphorum\Markdown
*/
class MentionExtension implements ExtensionInterface
{
/**
* {@inheritdoc}
*/
public function register(Markdown $markdown)
{
$markdown->on('inline', [$this, 'processMentions']);
}
/**
* @param Text $text
*/
public function processMentions(Text $text)
{
// Turn @username into [@username](http://example.com/user/username)
$text->replace('/(?:^|[^a-zA-Z0-9.])@([A-Za-z]+[A-Za-z0-9]+)/', function (Text $w, Text $username) {
return ' [@' . $username . '](http://forum.phalconphp.com/user/0/' . $username . ')';
});
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'mention';
}
}
|
Exclude tests from coverage reports | <?php
PHPUnit_Util_Filter::addDirectoryToFilter(__DIR__ . '/..');
//require_once(dirname(__FILE__) . '/importexport.php');
require_once 'PHPUnit/Framework.php';
require_once dirname(__FILE__) . '/../../src/jackalope/autoloader.php';
abstract class jackalope_baseSuite extends PHPUnit_Framework_TestSuite {
protected $path = '';
protected $configKeys = array('jcr.url', 'jcr.user', 'jcr.pass', 'jcr.workspace', 'jcr.transport');
public function setUp() {
parent::setUp();
$this->sharedFixture = array();
foreach ($this->configKeys as $cfgKey) {
$this->sharedFixture['config'][substr($cfgKey, 4)] = $GLOBALS[$cfgKey];
}
}
}
| <?php
//require_once(dirname(__FILE__) . '/importexport.php');
require_once 'PHPUnit/Framework.php';
require_once dirname(__FILE__) . '/../../src/jackalope/autoloader.php';
abstract class jackalope_baseSuite extends PHPUnit_Framework_TestSuite {
protected $path = '';
protected $configKeys = array('jcr.url', 'jcr.user', 'jcr.pass', 'jcr.workspace', 'jcr.transport');
public function setUp() {
parent::setUp();
$this->sharedFixture = array();
foreach ($this->configKeys as $cfgKey) {
$this->sharedFixture['config'][substr($cfgKey, 4)] = $GLOBALS[$cfgKey];
}
}
}
|
Use threaded_map to speed up refunds | #!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
from gratipay.billing.payday import threaded_map
import csv, os, requests
import threading
url = 'https://api.balancedpayments.com/debits/{}/refunds'
balanced_api_secret = os.environ['BALANCED_API_SECRET']
inp = csv.reader(open('refunds.csv'))
out = csv.writer(open('refunds.completed.csv', 'w+'))
writelock = threading.Lock()
def refund(row):
ts, id, amount, username, route_id = row
response = requests.post( url.format(id)
, data={'amount': amount}
, auth=(balanced_api_secret, '')
)
writelock.acquire()
try:
out.writerow((ts,id,amount,username,route_id,response.status_code,response.content))
finally:
writelock.release()
return
threaded_map(refund, inp)
| #!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv, os, requests
url = 'https://api.balancedpayments.com/debits/{}/refunds'
balanced_api_secret = os.environ['BALANCED_API_SECRET']
inp = csv.reader(open('refunds.csv'))
out = csv.writer(open('refunds.completed.csv', 'w+'))
for ts, id, amount, username, route_id in inp:
response = requests.post( url.format(id)
, data={'amount': amount}
, auth=(balanced_api_secret, '')
)
out.writerow((ts,id,amount,username,route_id,response.status_code,response.content))
|
Use connection string returned by PHP, to match mailbox name properly | <?php
namespace Ddeboer\Imap;
class Server
{
protected $hostname;
protected $port;
protected $connection;
protected $mailboxes;
public function __construct($hostname, $port = '993')
{
$this->server = '{' . $hostname . ':' . $port . '/imap}';
}
public function authenticate($username, $password)
{
$resource = @\imap_open($this->server, $username, $password, null, 1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));
$check = imap_check($resource);
$mailbox = $check->Mailbox;
$this->connection = substr($mailbox, 0, strpos($mailbox, '}')+1);
// These are necessary to get rid of PHP throwing IMAP errors
imap_errors();
imap_alerts();
return new Connection($resource, $this->connection);
}
} | <?php
namespace Ddeboer\Imap;
class Server
{
protected $hostname;
protected $port;
protected $connection;
protected $mailboxes;
public function __construct($hostname, $port = '993')
{
$this->server = '{' . $hostname . ':' . $port . '/imap}';
}
public function authenticate($username, $password)
{
$resource = @\imap_open($this->server, $username, $password, null, 1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));
// These are necessary to get rid of PHP throwing IMAP errors
imap_errors();
imap_alerts();
return new Connection($resource, $this->server);
}
} |
Fix 12PM/AM displaying as 00 | import React from 'react';
var Time = (props) => {
let time = props.time;
let hour = time.hour;
if (!props.hourFormat24 && time.pm) {
let pad = function (n) {
return (n < 10) ? `0${n}` : n.toString();
};
hour -= 12;
hour = pad(hour === 0 ? 12 : hour);
}
return (
<h1 className='colours__time'>
{hour} : {time.minute} : {time.second}
{!props.hourFormat24 && <span className='colours__time__postfix'>{time.pm ? 'PM' : 'AM'}</span>}
</h1>
);
}
export default Time;
| import React from 'react';
var Time = (props) => {
let time = props.time;
let hour = time.hour;
if (!props.hourFormat24 && time.pm) {
let pad = function (n) {
return (n < 10) ? `0${n}` : n.toString();
};
hour = pad(hour -= 12);
}
return (
<h1 className='colours__time'>
{hour} : {time.minute} : {time.second}
{!props.hourFormat24 && <span className='colours__time__postfix'>{time.pm ? 'PM' : 'AM'}</span>}
</h1>
);
}
export default Time;
|
Fix bug in prefilling IDE. | "use strict";
var ace = require('brace');
require('brace/theme/tomorrow');
require('brace/mode/javascript');
var React = require('react/addons');
var IdeComponent = React.createClass({
editor: null,
componentDidMount: function () {
this.editor = ace.edit(this.refs.ide.getDOMNode());
this.editor.setTheme('ace/theme/tomorrow');
var session = this.editor.getSession();
session.setMode('ace/mode/javascript');
session.setTabSize(2);
session.setUseSoftTabs(true);
session.on('change', this.onChange);
},
render: function () {
return <div ref='ide' className='ide'>{this.props.code}</div>;
},
onChange: function () {
this.props.onChange(this.editor.getValue());
}
});
module.exports = IdeComponent;
| "use strict";
var ace = require('brace');
require('brace/theme/tomorrow');
require('brace/mode/javascript');
var React = require('react/addons');
var IdeComponent = React.createClass({
editor: null,
componentDidMount: function () {
this.editor = ace.edit(this.refs.ide.getDOMNode());
this.editor.setTheme('ace/theme/tomorrow');
var session = this.editor.getSession();
session.setMode('ace/mode/javascript');
session.setTabSize(2);
session.setUseSoftTabs(true);
session.on('change', this.onChange);
},
componentDidUpdate: function () {
this.editor.setValue(this.props.code);
},
render: function () {
return (
<div ref='ide' className='ide'>
</div>
);
},
onChange: function () {
this.props.onChange(this.editor.getValue());
}
});
module.exports = IdeComponent;
|
Print the header at the right place. | package main
import (
"bsearch/index"
"bsearch/ops"
"fmt"
"os"
"flag"
)
func usage() {
fmt.Fprintf(os.Stderr, "usage: bsearch <path to index blob>\n")
flag.PrintDefaults()
os.Exit(1)
}
func main() {
flag.Parse()
if flag.NArg() != 1 {
usage()
}
dbname := flag.Arg(0)
in, err := index.Open(dbname)
if err != nil {
fmt.Fprintf(os.Stderr, "bindex.Open: %v\n", err)
return
}
defer in.Close()
a1 := ops.NewAttr(in, "root:10")
a2 := ops.NewAttr(in, "magic:boll")
a3 := ops.NewAttr(in, "status:active")
q := ops.NewIntersection(ops.NewUnion(a1, a2), a3)
q.Add(a3)
fmt.Printf("%v\n", in.Header())
var d *index.IbDoc
for true {
d = q.NextDoc(d)
if d == nil {
break
}
fmt.Printf("%v\n", string(in.Docs[d.Id]))
d = d.Inc()
}
}
| package main
import (
"bsearch/index"
"bsearch/ops"
"fmt"
"os"
"flag"
)
func usage() {
fmt.Fprintf(os.Stderr, "usage: bsearch <path to index blob>\n")
flag.PrintDefaults()
os.Exit(1)
}
func main() {
flag.Parse()
if flag.NArg() != 1 {
usage()
}
dbname := flag.Arg(0)
in, err := index.Open(dbname)
if err != nil {
fmt.Fprintf(os.Stderr, "bindex.Open: %v\n", err)
return
}
defer in.Close()
a1 := ops.NewAttr(in, "root:10")
a2 := ops.NewAttr(in, "magic:boll")
a3 := ops.NewAttr(in, "status:active")
q := ops.NewIntersection(ops.NewUnion(a1, a2), a3)
q.Add(a3)
var d *index.IbDoc
for true {
d = q.NextDoc(d)
if d == nil {
break
}
fmt.Printf("%v\n", string(in.Docs[d.Id]))
d = d.Inc()
}
}
|
Add a drop table for testing. | import os
from flask import Flask
import psycopg2
from urllib.parse import urlparse
url = urlparse(os.environ["DATABASE_URL"])
# Connect to a database
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
# Open a cursor to perform database operations
cur = conn.cursor()
# Drop table if it already exists
cur.execute("DROP TABLE test;")
# Create a table
cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
# Insert test data
cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (100, "abc'def"))
# Query the database and obtain data as Python objects
cur.execute("SELECT * FROM test;")
print(cur.fetchone())
# Make the changes to the database persistent
conn.commit()
# Close the cursor and the connection to the database
cur.close()
conn.close()
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello world!"
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
| import os
from flask import Flask
import psycopg2
from urllib.parse import urlparse
url = urlparse(os.environ["DATABASE_URL"])
# Connect to a database
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
# Open a cursor to perform database operations
cur = conn.cursor()
# Create a table
cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
# Insert test data
cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",(100, "abc'def"))
# Query the database and obtain data as Python objects
cur.execute("SELECT * FROM test;")
print(cur.fetchone())
# Make the changes to the database persistent
conn.commit()
# Close the cursor and the connection to the database
cur.close()
conn.close()
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello world!"
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
|
Add language href to link | <?php
/**
* Class LanguageLink | LanguageLink.php
* @package Faulancer\View\Helper
* @author Florian Knapp <office@florianknapp.de>
*/
namespace Faulancer\View\Helper;
use Faulancer\Service\Config;
use Faulancer\View\AbstractViewHelper;
/**
* Class LanguageLink
*/
class LanguageLink extends AbstractViewHelper
{
protected $languageTextMapping = [
'de' => 'Deutsch',
'en' => 'English',
'hr' => 'Hrvatski'
];
public function __invoke()
{
/** @var Config $config */
$config = $this->getServiceLocator()->get(Config::class);
$translations = $config->get('translation');
$result = [];
$pattern = '<a rel="alternate" hreflang="%s" class="lang %s" href="?lang=%s">%s</a>';
foreach ($translations as $key => $content) {
$result[] = sprintf($pattern, strtolower($key), strtolower($key), $key, $this->languageTextMapping[$key]);
}
return implode('', $result);
}
} | <?php
/**
* Class LanguageLink | LanguageLink.php
* @package Faulancer\View\Helper
* @author Florian Knapp <office@florianknapp.de>
*/
namespace Faulancer\View\Helper;
use Faulancer\Service\Config;
use Faulancer\View\AbstractViewHelper;
/**
* Class LanguageLink
*/
class LanguageLink extends AbstractViewHelper
{
protected $languageTextMapping = [
'de' => 'Deutsch',
'gb' => 'English',
'hr' => 'Hrvatski'
];
public function __invoke()
{
/** @var Config $config */
$config = $this->getServiceLocator()->get(Config::class);
$translations = $config->get('translation');
$result = [];
$pattern = '<a class="lang %s" href="?lang=%s">%s</a>';
foreach ($translations as $key => $content) {
$result[] = sprintf($pattern, strtolower($key), $key, $this->languageTextMapping[$key]);
}
return implode('', $result);
}
} |
Add correct flag to render different layout. | import React, { PropTypes } from 'react';
import { tile as tileConstants } from './constants';
const styles = {
wrapper: {
width: tileConstants.width,
height: tileConstants.height,
border: '1px solid #FFD1AA',
position: 'absolute',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
cursor: 'pointer',
},
number: {
color: '#FFD1AA',
fontSize: 22,
},
};
const Tile = ({ number, left, top, onClick, correct }) => {
const compStyles = Object.assign({}, styles.wrapper, {
left,
top,
backgroundColor: correct ? '#226666' : '#D4726A',
});
return (
<div style={compStyles} onClick={onClick}>
<span style={styles.number}>{number}</span>
</div>
);
};
Tile.propTypes = {
number: PropTypes.number,
left: PropTypes.number.isRequired,
top: PropTypes.number.isRequired,
onClick: PropTypes.func.isRequired,
correct: PropTypes.bool.isRequired,
};
Tile.defaultProps = {
number: 0,
correct: false,
};
export default Tile;
| import React, { PropTypes } from 'react';
import { tile as tileConstants } from './constants';
const styles = {
wrapper: {
width: tileConstants.width,
height: tileConstants.height,
border: '1px solid #FFD1AA',
backgroundColor: '#226666',
position: 'absolute',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
cursor: 'pointer',
},
number: {
color: '#FFD1AA',
fontSize: 22,
},
};
const Tile = ({ number, left, top, onClick }) => {
const compStyles = Object.assign({}, styles.wrapper, {
left,
top,
});
return (
<div style={compStyles} onClick={onClick}>
<span style={styles.number}>{number}</span>
</div>
);
};
Tile.propTypes = {
number: PropTypes.number,
left: PropTypes.number.isRequired,
top: PropTypes.number.isRequired,
onClick: PropTypes.func.isRequired,
};
Tile.defaultProps = {
number: 0,
};
export default Tile;
|
Fix invalid ref, improve error message | /** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var patches = require('./patches');
var clone = require('./clone');
var InvalidPatchOperationError = require('./InvalidPatchOperationError');
exports.apply = patch;
exports.applyInPlace = patchInPlace;
exports.clone = clone;
/**
* Apply the supplied JSON Patch to x
* @param {array} changes JSON Patch
* @param {object|array|string|number} x object/array/value to patch
* @returns {object|array|string|number} patched version of x. If x is
* an array or object, it will be mutated and returned. Otherwise, if
* x is a value, the new value will be returned.
*/
function patch(changes, x) {
return patchInPlace(changes, clone(x));
}
function patchInPlace(changes, x) {
// TODO: Consider throwing if changes is not an array
if(!Array.isArray(changes)) {
return x;
}
var patch, p;
for(var i=0; i<changes.length; ++i) {
p = changes[i];
patch = patches[p.op];
if(patch === void 0) {
throw new InvalidPatchOperationError('invalid op ' + p);
}
x = patch.apply(x, p);
}
return x;
}
| /** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var patches = require('./patches');
var clone = require('./clone');
var InvalidPatchOperationError = require('./InvalidPatchOperationError');
exports.apply = patch;
exports.applyInPlace = patchInPlace;
exports.clone = clone;
/**
* Apply the supplied JSON Patch to x
* @param {array} changes JSON Patch
* @param {object|array|string|number} x object/array/value to patch
* @returns {object|array|string|number} patched version of x. If x is
* an array or object, it will be mutated and returned. Otherwise, if
* x is a value, the new value will be returned.
*/
function patch(changes, x) {
return patchInPlace(changes, clone(x));
}
function patchInPlace(changes, x) {
// TODO: Consider throwing if changes is not an array
if(!Array.isArray(changes)) {
return x;
}
var patch, p;
for(var i=0; i<changes.length; ++i) {
p = changes[i];
patch = patches[p.op];
if(patch === void 0) {
throw new InvalidPatchOperationError('invalid op ' + change.op);
}
x = patch.apply(x, p);
}
return x;
}
|
Use normal exports here, not messing with the modules.exports | /*
* Licensed to Cloudkick, Inc ('Cloudkick') under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Cloudkick 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.
*/
exports.create_service = require('deployment/services').create_service;
exports.get_available_instances = require('deployment/instances').get_available_instances;
exports.realize_application_templates = require('deployment/templates').realize_application_templates;
| /*
* Licensed to Cloudkick, Inc ('Cloudkick') under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Cloudkick 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.
*/
module.exports = {
create_service: require('deployment/services').create_service,
get_available_instances: require('deployment/instances').get_available_instances,
realize_application_templates: require('deployment/templates').realize_application_templates
};
|
fix(envify): Apply envify globally so that local react files get processed by it. | const babelify = require('babelify')
const envify = require('envify/custom')
const markdown = require('browserify-markdown')
const through = require('through2')
const YAML = require('yamljs')
const babelConfig = require('./babel-config')
const util = require('./util')
module.exports = function transform ({
config,
env
}) {
util.configureEnvironment({config, env})
return [
htmlTransform,
markdown({
html: true
}),
yamlTransform,
babelify.configure(babelConfig(env)),
[envify(process.env), {global: true}] // Envify needs to happen last...
]
}
function htmlTransform (filename) {
if (!/\.html$/i.test(filename)) {
return through()
}
return through(function (buf, enc, next) {
this.push('module.exports=' + JSON.stringify(buf.toString('utf8')))
next()
})
}
function yamlTransform (filename) {
if (!/\.yml|\.yaml$/i.test(filename)) {
return through()
}
return through(function (buf, enc, next) {
this.push('module.exports=' + JSON.stringify(YAML.parse(buf.toString('utf8'))))
next()
})
}
| const babelify = require('babelify')
const envify = require('envify/custom')
const markdown = require('browserify-markdown')
const through = require('through2')
const YAML = require('yamljs')
const babelConfig = require('./babel-config')
const util = require('./util')
module.exports = function transform ({
config,
env
}) {
util.configureEnvironment({config, env})
return [
htmlTransform,
markdown({
html: true
}),
yamlTransform,
babelify.configure(babelConfig(env)),
envify(process.env) // Envify needs to happen last...
]
}
function htmlTransform (filename) {
if (!/\.html$/i.test(filename)) {
return through()
}
return through(function (buf, enc, next) {
this.push('module.exports=' + JSON.stringify(buf.toString('utf8')))
next()
})
}
function yamlTransform (filename) {
if (!/\.yml|\.yaml$/i.test(filename)) {
return through()
}
return through(function (buf, enc, next) {
this.push('module.exports=' + JSON.stringify(YAML.parse(buf.toString('utf8'))))
next()
})
}
|
Fix non-chanops not being able to query the topic | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class TopicLockMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "TopicLockMode"
core = True
affectedActions = { "commandpermission-TOPIC": 10 }
def channelModes(self):
return [ ("t", ModeType.NoParam, self) ]
def actions(self):
return [ ("modeactioncheck-channel-t-commandpermission-TOPIC", 10, self.channelHasMode) ]
def channelHasMode(self, channel, user, data):
if "t" in channel.modes:
return ""
return None
def apply(self, actionType, channel, param, user, data):
if "topic" not in data:
return None
if not self.ircd.runActionUntilValue("checkchannellevel", "topic", channel, user):
user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, channel.name, "You do not have access to change the topic on this channel")
return False
return None
topicLockMode = TopicLockMode() | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class TopicLockMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "TopicLockMode"
core = True
affectedActions = { "commandpermission-TOPIC": 10 }
def channelModes(self):
return [ ("t", ModeType.NoParam, self) ]
def actions(self):
return [ ("modeactioncheck-channel-t-commandpermission-TOPIC", 10, self.channelHasMode) ]
def channelHasMode(self, channel, user, data):
if "t" in channel.modes:
return ""
return None
def apply(self, actionType, channel, param, user, data):
if not self.ircd.runActionUntilValue("checkchannellevel", "topic", channel, user):
user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, channel.name, "You do not have access to change the topic on this channel")
return False
return None
topicLockMode = TopicLockMode() |
[core] GraphQL: Remove special handling of 404 in graphql list command | module.exports = async function listApisAction(args, context) {
const {apiClient, output, chalk} = context
const client = apiClient({
requireUser: true,
requireProject: true
})
let endpoints
try {
endpoints = await client.request({
url: `/apis/graphql`,
method: 'GET'
})
} catch (err) {
throw err
}
if (endpoints && endpoints.length > 0) {
output.print('Here are the GraphQL endpoints deployed for this project:')
endpoints.forEach((endpoint, index) => {
output.print(`${index + 1}. ${chalk.bold('Dataset:')} ${endpoint.dataset}`)
output.print(` ${chalk.bold('Tag:')} ${endpoint.tag}`)
output.print(` ${chalk.bold('Generation:')} ${endpoint.generation}`)
output.print(` ${chalk.bold('Playground:')} ${endpoint.playgroundEnabled}\n`)
})
} else {
output.print("This project doesn't have any GraphQL endpoints deployed.")
}
}
| module.exports = async function listApisAction(args, context) {
const {apiClient, output, chalk} = context
const client = apiClient({
requireUser: true,
requireProject: true
})
let endpoints
try {
endpoints = await client.request({
url: `/apis/graphql`,
method: 'GET'
})
} catch (err) {
if (err.statusCode === 404) {
endpoints = []
} else {
throw err
}
}
if (endpoints && endpoints.length > 0) {
output.print('Here are the GraphQL endpoints deployed for this project:')
endpoints.forEach((endpoint, index) => {
output.print(`${index + 1}. ${chalk.bold('Dataset:')} ${endpoint.dataset}`)
output.print(` ${chalk.bold('Tag:')} ${endpoint.tag}`)
output.print(` ${chalk.bold('Generation:')} ${endpoint.generation}`)
output.print(` ${chalk.bold('Playground:')} ${endpoint.playgroundEnabled}\n`)
})
} else {
output.print("This project doesn't have any GraphQL endpoints deployed.")
}
}
|
Fix snippet URL rules to use mountpoints' endpoint suffix | """
byceps.blueprints.snippet.init
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from flask import current_app
from ...services.snippet import mountpoint_service
from .views import blueprint as snippet_blueprint, view_current_version_by_name
def add_routes_for_snippets(site_id):
"""Register routes for snippets with the application."""
mountpoints = mountpoint_service.get_mountpoints_for_site(site_id)
for mountpoint in mountpoints:
add_route_for_snippet(mountpoint)
def add_route_for_snippet(mountpoint):
"""Register a route for the snippet."""
endpoint = '{}.{}'.format(snippet_blueprint.name,
mountpoint.endpoint_suffix)
defaults = {'name': mountpoint.endpoint_suffix}
current_app.add_url_rule(
mountpoint.url_path,
endpoint,
view_func=view_current_version_by_name,
defaults=defaults)
| """
byceps.blueprints.snippet.init
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from flask import current_app
from ...services.snippet import mountpoint_service
from .views import blueprint as snippet_blueprint, view_current_version_by_name
def add_routes_for_snippets(site_id):
"""Register routes for snippets with the application."""
mountpoints = mountpoint_service.get_mountpoints_for_site(site_id)
for mountpoint in mountpoints:
add_route_for_snippet(mountpoint)
def add_route_for_snippet(mountpoint):
"""Register a route for the snippet."""
endpoint = '{}.{}'.format(snippet_blueprint.name,
mountpoint.endpoint_suffix)
defaults = {'name': mountpoint.snippet.name}
current_app.add_url_rule(
mountpoint.url_path,
endpoint,
view_func=view_current_version_by_name,
defaults=defaults)
|
Add initial default plugin options | /*
* grunt-xcode
* https://github.com/matiassingers/grunt-xcode
*
* Copyright (c) 2014 Matias Singers
* Licensed under the MIT license.
*/
'use strict';
var Promise = require('bluebird');
var exec = Promise.promisify(require('child_process').exec);
String.prototype.format = function() {
var formatted = this;
for (var i = 0; i < arguments.length; i++) {
formatted = formatted.replace(
RegExp('\\{' + i + '\\}', 'g'), arguments[i]);
}
return formatted;
};
module.exports = function(grunt) {
function executeCommand(command){
grunt.verbose.writeln('Running command: {0}'.format(command));
return exec(command)
.catch(handleCommandError);
}
function handleCommandError(error){
if (error){
grunt.warn(error);
}
}
grunt.registerMultiTask('xcode', 'Build and export Xcode projects with Grunt', function() {
var done = this.async();
var options = this.options({
clean: true,
export: true,
project: '',
scheme: '',
archivePath: '',
exportPath: process.cwd(),
exportFilename: 'export.ipa'
});
if(!options.project){
throw new Error('`options.project` is required');
}
});
};
| /*
* grunt-xcode
* https://github.com/matiassingers/grunt-xcode
*
* Copyright (c) 2014 Matias Singers
* Licensed under the MIT license.
*/
'use strict';
var Promise = require('bluebird');
var exec = Promise.promisify(require('child_process').exec);
String.prototype.format = function() {
var formatted = this;
for (var i = 0; i < arguments.length; i++) {
formatted = formatted.replace(
RegExp('\\{' + i + '\\}', 'g'), arguments[i]);
}
return formatted;
};
module.exports = function(grunt) {
function executeCommand(command){
grunt.verbose.writeln('Running command: {0}'.format(command));
return exec(command)
.catch(handleCommandError);
}
function handleCommandError(error){
if (error){
grunt.warn(error);
}
}
grunt.registerMultiTask('xcode', 'Build and export Xcode projects with Grunt', function() {
var done = this.async();
});
};
|
Add socket check to avoid uninstantiated error | import config from '../config';
import createQueryString from './createQueryString';
import WebSocketClient from 'websocket.js';
let socket;
export function sendMessage(type, payload) {
if (socket) {
if (socket.ws.readyState === 0) {
socket.onopen = () => {
socket.send(`${type}:${payload}`);
};
} else if (socket.ws.readyState === 1) {
socket.send(`${type}:${payload}`);
}
}
}
export function connectWebsockets(dispatch, jwt) {
const qs = createQueryString({ jwt });
if (socket) socket.close();
socket = new WebSocketClient(`${config.wsServerUrl}/${qs}`);
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
dispatch({
type: data.type,
payload: data.payload
});
};
}
| import config from '../config';
import createQueryString from './createQueryString';
import WebSocketClient from 'websocket.js';
let socket;
export function sendMessage(type, payload) {
if (socket.ws.readyState === 0) {
socket.onopen = () => {
socket.send(`${type}:${payload}`);
};
} else if (socket.ws.readyState === 1) {
socket.send(`${type}:${payload}`);
}
}
export function connectWebsockets(dispatch, jwt) {
const qs = createQueryString({ jwt });
if (socket) socket.close();
socket = new WebSocketClient(`${config.wsServerUrl}/${qs}`);
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
dispatch({
type: data.type,
payload: data.payload
});
};
}
|
Add Repository.triggers backref to look up Triggers | from __future__ import unicode_literals
from django.db import models
TRIGGER_TYPES = (
('manual', 'Manual'),
('commit', 'Commit'),
('tag', 'Tag'),
('pr', 'Pull Request'),
)
class Trigger(models.Model):
name = models.CharField(max_length=255)
repo = models.ForeignKey('github.Repository', related_name="triggers")
type = models.CharField(max_length=8, choices=TRIGGER_TYPES)
regex = models.CharField(max_length=255, null=True, blank=True)
build_pr_commits = models.BooleanField(default=False)
flows = models.CharField(max_length=255)
org = models.CharField(max_length=255)
context = models.CharField(max_length=255)
def __unicode__(self):
return unicode(self.name)
def check_push(self, push):
return True
def check_pull_request(self, pull_request):
return True
| from __future__ import unicode_literals
from django.db import models
TRIGGER_TYPES = (
('manual', 'Manual'),
('commit', 'Commit'),
('tag', 'Tag'),
('pr', 'Pull Request'),
)
class Trigger(models.Model):
name = models.CharField(max_length=255)
repo = models.ForeignKey('github.Repository')
type = models.CharField(max_length=8, choices=TRIGGER_TYPES)
regex = models.CharField(max_length=255, null=True, blank=True)
build_pr_commits = models.BooleanField(default=False)
flows = models.CharField(max_length=255)
org = models.CharField(max_length=255)
context = models.CharField(max_length=255)
def __unicode__(self):
return unicode(self.name)
def check_push(self, push):
return True
def check_pull_request(self, pull_request):
return True
|
Exclude 'Intl' from new-cap exception | module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
extends: 'airbnb-base',
// required to lint *.vue files
plugins: [
'html'
],
// check if imports actually resolve
'settings': {
'import/resolver': {
'webpack': {
'config': 'build/webpack.base.conf.js'
}
}
},
// add your custom rules here
'rules': {
// don't require .vue extension when importing
'import/extensions': ['error', 'always', {
'js': 'never',
'vue': 'never'
}],
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
'no-console': 0,
'no-alert': 0,
'no-shadow': 0,
'no-param-reassign': 0,
'new-cap': [ 0, {
"capIsNewExceptions": [ "Intl" ]
}],
}
}
| module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
extends: 'airbnb-base',
// required to lint *.vue files
plugins: [
'html'
],
// check if imports actually resolve
'settings': {
'import/resolver': {
'webpack': {
'config': 'build/webpack.base.conf.js'
}
}
},
// add your custom rules here
'rules': {
// don't require .vue extension when importing
'import/extensions': ['error', 'always', {
'js': 'never',
'vue': 'never'
}],
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
'no-console': 0,
'no-alert': 0,
'no-shadow': 0,
'no-param-reassign': 0
}
}
|
Use existing method to create an AddFileInterface | // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.filedistribution;
import com.google.inject.Inject;
import com.yahoo.cloud.config.ConfigserverConfig;
import com.yahoo.config.application.api.FileRegistry;
import com.yahoo.config.model.api.FileDistribution;
import com.yahoo.jrt.Supervisor;
import com.yahoo.jrt.Transport;
import com.yahoo.vespa.defaults.Defaults;
import java.io.File;
/**
* Factory for creating providers that are used to interact with file distribution.
*
* @author Ulf Lilleengen
*/
@SuppressWarnings("WeakerAccess")
public class FileDistributionFactory {
protected final ConfigserverConfig configserverConfig;
private final Supervisor supervisor = new Supervisor(new Transport("filedistribution"));
@Inject
public FileDistributionFactory(ConfigserverConfig configserverConfig) {
this.configserverConfig = configserverConfig;
}
public FileRegistry createFileRegistry(File applicationPackage) {
return new FileDBRegistry(createFileManager(applicationPackage));
}
public FileDistribution createFileDistribution() {
return new FileDistributionImpl(getFileReferencesDir(), supervisor);
}
public AddFileInterface createFileManager(File applicationDir) {
return new ApplicationFileManager(applicationDir, new FileDirectory(getFileReferencesDir()));
}
protected File getFileReferencesDir() {
return new File(Defaults.getDefaults().underVespaHome(configserverConfig.fileReferencesDir()));
}
}
| // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.filedistribution;
import com.google.inject.Inject;
import com.yahoo.cloud.config.ConfigserverConfig;
import com.yahoo.config.application.api.FileRegistry;
import com.yahoo.config.model.api.FileDistribution;
import com.yahoo.jrt.Supervisor;
import com.yahoo.jrt.Transport;
import com.yahoo.vespa.defaults.Defaults;
import java.io.File;
/**
* Factory for creating providers that are used to interact with file distribution.
*
* @author Ulf Lilleengen
*/
@SuppressWarnings("WeakerAccess")
public class FileDistributionFactory {
protected final ConfigserverConfig configserverConfig;
private final Supervisor supervisor = new Supervisor(new Transport("filedistribution"));
@Inject
public FileDistributionFactory(ConfigserverConfig configserverConfig) {
this.configserverConfig = configserverConfig;
}
public FileRegistry createFileRegistry(File applicationPackage) {
return new FileDBRegistry(new ApplicationFileManager(applicationPackage, new FileDirectory(getFileReferencesDir())));
}
public FileDistribution createFileDistribution() {
return new FileDistributionImpl(getFileReferencesDir(), supervisor);
}
public AddFileInterface createFileManager(File applicationDir) {
return new ApplicationFileManager(applicationDir, new FileDirectory(getFileReferencesDir()));
}
protected File getFileReferencesDir() {
return new File(Defaults.getDefaults().underVespaHome(configserverConfig.fileReferencesDir()));
}
}
|
Reorder source and author links | import React, { Component, PropTypes } from 'react'
import { Link } from 'react-router'
import 'normalize.css/normalize.css'
import '../styles/defaults.scss'
import classNames from './App.scss'
import { trackTiming } from '../analytics'
import { APP_NAME, AUTHOR_URL, SOURCE_URL, SEPARATOR } from '../config'
export default class App extends Component {
static propTypes = {
children: PropTypes.node
};
componentDidMount () {
if (window.performance) {
trackTiming('react', 'firstrender', Math.round(window.performance.now()))
}
}
render () {
return (
<div className={classNames.app}>
<header className={classNames.header}>
<h1 className={classNames.title}>
<Link to='/'>
{APP_NAME}
</Link>
</h1>
{SEPARATOR}
by <a href={AUTHOR_URL} target='_blank'>CookPete</a>
{SEPARATOR}
<a href={SOURCE_URL} target='_blank'>Source</a>
</header>
{ this.props.children }
</div>
)
}
}
| import React, { Component, PropTypes } from 'react'
import { Link } from 'react-router'
import 'normalize.css/normalize.css'
import '../styles/defaults.scss'
import classNames from './App.scss'
import { trackTiming } from '../analytics'
import { APP_NAME, AUTHOR_URL, SOURCE_URL, SEPARATOR } from '../config'
export default class App extends Component {
static propTypes = {
children: PropTypes.node
};
componentDidMount () {
if (window.performance) {
trackTiming('react', 'firstrender', Math.round(window.performance.now()))
}
}
render () {
return (
<div className={classNames.app}>
<header className={classNames.header}>
<h1 className={classNames.title}>
<Link to='/'>
{APP_NAME}
</Link>
</h1>
{SEPARATOR}
<a href={SOURCE_URL} target='_blank'>Source</a>
{SEPARATOR}
by <a href={AUTHOR_URL} target='_blank'>CookPete</a>
</header>
{ this.props.children }
</div>
)
}
}
|
Add warning for unimplemented adapter methods | var get = Ember.get;
DS.Serializer = Ember.Object.extend({
toJSON: function(record, options) {
options = options || {};
var hash = {};
this.addAttributes(hash, record);
if (options.includeId) {
this.addId(hash, record);
}
this.addRelationships(hash, record);
return hash;
},
addAttributes: function(hash, record) {
record.eachAttribute(function(name, attribute) {
var attributeName = this.attributeName(attribute, record);
var value = get(record, attribute.name);
hash[attributeName] = this.transform(value, attribute);
}, this);
},
attributeName: function(attribute, record) {
return attribute.name;
},
transform: function(value, attribute) {
return value;
},
addRelationships: function(hash, record) {
record.eachAssociation(function(name, relationship) {
if (relationship.kind === 'belongsTo') {
this.addBelongsTo(hash, record, relationship);
} else if (relationship.kind === 'hasMany') {
this.addHasMany(hash, record, relationship);
}
}, this);
},
addBelongsTo: function() {
Ember.assert("Serializers must implement addBelongsTo", false);
},
addHasMany: function() {
Ember.assert("Serializers must implement addHasMany", false);
},
addId: function(hash, record) {
var primaryKey = this.primaryKey(record);
hash[primaryKey] = get(record, 'id');
}
});
| var get = Ember.get;
DS.Serializer = Ember.Object.extend({
toJSON: function(record, options) {
options = options || {};
var hash = {};
this.addAttributes(hash, record);
if (options.includeId) {
this.addId(hash, record);
}
this.addRelationships(hash, record);
return hash;
},
addAttributes: function(hash, record) {
record.eachAttribute(function(name, attribute) {
var attributeName = this.attributeName(attribute, record);
var value = get(record, attribute.name);
hash[attributeName] = this.transform(value, attribute);
}, this);
},
attributeName: function(attribute, record) {
return attribute.name;
},
transform: function(value, attribute) {
return value;
},
addRelationships: function(hash, record) {
record.eachAssociation(function(name, relationship) {
if (relationship.kind === 'belongsTo') {
this.addBelongsTo(hash, record, relationship);
} else if (relationship.kind === 'hasMany') {
this.addHasMany(hash, record, relationship);
}
}, this);
},
addBelongsTo: function() {
},
addHasMany: function() {
},
addId: function(hash, record) {
var primaryKey = this.primaryKey(record);
hash[primaryKey] = get(record, 'id');
}
});
|
Rename object to entity in interface. | /*
* Copyright 2019 Google LLC. 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.
*
* Any software provided by Google hereunder is distributed “AS IS”,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, and is not intended for production use.
*
*/
package com.google.gcs.sdrs.dao;
import java.io.Serializable;
/**
* Interface for Data Access Object pattern
*
* @author salguerod
*
* @param <T>
* @param <Id>
*/
public interface Dao<T, Id extends Serializable> {
Id save(T entity);
void update(T entity);
T findById(Id id);
void delete(T entity);
}
| /*
* Copyright 2019 Google LLC. 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.
*
* Any software provided by Google hereunder is distributed “AS IS”,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, and is not intended for production use.
*
*/
package com.google.gcs.sdrs.dao;
import java.io.Serializable;
/**
* Interface for Data Access Object pattern
*
* @author salguerod
*
* @param <T>
* @param <Id>
*/
public interface Dao<T, Id extends Serializable> {
Id save(T entity);
void update(T object);
T findById(Id id);
void delete(T object);
}
|
Replace parsing with Python's ast
Allows greater flexibility and syntax checks | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
import ast
from ..semantics import mpq
from .common import OPERATORS, ADD_OP, MULTIPLY_OP
def try_to_number(s):
try:
return mpq(s)
except (ValueError, TypeError):
return s
OPERATOR_MAP = {
ast.Add: ADD_OP,
ast.Mult: MULTIPLY_OP,
}
def parse(s):
from .biop import Expr
def _parse_r(t):
try:
return t.n
except AttributeError:
pass
try:
return t.id
except AttributeError:
op = OPERATOR_MAP[t.op.__class__]
a1 = _parse_r(t.left)
a2 = _parse_r(t.right)
return Expr(op, a1, a2)
return _parse_r(ast.parse(s, mode='eval').body)
| #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from ..semantics import mpq
from .common import OPERATORS, ADD_OP, MULTIPLY_OP
def try_to_number(s):
try:
return mpq(s)
except (ValueError, TypeError):
return s
def _parse_r(s):
s = s.strip()
bracket_level = 0
operator_pos = -1
for i, v in enumerate(s):
if v == '(':
bracket_level += 1
if v == ')':
bracket_level -= 1
if bracket_level == 1 and v in OPERATORS:
operator_pos = i
break
if operator_pos == -1:
return s
a1 = _parse_r(s[1:operator_pos].strip())
a2 = _parse_r(s[operator_pos + 1:-1].strip())
return Expr(s[operator_pos], a1, a2)
|
Correct logic for is isCategoryNameValidForCategory()
Long.equals(Long) isn't equals to (Long == Long)?
OPEN - task 54: Create Category CRUD packages
http://github.com/DevOpsDistilled/OpERP/issues/issue/54 | package devopsdistilled.operp.server.data.service.items.impl;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import devopsdistilled.operp.server.data.entity.items.Category;
import devopsdistilled.operp.server.data.repo.items.CategoryRepository;
import devopsdistilled.operp.server.data.service.impl.AbstractEntityService;
import devopsdistilled.operp.server.data.service.items.CategoryService;
@Service
public class CategoryServiceImpl extends
AbstractEntityService<Category, Long, CategoryRepository> implements
CategoryService {
private static final long serialVersionUID = 7024824459392415034L;
@Inject
private CategoryRepository repo;
@Override
protected CategoryRepository getRepo() {
return repo;
}
@Override
public boolean isCategoryNameExists(String categoryName) {
Category category = repo.findByCategoryName(categoryName);
if (category != null)
return true;
return false;
}
@Override
public boolean isCategoryNameValidForCategory(Long categoryId,
String categoryName) {
Category category = repo.findByCategoryName(categoryName);
if (category == null)
return true;
if (category.getCategoryId().equals(categoryId))
return true;
return false;
}
}
| package devopsdistilled.operp.server.data.service.items.impl;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import devopsdistilled.operp.server.data.entity.items.Category;
import devopsdistilled.operp.server.data.repo.items.CategoryRepository;
import devopsdistilled.operp.server.data.service.impl.AbstractEntityService;
import devopsdistilled.operp.server.data.service.items.CategoryService;
@Service
public class CategoryServiceImpl extends
AbstractEntityService<Category, Long, CategoryRepository> implements
CategoryService {
private static final long serialVersionUID = 7024824459392415034L;
@Inject
private CategoryRepository repo;
@Override
protected CategoryRepository getRepo() {
return repo;
}
@Override
public boolean isCategoryNameExists(String categoryName) {
Category category = repo.findByCategoryName(categoryName);
if (category != null)
return true;
return false;
}
@Override
public boolean isCategoryNameValidForCategory(Long categoryId,
String categoryName) {
Category category = repo.findByCategoryName(categoryName);
if (category == null)
return true;
if (category.getCategoryId() != categoryId)
return false;
return true;
}
}
|
Add json reader/writer for websocket connection | package websocket
import(
"net/http"
"log"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type WebSocketHandler struct {}
type Data struct {
Id int `json:"id"`
Test interface{} `json:"test"`
}
func NewWebSocketHandler() *WebSocketHandler {
return &WebSocketHandler{}
}
func (handler *WebSocketHandler) ServeHTTP(
responseWriter http.ResponseWriter,
request *http.Request,
) {
connection, err := upgrader.Upgrade(responseWriter, request, nil)
if err != nil {
log.Println(err.Error())
return
}
defer connection.Close()
data := Data{}
for {
err := connection.ReadJSON(&data)
if err != nil {
log.Println("read: ", err.Error())
break
}
log.Printf("recv: ", data)
err = connection.WriteJSON(data)
if err != nil {
log.Println("write: ", err.Error())
break
}
}
}
| package websocket
import(
"net/http"
"log"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type WebSocketHandler struct {}
func NewWebSocketHandler() *WebSocketHandler {
return &WebSocketHandler{}
}
func (handler *WebSocketHandler) ServeHTTP(
responseWriter http.ResponseWriter,
request *http.Request,
) {
connection, err := upgrader.Upgrade(responseWriter, request, nil)
if err != nil {
log.Println(err.Error())
return
}
defer connection.Close()
for {
messageType, message, err := connection.ReadMessage()
if err != nil {
log.Println("read: ", err.Error())
break
}
log.Printf("recv: %s", message)
err = connection.WriteMessage(messageType, message)
if err != nil {
log.Println("write: ", err)
break
}
}
}
|
Fix to count 0 on empty files and (amount of line-breaks + 1) on non-empty files | package bogush;
import java.io.*;
import java.nio.file.Path;
class LineCounter {
static int count(Path file) throws IOException {
try (InputStream is = new BufferedInputStream(new FileInputStream(file.toFile()))) {
boolean empty = true;
byte bytes[] = new byte[1024];
int readChars;
int count = 1;
while ((readChars = is.read(bytes)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (bytes[i] == '\n') {
++count;
}
}
}
if (empty) {
return 0;
} else {
return count;
}
}
}
}
| package bogush;
import java.io.*;
import java.nio.file.Path;
class LineCounter {
static int count(Path file) throws IOException {
try (InputStream is = new BufferedInputStream(new FileInputStream(file.toFile()))) {
boolean empty = true;
byte bytes[] = new byte[1024];
int readChars;
int count = 0;
while ((readChars = is.read(bytes)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (bytes[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
}
}
}
|
Fix typo on last commit | <?php
namespace RocketTheme\Toolbox\ArrayTraits;
/**
* Implements getters and setters.
*
* @package RocketTheme\Toolbox\ArrayTraits
* @author RocketTheme
* @license MIT
*/
trait NestedArrayAccessWithGetters
{
use NestedArrayAccess;
/**
* Magic setter method
*
* @param mixed $offset Asset name value
* @param mixed $value Asset value
*/
public function __set($offset, $value)
{
$this->offsetSet($offset, $value);
}
/**
* Magic getter method
*
* @param mixed $offset Asset name value
* @return mixed Asset value
*/
public function __get($offset)
{
return $this->offsetGet($offset);
}
/**
* Magic method to determine if the attribute is set
*
* @param mixed $offset Asset name value
* @return boolean True if the value is set
*/
public function __isset($offset)
{
return $this->offsetExists($offset);
}
/**
* Magic method to unset the attribute
*
* @param mixed $offset The name value to unset
*/
public function __unset($offset)
{
$this->offsetUnset($offset);
}
}
| <?php
namespace RocketTheme\Toolbox\ArrayTraits;
/**
* Implements getters and setters.
*
* @package RocketTheme\Toolbox\ArrayTraits
* @author RocketTheme
* @license MIT
*/
trait Getters
{
use NestedArrayAccess;
/**
* Magic setter method
*
* @param mixed $offset Asset name value
* @param mixed $value Asset value
*/
public function __set($offset, $value)
{
$this->offsetSet($offset, $value);
}
/**
* Magic getter method
*
* @param mixed $offset Asset name value
* @return mixed Asset value
*/
public function __get($offset)
{
return $this->offsetGet($offset);
}
/**
* Magic method to determine if the attribute is set
*
* @param mixed $offset Asset name value
* @return boolean True if the value is set
*/
public function __isset($offset)
{
return $this->offsetExists($offset);
}
/**
* Magic method to unset the attribute
*
* @param mixed $offset The name value to unset
*/
public function __unset($offset)
{
$this->offsetUnset($offset);
}
}
|
Update icat API functions to new location. Fix made by someone else. | <?php
require_once 'icat.php';
?>
<!doctype html>
<html>
<head>
<title>Scoreboard</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" type="text/css" href="katalyze/css/katalyze.css" />
<meta charset="utf-8">
<style type="text/css">
h1 { text-align: center; margin: 0; }
</style>
<script type="text/javascript" src="katalyze/web/jquery-1.6.1.js"></script>
<script type="text/javascript" src="feed.js"></script>
<script type="text/javascript" src="misc.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<?php navigation_container() ?>
<h1>Scoreboard</h1>
<!--<div class='teamscore' data-source='http://<?php echo $_SERVER['SERVER_ADDR']; ?>:8099' data-filter="">(Katalyzer must be running for this to work)</div>-->
<div class='teamscore' data-source='/icat/api' data-filter="">(Katalyzer must be running for this to work)</div>
<script type='text/javascript' src='katalyze/web/scores.js'></script>
</body>
</html>
| <?php
require_once 'icat.php';
?>
<!doctype html>
<html>
<head>
<title>Scoreboard</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" type="text/css" href="katalyze/css/katalyze.css" />
<meta charset="utf-8">
<style type="text/css">
h1 { text-align: center; margin: 0; }
</style>
<script type="text/javascript" src="katalyze/web/jquery-1.6.1.js"></script>
<script type="text/javascript" src="feed.js"></script>
<script type="text/javascript" src="misc.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<?php navigation_container() ?>
<h1>Scoreboard</h1>
<!--<div class='teamscore' data-source='http://<?php echo $_SERVER['SERVER_ADDR']; ?>:8099' data-filter="">(Katalyzer must be running for this to work)</div>-->
<div class='teamscore' data-source='' data-filter="">(Katalyzer must be running for this to work)</div>
<script type='text/javascript' src='katalyze/web/scores.js'></script>
</body>
</html>
|
Refactor create english superset code to create english superset dictionaries in batches of 10K. Also re-include untranslated words. | import optparse
import os
optparser = optparse.OptionParser()
optparser.add_option("-d", "--directory", dest="directory", default="dictionaries/", help="Directory with dictionaries")
(opts, _) = optparser.parse_args()
full_path = os.path.abspath(opts.directory)
all_english_words = set()
for filename in os.listdir(full_path):
if filename.startswith('dict'):
for line in open(full_path+'\\'+filename, encoding='utf-8'):
translations = line.strip().split('\t')
foreign_word = translations[0]
# skip the first word because it is the foreign word
for word in translations[1:]:
all_english_words.add(word)
all_english_words_list = list(all_english_words)
words_per_batch = 10000
words_by_batch = [all_english_words_list[i:i+words_per_batch] for i in range(0, len(all_english_words_list), words_per_batch)]
for i, word_batch in enumerate(words_by_batch):
with open(full_path+'\\english.superset'+"{0:0=2d}".format(i+1), 'w', encoding='utf-8') as text_file:
text_file.write("\n".join(word_batch))
| import optparse
import os
optparser = optparse.OptionParser()
optparser.add_option("-d", "--directory", dest="directory", default="dictionaries/", help="Directory with dictionaries")
(opts, _) = optparser.parse_args()
full_path = os.path.abspath(opts.directory)
all_english_words = set()
for filename in os.listdir(full_path):
if filename.startswith('dict'):
for line in open(full_path+'\\'+filename, encoding='utf-8'):
translations = line.strip().split('\t')
foreign_word = translations[0]
# skip the first word because it is the foreign word
for word in translations[1:]:
# skip if word had no translation
if foreign_word != word:
all_english_words.add(word)
with open(full_path+'\\english.superset', 'w', encoding='utf-8') as text_file:
text_file.write("\n".join(all_english_words))
|
Add long description for PyPI | #!/usr/bin/env python
from os import environ
from setuptools import Extension, find_packages, setup
# Opt-in to building the C extensions for Python 2 by setting the
# ENABLE_DJB_HASH_CEXT environment variable
if environ.get('ENABLE_DJB_HASH_CEXT'):
ext_modules = [
Extension('cdblib._djb_hash', sources=['cdblib/_djb_hash.c']),
]
else:
ext_modules = []
description = "Pure Python reader/writer for Dan J. Berstein's CDB format."
setup(
author='David Wilson',
author_email='dw@botanicus.net',
description=description,
long_description=description,
download_url='https://github.com/dw/python-pure-cdb',
keywords='cdb file format appengine database db',
license='MIT',
name='pure-cdb',
version='2.1.0',
packages=find_packages(include=['cdblib']),
ext_modules=ext_modules,
install_requires=['six>=1.0.0,<2.0.0'],
test_suite='tests',
tests_require=['flake8'],
entry_points={
'console_scripts': ['python-pure-cdbmake=cdblib.cdbmake:main'],
},
)
| #!/usr/bin/env python
from os import environ
from setuptools import Extension, find_packages, setup
# Opt-in to building the C extensions for Python 2 by setting the
# ENABLE_DJB_HASH_CEXT environment variable
if environ.get('ENABLE_DJB_HASH_CEXT'):
ext_modules = [
Extension('cdblib._djb_hash', sources=['cdblib/_djb_hash.c']),
]
else:
ext_modules = []
setup(
author='David Wilson',
author_email='dw@botanicus.net',
description="Pure Python reader/writer for Dan J. Berstein's CDB format.",
download_url='https://github.com/dw/python-pure-cdb',
keywords='cdb file format appengine database db',
license='MIT',
name='pure-cdb',
version='2.1.0',
packages=find_packages(include=['cdblib']),
ext_modules=ext_modules,
install_requires=['six>=1.0.0,<2.0.0'],
test_suite='tests',
tests_require=['flake8'],
entry_points={
'console_scripts': ['python-pure-cdbmake=cdblib.cdbmake:main'],
},
)
|
Fix date to epoch converter to timestamp at exactly midnight | # For now I am assuming the investment date will be returned from the db
# as a string yyyy-mm-dd, representing the day the trend was purchased in UTC time
#!/usr/bin/env python3
from datetime import datetime, timezone, timedelta
import pytz
def get_start_times(date):
"""
date: an epoch integer representing the date that the investment was purchased
returns the integers (year, month, day)
"""
datetime_object = datetime.utcfromtimestamp(date)
return datetime_object.year, datetime_object.month, datetime_object.day
def get_end_times():
"""
returns the end dates to query pytrends for as integers (year, month, day)
"""
datetime = get_current_date() - timedelta(days = 1) #get yesterday's date
return datetime.year, datetime.month, datetime.day
def get_current_date():
"""
returns the current date in UTC as a datetime object
"""
utc = pytz.utc
date = datetime.now(tz=utc)
return date
def date_to_epoch(date):
"""
converts date object back into epoch (at exactly midnight utc on day of timestamp)
"""
year, month, day = date.year, date.month, date.day
dt = datetime(year=year, month=month, day=day)
utc_time = dt.replace(tzinfo = timezone.utc)
utc_dt = utc_time.timestamp()
return int(utc_dt)
| # For now I am assuming the investment date will be returned from the db
# as a string yyyy-mm-dd, representing the day the trend was purchased in UTC time
#!/usr/bin/env python3
from datetime import datetime, timedelta
import pytz
def get_start_times(date):
"""
date: an epoch integer representing the date that the investment was purchased
returns the integers (year, month, day)
"""
datetime_object = datetime.utcfromtimestamp(date)
return datetime_object.year, datetime_object.month, datetime_object.day
def get_end_times():
"""
returns the end dates to query pytrends for as integers (year, month, day)
"""
datetime = get_current_date() - timedelta(days = 1) #get yesterday's date
return datetime.year, datetime.month, datetime.day
def get_current_date():
"""
returns the current date in UTC as a datetime object
"""
utc = pytz.utc
date = datetime.now(tz=utc)
return date
def date_to_epoch(date):
"""
converts date object back into epoch
"""
return int(date.timestamp())
|
Fix test due to addition of coeff property
Address #49
Add fftshift to test coefficients as model.coeff now returns the
shifted real versions. | from pymks import MKSRegressionModel
import numpy as np
def test():
Nbin = 2
Nspace = 81
Nsample = 400
def filter(x):
return np.where(x < 10,
np.exp(-abs(x)) * np.cos(x * np.pi),
np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi))
coeff = np.linspace(1, 0, Nbin)[None,:] * filter(np.linspace(0, 20, Nspace))[:,None]
Fcoeff = np.fft.fft(coeff, axis=0)
np.random.seed(2)
X = np.random.random((Nsample, Nspace))
H = np.linspace(0, 1, Nbin)
X_ = np.maximum(1 - abs(X[:,:,None] - H) / (H[1] - H[0]), 0)
FX = np.fft.fft(X_, axis=1)
Fy = np.sum(Fcoeff[None] * FX, axis=-1)
y = np.fft.ifft(Fy, axis=1).real
model = MKSRegressionModel(Nbin=Nbin)
model.fit(X, y)
assert np.allclose(np.fft.fftshift(coeff, axes=(0,)), model.coeff)
if __name__ == '__main__':
test()
| from pymks import MKSRegressionModel
import numpy as np
def test():
Nbin = 2
Nspace = 81
Nsample = 400
def filter(x):
return np.where(x < 10,
np.exp(-abs(x)) * np.cos(x * np.pi),
np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi))
coeff = np.linspace(1, 0, Nbin)[None,:] * filter(np.linspace(0, 20, Nspace))[:,None]
Fcoeff = np.fft.fft(coeff, axis=0)
np.random.seed(2)
X = np.random.random((Nsample, Nspace))
H = np.linspace(0, 1, Nbin)
X_ = np.maximum(1 - abs(X[:,:,None] - H) / (H[1] - H[0]), 0)
FX = np.fft.fft(X_, axis=1)
Fy = np.sum(Fcoeff[None] * FX, axis=-1)
y = np.fft.ifft(Fy, axis=1).real
model = MKSRegressionModel(Nbin=Nbin)
model.fit(X, y)
model.coeff = np.fft.ifft(model.Fcoeff, axis=0)
assert np.allclose(coeff, model.coeff)
if __name__ == '__main__':
test()
|
Set brand to 'New Item', set barcode if given, link to vendor items | <?
include '../scat.php';
include '../lib/item.php';
$code= $_REQUEST['code'];
$name= $_REQUEST['name'];
$msrp= $_REQUEST['retail_price'];
if (!$code)
die_jsonp('Must specify a code.');
if (!$name)
die_jsonp('Must specify a name.');
if (!$msrp)
die_jsonp('Must specify a price.');
$code= $db->escape($code);
$name= $db->escape($name);
$msrp= $db->escape($msrp);
$brand= $db->get_one("SELECT id FROM brand WHERE name = 'New Item'");
$q= "INSERT INTO item
SET code = '$code', name = '$name', retail_price = '$msrp',
brand = $brand,
taxfree = 0, minimum_quantity = 1, active = 1";
$r= $db->query($q)
or die_query($db, $q);
$item_id= $db->insert_id;
if ($_REQUEST['barcode']) {
$bar= $db->escape($_REQUEST['barcode']);
$q= "INSERT INTO barcode SET code = '$bar', item = $item_id, quantity = 1";
$r= $db->query($q)
or die_query($db, $q);
}
/* Link to vendor items */
$q= "UPDATE vendor_item
SET vendor_item.item = $item_id
WHERE vendor_item.code = '$code'";
$db->query($q)
or die_query($db, $q);
$item= item_load($db, $item_id);
echo jsonp(array('item' => $item));
| <?
include '../scat.php';
include '../lib/item.php';
$code= $_REQUEST['code'];
$name= $_REQUEST['name'];
$msrp= $_REQUEST['retail_price'];
if (!$code)
die_jsonp('Must specify a code.');
if (!$name)
die_jsonp('Must specify a name.');
if (!$msrp)
die_jsonp('Must specify a price.');
$code= $db->escape($code);
$name= $db->escape($name);
$msrp= $db->escape($msrp);
$q= "INSERT INTO item
SET code = '$code', name = '$name', retail_price = '$msrp',
taxfree = 0, minimum_quantity = 1, active = 1";
$r= $db->query($q)
or die_query($db, $q);
$item_id= $db->insert_id;
$item= item_load($db, $item_id);
echo jsonp(array('item' => $item));
|
Add more precise type annotation | <?php declare(strict_types=1);
namespace Imjoehaines\Flowder\Loader;
final class CachingLoader implements LoaderInterface
{
/**
* The array of cached data
*
* @var array<string, array<string, iterable>>
*/
private $cache = [];
/**
* A "real" loader instance that actually does the loading
*
* @var LoaderInterface
*/
private $loader;
/**
* @param LoaderInterface $loader
*/
public function __construct(LoaderInterface $loader)
{
$this->loader = $loader;
}
/**
* Load the given thing and cache the results for repeated calls
*
* @param mixed $thingToLoad
* @return iterable
*/
public function load($thingToLoad): iterable
{
if (!array_key_exists($thingToLoad, $this->cache)) {
foreach ($this->loader->load($thingToLoad) as $table => $data) {
$this->cache[$thingToLoad][$table] = $data;
yield $table => $data;
}
} else {
yield from $this->cache[$thingToLoad];
}
}
}
| <?php declare(strict_types=1);
namespace Imjoehaines\Flowder\Loader;
final class CachingLoader implements LoaderInterface
{
/**
* The array of cached data
*
* @var array
*/
private $cache = [];
/**
* A "real" loader instance that actually does the loading
*
* @var LoaderInterface
*/
private $loader;
/**
* @param LoaderInterface $loader
*/
public function __construct(LoaderInterface $loader)
{
$this->loader = $loader;
}
/**
* Load the given thing and cache the results for repeated calls
*
* @param mixed $thingToLoad
* @return iterable
*/
public function load($thingToLoad): iterable
{
if (!array_key_exists($thingToLoad, $this->cache)) {
foreach ($this->loader->load($thingToLoad) as $table => $data) {
$this->cache[$thingToLoad][$table] = $data;
yield $table => $data;
}
} else {
yield from $this->cache[$thingToLoad];
}
}
}
|
Fix IE bug when calculating displayName
IE does not have Function.prototype.bind. Supply a super-generic
fallback of "Component" so that a String is always returned. | import React, { PropTypes } from "react"
export const nameWithContext = (Lower, prop = "name") => {
const getDisplayName = (component) => component.displayName || component.name || "Component"
const buildInputName = (namespaces, name = "") => (
[ ...namespaces, name ].map((field, index) => ( index === 0 ? field : `[${field}]` )).join("")
)
const higher = (props, context) => {
const replacedProp = buildInputName(context.railsFormNamespaces, props[prop])
const replacedProps = Object.assign({}, props, { [prop]: replacedProp })
return <Lower {...replacedProps} />
}
higher.displayName = getDisplayName(Lower).replace(/Tag$/, "")
higher.contextTypes = { railsFormNamespaces: PropTypes.arrayOf(PropTypes.string) }
return higher
}
export const whitelistProps = (props, ...omit) => {
const alwaysOmit = [ "key", "ref", ...omit ]
const cloned = { ...props }
alwaysOmit.forEach((key) => delete cloned[key])
return cloned
}
| import React, { PropTypes } from "react"
export const nameWithContext = (Lower, prop = "name") => {
const getDisplayName = (Lower) => ((Lower.displayName || Lower.name).replace(/Tag$/, ""))
const buildInputName = (namespaces, name = "") => (
[ ...namespaces, name ].map((field, index) => ( index === 0 ? field : `[${field}]` )).join("")
)
const higher = (props, context) => {
const replacedProp = buildInputName(context.railsFormNamespaces, props[prop])
const replacedProps = Object.assign({}, props, { [prop]: replacedProp })
return <Lower {...replacedProps} />
}
higher.displayName = getDisplayName(Lower)
higher.contextTypes = { railsFormNamespaces: PropTypes.arrayOf(PropTypes.string) }
return higher
}
export const whitelistProps = (props, ...omit) => {
const alwaysOmit = [ "key", "ref", ...omit ]
const cloned = { ...props }
alwaysOmit.forEach((key) => delete cloned[key])
return cloned
}
|
Rename program to string in tokenize | # Kimi language interpreter in Python 3
# Anjana Vakil
# http://www.github.com/vakila/kimi
import sys
def tokenize(string):
'''Take a Kimi program as a string, return the tokenized program as a list of strings.
>>> tokenize("(+ 1 2)")
['(', '+', '1', '2', ')']
>>> tokenize("(define square (lambda x (* x x)))")
['(', 'define', 'square', '(', 'lambda', 'x', '(', '*', 'x', 'x', ')', ')', ')']
'''
string = string.replace("(", " ( ")
string = string.replace(")", " ) ")
tokens = string.split()
return tokens
def parse(tokens):
pass
def evaluate(tree):
pass
if __name__ == "__main__":
program = sys.argv[1]
print(tokenize(program))
| # Kimi language interpreter in Python 3
# Anjana Vakil
# http://www.github.com/vakila/kimi
import sys
def tokenize(program):
'''Take a Kimi program as a string, return the tokenized program as a list of strings.
>>> tokenize("(+ 1 2)")
['(', '+', '1', '2', ')']
>>> tokenize("(define square (lambda x (* x x)))")
['(', 'define', 'square', '(', 'lambda', 'x', '(', '*', 'x', 'x', ')', ')', ')']
'''
program = program.replace("(", " ( ")
program = program.replace(")", " ) ")
tokens = program.split()
return tokens
def parse(tokens):
pass
def evaluate(tree):
pass
if __name__ == "__main__":
program = sys.argv[1]
print(tokenize(program))
|
Fix warning ActionBarActivity is deprecated. Replace ActionBarActivity from new project template with AppCompatActivity.
References
http://stackoverflow.com/questions/29890530/actionbaractivity-is-deprecated-android-studio?rq=1
http://android-developers.blogspot.com/2015/04/android-support-library-221.html | package com.beepscore.android.sunshine;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class DetailActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detail, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| package com.beepscore.android.sunshine;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class DetailActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detail, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
Copy service worker to root path. | var baseConfig = require('./webpack.config.common.js');
var webpack = require('webpack');
const merge = require('webpack-merge');
var path = require('path');
var OfflinePlugin = require('offline-plugin');
module.exports = merge(baseConfig, {
output: {
path: path.resolve(__dirname, './dist/static/'),
filename: 'js/[name]-bundle.[chunkhash].js'
},
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: true,
warnings: false,
},
// mangle brakes angular.
mangle: false,
output: {
screw_ie8: true
},
exclude: [/\.min\.js$/gi]
}),
// it's always better if OfflinePlugin is the last plugin added
new OfflinePlugin({
ServiceWorker: {
output: '../sw.js',
},
}),
],
});
| var baseConfig = require('./webpack.config.common.js');
var webpack = require('webpack');
const merge = require('webpack-merge');
var path = require('path');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var OfflinePlugin = require('offline-plugin');
module.exports = merge(baseConfig, {
output: {
path: path.resolve(__dirname, './dist/static/'),
filename: 'js/[name]-bundle.[chunkhash].js'
},
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: true,
warnings: false,
},
// mangle brakes angular.
mangle: false,
output: {
screw_ie8: true
},
exclude: [/\.min\.js$/gi]
}),
// it's always better if OfflinePlugin is the last plugin added
new OfflinePlugin(),
],
});
|
Use category, not category title for list_filter | # -*- coding: utf-8 -*-
from django.contrib import admin
from blanc_pages.admin import BlancPageAdminMixin
from .models import Category, Event
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
search_fields = ('title',)
prepopulated_fields = {
'slug': ('title',)
}
@admin.register(Event)
class EventAdmin(BlancPageAdminMixin, admin.ModelAdmin):
fieldsets = (
('Event', {
'fields': (
'title', 'category', 'location', 'image', 'summary', 'start', 'end'
)
}),
('Advanced options', {
'fields': ('slug',)
}),
)
date_hierarchy = 'start'
list_display = ('title', 'start', 'end', 'category',)
list_filter = ('published', 'start', 'category',)
prepopulated_fields = {
'slug': ('title',)
}
| # -*- coding: utf-8 -*-
from django.contrib import admin
from blanc_pages.admin import BlancPageAdminMixin
from .models import Category, Event
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
search_fields = ('title',)
prepopulated_fields = {
'slug': ('title',)
}
@admin.register(Event)
class EventAdmin(BlancPageAdminMixin, admin.ModelAdmin):
pass
fieldsets = (
('Event', {
'fields': (
'title', 'category', 'location', 'image', 'summary', 'start', 'end'
)
}),
('Advanced options', {
'fields': ('slug',)
}),
)
date_hierarchy = 'start'
list_display = ('title', 'start', 'end', 'category',)
list_filter = ('published', 'start', 'category__title',)
prepopulated_fields = {
'slug': ('title',)
}
|
Use error response when request fails | package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"regexp"
"time"
)
func main() {
fmt.Println("Verifying URLs..")
readmeFile, err := ioutil.ReadFile("README.md")
if err != nil {
fmt.Println("Could not find README!")
os.Exit(1)
}
fileContent := string(readmeFile)
urlElementRegex := regexp.MustCompile(`(?m)\[.+?]\(((http|https)://.+?)\)`)
httpClient := http.Client{Timeout: 10 * time.Second}
var brokenUrls []string
for _, urlElement := range urlElementRegex.FindAllStringSubmatch(fileContent, -1) {
var url = urlElement[1]
fmt.Printf("Checking %s: ", url)
resp, err := httpClient.Get(url)
if err != nil || resp.StatusCode != 200 {
brokenUrls = append(brokenUrls, url)
fmt.Println("FAILED - ", err)
} else {
fmt.Println("OK")
}
}
if len(brokenUrls) != 0 {
fmt.Println("Broken URLs were found:")
for _, brokenUrl := range brokenUrls {
fmt.Println(brokenUrl)
}
os.Exit(1)
}
fmt.Println("No broken URLs found!")
os.Exit(0)
}
| package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"regexp"
"time"
)
func main() {
fmt.Println("Verifying URLs..")
readmeFile, err := ioutil.ReadFile("README.md")
if err != nil {
fmt.Println("Could not find README!")
os.Exit(1)
}
fileContent := string(readmeFile)
urlElementRegex := regexp.MustCompile(`(?m)\[.+?]\(((http|https)://.+?)\)`)
httpClient := http.Client{Timeout: 10 * time.Second}
var brokenUrls []string
for _, urlElement := range urlElementRegex.FindAllStringSubmatch(fileContent, -1) {
var url = urlElement[1]
fmt.Printf("Checking %s: ", url)
resp, err := httpClient.Get(url)
if err != nil || resp.StatusCode != 200 {
brokenUrls = append(brokenUrls, url)
fmt.Println("FAILED - " err)
} else {
fmt.Println("OK")
}
}
if len(brokenUrls) != 0 {
fmt.Println("Broken URLs were found:")
for _, brokenUrl := range brokenUrls {
fmt.Println(brokenUrl)
}
os.Exit(1)
}
fmt.Println("No broken URLs found!")
os.Exit(0)
}
|
Prepare once plug-ins are loaded
With the new version of the listen hook. | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license differs from the license provided with this software, the license provided with this software should be applied.
"""
Provides a class that allows for creating global application preferences.
"""
import luna.listen #To prepare the preferences for use when plug-ins are loaded.
import luna.plugins #To get the configuration data type to extend from.
class Preferences:
"""
Offers a system to create global application preferences.
"""
def __init__(self):
luna.listen.listen(self.check_prepare, luna.plugins, "state")
def check_prepare(self, _, new_state):
if new_state == luna.plugins.PluginsState.LOADED:
self.prepare()
def prepare(self):
"""
Finalizes the class initialisation using data that is only available at
run time.
"""
original_class = self.__class__
parent_class = luna.plugins.api("configuration").Configuration
self.__class__ = original_class.__class__(original_class.__name__ + "Configuration", (original_class, parent_class), {}) #Add the configuration class mixin.
super().__init__() #Execute the Configuration class' initialisation method to create the data structures. | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license differs from the license provided with this software, the license provided with this software should be applied.
"""
Provides a class that allows for creating global application preferences.
"""
import luna.plugins #To get the configuration data type to extend from.
class Preferences:
"""
Offers a system to create global application preferences.
"""
def prepare(self):
"""
Finalizes the class initialisation using data that is only available at
run time.
"""
original_class = self.__class__
parent_class = luna.plugins.api("configuration").Configuration
self.__class__ = original_class.__class__(original_class.__name__ + "Configuration", (original_class, parent_class), {}) #Add the configuration class mixin.
super().__init__() #Execute the Configuration class' initialisation method to create the data structures. |
Add function to get list of objects having only userNames | const sqlite3 = require('sqlite3').verbose()
const dbName = 'chat.sqlite'
const db = new sqlite3.Database(dbName)
db.serialize(() => {
const sql = `
CREATE TABLE IF NOT EXISTS users
(id integer primary key AUTOINCREMENT, phoneNumber, userName)
`;
db.run(sql)
})
class Users {
static all (cb) {
db.all('SELECT * FROM users', cb)
}
static allUserNames (cb) {
db.all('SELECT userName FROM users', cb)
}
static find (data, cb) {
if (data) {
db.get('SELECT * FROM users WHERE userName = ?', data.name, cb)
}
}
static findByPhoneNumber (phoneNumber, cb) {
if (phoneNumber) {
db.get('SELECT * FROM users WHERE phoneNumber = ?', phoneNumber, cb)
}
}
static insert (data, cb) {
const sql = 'INSERT INTO users(phoneNumber, userName) VALUES (?, ?)'
db.run(sql, data.phoneNumber, data.name, cb)
}
}
module.exports = db
module.exports.Users = Users
| const sqlite3 = require('sqlite3').verbose()
const dbName = 'chat.sqlite'
const db = new sqlite3.Database(dbName)
db.serialize(() => {
const sql = `
CREATE TABLE IF NOT EXISTS users
(id integer primary key AUTOINCREMENT, phoneNumber, userName)
`;
db.run(sql)
})
class Users {
static all(cb) {
db.all('SELECT * FROM users', cb)
}
static find(data, cb) {
if (data) {
db.get('SELECT * FROM users WHERE userName = ?', data.name, cb)
}
}
static findByPhoneNumber(phoneNumber, cb) {
if (phoneNumber) {
db.get('SELECT * FROM users WHERE phoneNumber = ?', phoneNumber, cb)
}
}
static insert(data, cb) {
const sql = 'INSERT INTO users(phoneNumber, userName) VALUES (?, ?)'
db.run(sql, data.phoneNumber, data.name, cb)
}
}
module.exports = db
module.exports.Users = Users
|
test: Write test to catch invalid inserts | 'use strict';
const assert = require('assert');
const Event = require('../db/models/Event');
describe('Validation of User records', () => {
// Tests that records for which no `name` property is defined are marked invalid
// and return a validation fallback message:
it('should require a name for every event', () => {
const validationEvt = new Event({ name: undefined }),
validationResult = validationEvt.validateSync(),
{ message } = validationResult.errors.name;
assert(message === 'This event requires a name.');
});
// Tests that records for which the `name` property is less than three (3) characters
// in length are marked invalid and return a validation fallback message:
it ('should require an event\'s name to be at least 3 characters long', () => {
const validationEvt = new Event({ name: 'ab' }),
validationResult = validationEvt.validateSync(),
{ message } = validationResult.errors.name;
assert(message === 'Your event name must be at least 3 characters long.');
});
// Tests that attempts to `save()` records marked as invalid to the database are caught
// as errors and are not added to the database:
it('should disallow invalid records from being saved to the database', (done) => {
const invalidEvt = new Event({ name: 'ab', });
invalidEvt
.save()
.catch((validationResult) => {
const { message } = validationResult.errors.name;
assert(message === 'Your event name must be at least 3 characters long.');
done();
});
});
});
| 'use strict';
const assert = require('assert');
const Event = require('../db/models/Event');
describe('Validation of User records', () => {
it('should require a name for every event', () => {
const validationEvt = new Event({ name: undefined }),
validationResult = validationEvt.validateSync(),
{ message } = validationResult.errors.name;
assert(message === 'This event requires a name.');
});
it ('should require an event\'s name to be at least 3 characters long', () => {
const validationEvt = new Event({ name: 'ab' }),
validationResult = validationEvt.validateSync(),
{ message } = validationResult.errors.name;
assert(message === 'Your event name must be at least 3 characters long.');
});
it('should disallow invalid records from being saved to the database', (done) => {
const invalidEvt = new Event({ name: 'ab', });
invalidEvt
.save()
.catch((validationResult) => {
const { message } = validationResult.errors.name;
assert(message === 'Your event name must be at least 3 characters long.');
done();
});
});
});
|
Make sure we can add activities to initiatives in admin | from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from bluebottle.fsm.effects import Effect
from bluebottle.activities.models import Organizer, OrganizerContribution
class CreateOrganizer(Effect):
"Create an organizer for the activity"
display = False
def post_save(self, **kwargs):
Organizer.objects.get_or_create(
activity=self.instance,
defaults={'user': self.instance.owner}
)
def __str__(self):
return str(_('Create organizer'))
class CreateOrganizerContribution(Effect):
"Create an contribution for the organizer of the activity"
display = False
def post_save(self, **kwargs):
OrganizerContribution.objects.get_or_create(
contributor=self.instance
)
def __str__(self):
return str(_('Create organizer contribution'))
class SetContributionDateEffect(Effect):
"Set the contribution date"
conditions = []
display = False
def pre_save(self, **kwargs):
self.instance.start = now()
def __str__(self):
return _('Set the contribution date.')
| from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from bluebottle.fsm.effects import Effect
from bluebottle.activities.models import Organizer, OrganizerContribution
class CreateOrganizer(Effect):
"Create an organizer for the activity"
def post_save(self, **kwargs):
Organizer.objects.get_or_create(
activity=self.instance,
defaults={'user': self.instance.owner}
)
def __str__(self):
return str(_('Create organizer'))
class CreateOrganizerContribution(Effect):
"Create an contribution for the organizer of the activity"
def post_save(self, **kwargs):
OrganizerContribution.objects.get_or_create(
contributor=self.instance
)
def __str__(self):
return str(_('Create organizer contribution'))
class SetContributionDateEffect(Effect):
"Set the contribution date"
conditions = []
display = False
def pre_save(self, **kwargs):
self.instance.start = now()
def __str__(self):
return _('Set the contribution date.')
|
Remove support for deprecated `captureError` (now `...Exception`) | 'use strict'
var raven = require('raven')
exports.register = function (server, options, next) {
var client = new raven.Client(options.dsn, options.client)
server.expose('client', client)
server.on('request-error', function (request, err) {
client.captureException(err, {
extra: {
timestamp: request.info.received,
id: request.id,
method: request.method,
path: request.path,
query: request.query,
remoteAddress: request.info.remoteAddress,
userAgent: request.raw.req.headers['user-agent']
},
tags: options.tags
})
})
next()
}
exports.register.attributes = {
pkg: require('./package.json')
}
| 'use strict'
var raven = require('raven')
exports.register = function (server, options, next) {
var client = new raven.Client(options.dsn, options.client)
server.expose('client', client)
server.on('request-error', function (request, err) {
(client.captureException || client.captureError).call(client, err, {
extra: {
timestamp: request.info.received,
id: request.id,
method: request.method,
path: request.path,
query: request.query,
remoteAddress: request.info.remoteAddress,
userAgent: request.raw.req.headers['user-agent']
},
tags: options.tags
})
})
next()
}
exports.register.attributes = {
pkg: require('./package.json')
}
|
Fix missing parameter in docs of setChannel function | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Channel\Model;
use Sylius\Component\Resource\Model\CodeAwareInterface;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;
use Sylius\Component\Resource\Model\ToggleableInterface;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface ChannelInterface extends CodeAwareInterface, TimestampableInterface, ToggleableInterface, ResourceInterface
{
/**
* @return string
*/
public function getName();
/**
* @param string $name
*/
public function setName($name);
/**
* @return string
*/
public function getDescription();
/**
* @param string $description
*/
public function setDescription($description);
/**
* @return string
*/
public function getHostname();
/**
* @param string $hostname
*/
public function setHostname($hostname);
/**
* @return string
*/
public function getColor();
/**
* @param string $color
*/
public function setColor($color);
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Channel\Model;
use Sylius\Component\Resource\Model\CodeAwareInterface;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;
use Sylius\Component\Resource\Model\ToggleableInterface;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface ChannelInterface extends CodeAwareInterface, TimestampableInterface, ToggleableInterface, ResourceInterface
{
/**
* @return string
*/
public function getName();
/**
* @param string $name
*/
public function setName($name);
/**
* @return string
*/
public function getDescription();
/**
* @param string $description
*/
public function setDescription($description);
/**
* @return string
*/
public function getHostname();
/**
* @param string $url
*/
public function setHostname($hostname);
/**
* @return string
*/
public function getColor();
/**
* @param string $color
*/
public function setColor($color);
}
|
[ALIEN-2755] Allow specific handling of docker image artifact update in the editor, util fix. | package org.alien4cloud.tosca.utils;
import static alien4cloud.utils.AlienUtils.safe;
import java.util.Map;
import java.util.Optional;
import org.alien4cloud.tosca.model.definitions.ImplementationArtifact;
import org.alien4cloud.tosca.model.definitions.Interface;
import org.alien4cloud.tosca.model.definitions.Operation;
public final class InterfaceUtils {
private InterfaceUtils() {
}
public static ImplementationArtifact getArtifact(Map<String, Interface> interfaceMap, String interfaceName, String operationName) {
Optional.of(safe(interfaceMap).get(interfaceName)).map()
Interface interfaz = safe(interfaceMap).get(interfaceName);
if (interfaz == null) {
return null;
}
Operation operation = safe(interfaz.getOperations()).get(operationName);
if(operation == null) {
return null;
}
return operation.getImplementationArtifact();
}
}
| package org.alien4cloud.tosca.utils;
import org.alien4cloud.tosca.model.definitions.ImplementationArtifact;
import org.alien4cloud.tosca.model.definitions.Interface;
import org.alien4cloud.tosca.model.definitions.Operation;
import java.util.Map;
import java.util.Optional;
import static alien4cloud.utils.AlienUtils.safe;
public final class InterfaceUtils {
private InterfaceUtils() {
}
public static ImplementationArtifact getArtifact(Map<String, Interface> interfaceMap, String interfaceName, String operationName) {
Optional.of(safe(interfaceMap).get(interfaceName)).map()
Interface interfaz = safe(interfaceMap).get(interfaceName);
if (interfaz == null) {
return null;
}
Operation operation = safe(interfaz.getOperations()).get(operationName);
if(operation )
}
}
|
Add debugging info to the main test | package main_test
import (
"os"
"os/exec"
"path"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestMain(t *testing.T) {
RegisterFailHandler(Fail)
dir, err := os.Getwd()
Expect(err).NotTo(HaveOccurred())
cmd := exec.Command("go", "build", "-o", path.Join(dir, "..", "fixtures", "plugins", "test"), path.Join(dir, "..", "fixtures", "plugins", "test.go"))
err = cmd.Run()
if err != nil {
println(err.Error())
}
Expect(err).NotTo(HaveOccurred())
cmd = exec.Command("go", "build", "-o", path.Join(dir, "..", "fixtures", "plugins", "plugin2"), path.Join(dir, "..", "fixtures", "plugins", "plugin2.go"))
err = cmd.Run()
Expect(err).NotTo(HaveOccurred())
RunSpecs(t, "Main Suite")
}
| package main_test
import (
"os"
"os/exec"
"path"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestMain(t *testing.T) {
RegisterFailHandler(Fail)
dir, err := os.Getwd()
Expect(err).NotTo(HaveOccurred())
cmd := exec.Command("go", "build", "-o", path.Join(dir, "..", "fixtures", "plugins", "test"), path.Join(dir, "..", "fixtures", "plugins", "test.go"))
err = cmd.Run()
defer GinkgoRecover()
Expect(err).NotTo(HaveOccurred())
cmd = exec.Command("go", "build", "-o", path.Join(dir, "..", "fixtures", "plugins", "plugin2"), path.Join(dir, "..", "fixtures", "plugins", "plugin2.go"))
err = cmd.Run()
Expect(err).NotTo(HaveOccurred())
RunSpecs(t, "Main Suite")
}
|
Simplify assertion from to.not.be.empty to to.exist | import {List} from 'immutable';
import {expect} from 'chai';
import {createPlayer} from '../src/core';
describe('createPlayer', () => {
it('sets name properly', () => {
const name = 'someName';
const player = createPlayer(name);
expect(player.name).to.equal(name);
});
it('sets a non-empty ID', () => {
const player = createPlayer('someName');
expect(player.id).to.exist;
});
it('initializes an empty hand', () => {
const player = createPlayer('someName');
expect(player.hand).to.equal(List.of());
});
}
);
| import {List} from 'immutable';
import {expect} from 'chai';
import {createPlayer} from '../src/core';
describe('createPlayer', () => {
it('sets name properly', () => {
const name = 'someName';
const player = createPlayer(name);
expect(player.name).to.equal(name);
});
it('sets a non-empty ID', () => {
const player = createPlayer('someName');
expect(player.id).to.not.be.empty;
});
it('initializes an empty hand', () => {
const player = createPlayer('someName');
expect(player.hand).to.equal(List.of());
});
}
); |
Bump version to 1.0.1 for unit test fix. | import os.path
VERSION = (1, 0, 1, 'stable')
def get_version():
"""
Return the version as a string. If this is flagged as a development
release and mercurial can be loaded the specifics about the changeset
will be appended to the version string.
"""
if 'dev' in VERSION:
try:
from mercurial import hg, ui
repo_path = os.path.join(os.path.dirname(__file__), '..')
repo = hg.repository(ui.ui(), repo_path)
ctx = repo['tip']
build_info = 'dev %s %s:%s' % (ctx.branch(), ctx.rev(), str(ctx))
except:
# mercurial module missing or repository not found
build_info = 'dev-unknown'
v = VERSION[:VERSION.index('dev')] + (build_info,)
return '.'.join(map(str, v))
| import os.path
VERSION = (1, 0, 0, 'stable')
def get_version():
"""
Return the version as a string. If this is flagged as a development
release and mercurial can be loaded the specifics about the changeset
will be appended to the version string.
"""
if 'dev' in VERSION:
try:
from mercurial import hg, ui
repo_path = os.path.join(os.path.dirname(__file__), '..')
repo = hg.repository(ui.ui(), repo_path)
ctx = repo['tip']
build_info = 'dev %s %s:%s' % (ctx.branch(), ctx.rev(), str(ctx))
except:
# mercurial module missing or repository not found
build_info = 'dev-unknown'
v = VERSION[:VERSION.index('dev')] + (build_info,)
return '.'.join(map(str, v))
|
Remove useless comment about returning a null mouse. Access mouse through ForPlay.mouse().
git-svn-id: 53b953c7be2d47dd5cb9b5c1ab101a1158da7762@77 a6a9a2b1-fcd7-f629-9329-86f1cfbb9621 | /**
* Copyright 2010 The ForPlay Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package forplay.core;
/**
* Generic platform interface. New platforms are defined as implementations of this interface.
*/
public interface Platform {
Audio audio();
Graphics graphics();
AssetManager assetManager();
Json json();
Keyboard keyboard();
Log log();
Net net();
Pointer pointer();
Mouse mouse();
Storage storage();
Analytics analytics();
float random();
void run(Game game);
double time();
RegularExpression regularExpression();
void openURL(String url);
}
| /**
* Copyright 2010 The ForPlay Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package forplay.core;
/**
* Generic platform interface. New platforms are defined as implementations of this interface.
*/
public interface Platform {
Audio audio();
Graphics graphics();
AssetManager assetManager();
Json json();
Keyboard keyboard();
Log log();
Net net();
Pointer pointer();
/**
* Return the mouse if it is supported, or null otherwise.
*
* @return the mouse if it is supported, or null otherwise.
*/
Mouse mouse();
Storage storage();
Analytics analytics();
float random();
void run(Game game);
double time();
RegularExpression regularExpression();
void openURL(String url);
}
|
Allow deprecated warning to have one prop
and not a new prop | /* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */
/* eslint-disable import/no-mutable-exports */
// This function will deliver an error message to the browser console about the removal of a property.
import warning from 'warning';
let deprecated = function () {};
if (process.env.NODE_ENV !== 'production') {
const hasWarned = {};
deprecated = function (control, propValue, oldProp, newProp, comment) {
const additionalComment = comment ? ` ${comment}` : '';
const newProperty = newProp ? `Use \`${newProp}\`` : '';
const newPropertySentence = newProp ? ` ${newProperty} instead.` : '';
if (!hasWarned[control + oldProp]) {
/* eslint-disable max-len */
warning(propValue === undefined, `[Design System React] \`${oldProp}\` will be removed in the next major version of ${control}.${newPropertySentence}${additionalComment}`);
/* eslint-enable max-len */
hasWarned[control + oldProp] = propValue !== undefined;
}
};
}
export default deprecated;
| /* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */
/* eslint-disable import/no-mutable-exports */
// This function will deliver an error message to the browser console about the removal of a property.
import warning from 'warning';
let deprecated = function () {};
if (process.env.NODE_ENV !== 'production') {
const hasWarned = {};
deprecated = function (control, propValue, oldProp, newProp, comment) {
const additionalComment = comment ? ` ${comment}` : '';
const newProperty = newProp ? `Use \`${newProp}\`` : '';
if (!hasWarned[control + oldProp]) {
/* eslint-disable max-len */
warning(propValue === undefined, `[Design System React] \`${oldProp}\` will be removed in the next major version of ${control}. ${newProperty} instead.${additionalComment}`);
/* eslint-enable max-len */
hasWarned[control + oldProp] = propValue !== undefined;
}
};
}
export default deprecated;
|
Set svn:eol-style='native' on some text files that were lacking it.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@855475 13f79535-47bb-0310-9956-ffa450edef68 | #
# strip-po-charset.py
#
import sys, string
def strip_po_charset(inp, out):
out.write(string.replace(inp.read(),
"\"Content-Type: text/plain; charset=UTF-8\\n\"\n",""))
def main():
if len(sys.argv) != 3:
print "Usage: %s <input (po) file> <output (spo) file>" % sys.argv[0]
print
print "Unsupported number of arguments; 2 required."
sys.exit(1)
strip_po_charset(open(sys.argv[1],'r'), open(sys.argv[2],'w'))
if __name__ == '__main__':
main()
| #
# strip-po-charset.py
#
import sys, string
def strip_po_charset(inp, out):
out.write(string.replace(inp.read(),
"\"Content-Type: text/plain; charset=UTF-8\\n\"\n",""))
def main():
if len(sys.argv) != 3:
print "Usage: %s <input (po) file> <output (spo) file>" % sys.argv[0]
print
print "Unsupported number of arguments; 2 required."
sys.exit(1)
strip_po_charset(open(sys.argv[1],'r'), open(sys.argv[2],'w'))
if __name__ == '__main__':
main()
|
Remove printStackTrace from Ant task
Change StopZapTask to remove the call to Throwable.printStackTrace(),
the exception is wrapped and thrown for the caller to handle (e.g. Ant
which already outputs the stack trace). | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2011 The Zed Attack Proxy Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.clientapi.ant;
import org.apache.tools.ant.BuildException;
public class StopZapTask extends ZapTask {
@Override
public void execute() throws BuildException {
try {
this.getClientApi().core.shutdown(null);
} catch (Exception e) {
throw new BuildException(e);
}
}
}
| /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2011 The Zed Attack Proxy Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.clientapi.ant;
import org.apache.tools.ant.BuildException;
public class StopZapTask extends ZapTask {
@Override
public void execute() throws BuildException {
try {
this.getClientApi().core.shutdown(null);
} catch (Exception e) {
e.printStackTrace();
throw new BuildException(e);
}
}
}
|
Check that reasons length is greater than 0 | 'use strict';
/* Controllers */
angular.module('nodeCheck.controllers', []).
controller('AppCtrl', function($scope, $http) {
$scope.website = {url: ''};
$scope.displayResult = false;
$scope.displayError = false;
$scope.check = function() {
var url = $scope.website.url;
if (url !== "") {
$scope.reasons = [];
$scope.makeRequest(url);
}
}
$scope.makeRequest = function(url) {
$http({method: 'GET', url: "/?url=" +encodeURIComponent(url)}).
success(function(data, status, headers, config) {
$scope.displayResult = true;
$scope.displayError = false;
$scope.resultUrl = data.message.url;
$scope.message = data.message.answer;
if(data.message.reasons.length > 0)
$scope.reasons = data.message.reasons[0].reasons;
}).
error(function(data, status, headers, config) {
$scope.displayError = true;
$scope.displayResult = false;
$scope.errorMsg = "Sorry, an error "+status+" occured";
});
}
}); | 'use strict';
/* Controllers */
angular.module('nodeCheck.controllers', []).
controller('AppCtrl', function($scope, $http) {
$scope.website = {url: ''};
$scope.displayResult = false;
$scope.displayError = false;
$scope.check = function() {
var url = $scope.website.url;
if (url !== "") {
$scope.reasons = [];
$scope.makeRequest(url);
}
}
$scope.makeRequest = function(url) {
$http({method: 'GET', url: "/?url=" +encodeURIComponent(url)}).
success(function(data, status, headers, config) {
$scope.displayResult = true;
$scope.displayError = false;
$scope.resultUrl = data.message.url;
$scope.message = data.message.answer;
$scope.reasons = data.message.reasons[0].reasons;
}).
error(function(data, status, headers, config) {
$scope.displayError = true;
$scope.displayResult = false;
$scope.errorMsg = "Sorry, an error "+status+" occured";
});
}
}); |
Update to use all the test | import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
from sklearn.ensemble import RandomForestClassifier
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
parameter_str = '_'.join(['top', str(utils.k), 'cw', str(utils.click_weight), 'year', utils.train_year])
cforest = joblib.load(utils.model_path + 'rf_all_without_time_' + parameter_str +'.pkl')
test = joblib.load(utils.processed_data_path + 'test_all_' + parameter_str +'.pkl')
X_test = test.ix[:,1:]
X_test.fillna(-1, inplace=True)
print "predict RandomForest Classifier..."
probs = cforest.predict_proba(X_test)
sorted_index = np.argsort(-np.array(probs))[:,:5]
result = pd.DataFrame(columns = {'hotel_cluster'})
result['hotel_cluster'] = np.array([np.array_str(sorted_index[i])[1:-1] for i in range(sorted_index.shape[0])])
result.hotel_cluster.to_csv(utils.model_path +
'results/submission_rf_all_without_time_' + parameter_str + '.csv', header=True, index_label='id')
| import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
from sklearn.ensemble import RandomForestClassifier
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
parameter_str = '_'.join(['top', str(utils.k), 'cw', str(utils.click_weight), 'year', utils.train_year])
cforest = joblib.load(utils.model_path + 'rf_all_without_time_' + parameter_str +'.pkl')
test = joblib.load(utils.processed_data_path + 'test_all_' + parameter_str +'.pkl')
#X_test = test.ix[:,1:]
X_test = test.ix[:9,1:]
X_test.fillna(-1, inplace=True)
print "predict RandomForest Classifier..."
probs = cforest.predict_proba(X_test)
sorted_index = np.argsort(-np.array(probs))[:,:5]
result = pd.DataFrame(columns = {'hotel_cluster'})
result['hotel_cluster'] = np.array([np.array_str(sorted_index[i])[1:-1] for i in range(sorted_index.shape[0])])
result.hotel_cluster.to_csv(utils.model_path +
'results/submission_rf_all_without_time_' + parameter_str + '.csv', header=True, index_label='id')
|
[API][Promotion] Index coupons only for requested promotion | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Promotion\Repository;
use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Promotion\Model\PromotionCouponInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
/**
* @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
*/
interface PromotionCouponRepositoryInterface extends RepositoryInterface
{
/**
* @param mixed $promotionId
*
* @return QueryBuilder
*/
public function createQueryBuilderByPromotionId($promotionId): QueryBuilder;
/**
* @param int $codeLength
*
* @return int
*/
public function countByCodeLength(int $codeLength): int;
/**
* @param string $code
* @param string $promotionCode
*
* @return PromotionCouponInterface|null
*/
public function findOneByCodeAndPromotionCode(string $code, string $promotionCode): ?PromotionCouponInterface;
/**
* @param string $promotionCode
*
* @return iterable
*/
public function findByPromotionCode(string $promotionCode): iterable;
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Promotion\Repository;
use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Promotion\Model\PromotionCouponInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
/**
* @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
*/
interface PromotionCouponRepositoryInterface extends RepositoryInterface
{
/**
* @param mixed $promotionId
*
* @return QueryBuilder
*/
public function createQueryBuilderByPromotionId($promotionId): QueryBuilder;
/**
* @param int $codeLength
*
* @return int
*/
public function countByCodeLength(int $codeLength): int;
/**
* @param string $code
* @param string $promotionCode
*
* @return PromotionCouponInterface|null
*/
public function findOneByCodeAndPromotionCode(string $code, string $promotionCode): ?PromotionCouponInterface;
}
|
Update the background printer widget to handle the new system | // command: 'cat ./stolaf-base/printer-data-url.txt | xargs curl --silent',
command: 'bash ./stolaf-base/snmpGet.sh',
refreshFrequency: 60000,
lastUpdateTime: undefined,
style: [
"bottom: 0",
"left: 75%",
"width: 25%",
"text-align: center",
"border: 0",
"height: 3%",
"vertical-align: middle",
"color: rgba(255, 255, 255, 0.5)",
"font-weight: 300",
].join('\n'),
render: function(argument) {
return 'Printers: <span class="last-updated"></span>';
},
update: function(output, domEl) {
if (!window.sto) return '';
if (!window.sto.libs.csv) return '';
if (!window.sto.libs.moment) return '';
var csv = window.sto.libs.csv;
var moment = window.sto.libs.moment;
window.sto.data.printers = csv.parse(output, {header: true, cast: ['String', 'String', 'String', 'String']});;
this.lastUpdateTime = new Date();
domEl.querySelector('.last-updated').textContent = moment(this.lastUpdateTime).calendar();
},
| // command: 'cat ./stolaf-base/printer-data-url.txt | xargs curl --silent',
command: 'cat ./stolaf-base/printerstatus.csv',
refreshFrequency: 60000,
lastUpdateTime: undefined,
style: [
"bottom: 0",
"left: 75%",
"width: 25%",
"text-align: center",
"border: 0",
"height: 3%",
"vertical-align: middle",
"color: rgba(255, 255, 255, 0.5)",
"font-weight: 300",
].join('\n'),
render: function(argument) {
return 'Printers: <span class="last-updated"></span>';
},
update: function(output, domEl) {
if (!window.sto) return '';
if (!window.sto.libs.csv) return '';
if (!window.sto.libs.moment) return '';
var csv = window.sto.libs.csv;
var moment = window.sto.libs.moment;
window.sto.data.printers = csv.parse(output, {header: true, cast: ['String', 'String', 'String']});;
this.lastUpdateTime = new Date();
domEl.querySelector('.last-updated').textContent = moment(this.lastUpdateTime).calendar();
},
|
Make NavigationTree expand by default | package devopsdistilled.operp.client.main;
import javax.inject.Inject;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import devopsdistilled.operp.client.abstracts.TaskPane;
import devopsdistilled.operp.client.abstracts.ViewPane;
public class NavigationPane extends ViewPane implements TreeSelectionListener {
@Inject
private NavigationTree navigationTree;
@Inject
private MainWindow mainWindow;
@Override
public JComponent getPane() {
navigationTree.getTree().expandRow(0);
navigationTree.setListener(this);
return new JScrollPane(navigationTree.getTree());
}
@Override
public void valueChanged(TreeSelectionEvent event) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) event
.getPath().getLastPathComponent();
DefaultMutableTreeNode prevNode = (DefaultMutableTreeNode) event
.getOldLeadSelectionPath().getLastPathComponent();
TaskPane newTaskPane = (TaskPane) selectedNode.getUserObject();
TaskPane oldTaskPane = (TaskPane) prevNode.getUserObject();
mainWindow.getController().changeTaskPane(newTaskPane, oldTaskPane);
}
}
| package devopsdistilled.operp.client.main;
import javax.inject.Inject;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import devopsdistilled.operp.client.abstracts.TaskPane;
import devopsdistilled.operp.client.abstracts.ViewPane;
public class NavigationPane extends ViewPane implements TreeSelectionListener {
@Inject
private NavigationTree navigationTree;
@Inject
private MainWindow mainWindow;
@Override
public JComponent getPane() {
navigationTree.setListener(this);
return new JScrollPane(navigationTree.getTree());
}
@Override
public void valueChanged(TreeSelectionEvent event) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) event
.getPath().getLastPathComponent();
DefaultMutableTreeNode prevNode = (DefaultMutableTreeNode) event
.getOldLeadSelectionPath().getLastPathComponent();
TaskPane newTaskPane = (TaskPane) selectedNode.getUserObject();
TaskPane oldTaskPane = (TaskPane) prevNode.getUserObject();
mainWindow.getController().changeTaskPane(newTaskPane, oldTaskPane);
}
}
|
test: Check handling duplicate key for instance links | """Verifies that instance_links are being retrieved properly from LINKS. Verifies that app_data.json.j2
contains the instance link information"""
from unittest import mock
from foremast.plugin_manager import PluginManager
MANAGER = PluginManager('app', 'aws')
PLUGIN = MANAGER.load()
@mock.patch('foremast.app.aws.base.LINKS', new={'example1': 'https://example1.com'})
def test_default_instance_links():
"""Validate default instance_links are being populated properly."""
pipeline_config = {
"instance_links": {
"example2": "https://example2.com",
}
}
combined = {'example1': 'https://example1.com'}
combined.update(pipeline_config['instance_links'])
spinnaker_app = PLUGIN.SpinnakerApp(pipeline_config=pipeline_config)
instance_links = spinnaker_app.retrieve_instance_links()
assert instance_links == combined, "Instance Links are not being retrieved properly"
@mock.patch('foremast.app.aws.base.LINKS', new={'example': 'example1', 'example': 'example2'})
def test_duplicate_instance_links():
"""Validate behavior when two keys are identical."""
pipeline_config = {
"instance_links": {}
}
duplicate = {'example': 'example2'}
spinnaker_app = PLUGIN.SpinnakerApp(pipeline_config=pipeline_config)
instance_links = spinnaker_app.retrieve_instance_links()
assert instance_links == duplicate, "Instance links handing duplicates are wrong."
| """Verifies that instance_links are being retrieved properly from LINKS. Verifies that app_data.json.j2
contains the instance link information"""
from unittest import mock
from foremast.plugin_manager import PluginManager
MANAGER = PluginManager('app', 'aws')
PLUGIN = MANAGER.load()
@mock.patch('foremast.app.aws.base.LINKS', new={'example1': 'https://example1.com'})
def test_default_instance_links():
"""Validate default instance_links are being populated properly."""
pipeline_config = {
"instance_links": {
"example2": "https://example2.com",
}
}
combined = {'example1': 'https://example1.com'}
combined.update(pipeline_config['instance_links'])
spinnaker_app = PLUGIN.SpinnakerApp(pipeline_config=pipeline_config)
instance_links = spinnaker_app.retrieve_instance_links()
assert instance_links == combined, "Instance Links are not being retrieved properly"
|
Make sure expression operator precedence is correct | #
# Copyright (C) 2014-2017 S[&]T, The Netherlands.
#
from __future__ import absolute_import, division, print_function
import logging
import muninn
from .utils import create_parser, parse_args_and_run
def pull(args):
with muninn.open(args.archive) as archive:
verify_hash = True if args.verify_hash else False
# find all remote products that satisfy filter
expression = "is_defined(remote_url) and not is_defined(archive_path)"
if args.expression:
expression = "%s and (%s)" % (expression, args.expression)
logging.debug('Going to pull products that match: %s', expression)
num_products = archive.pull(expression, verify_hash=verify_hash)
logging.debug('Pulled %d product(s)', num_products)
return 0
def main():
parser = create_parser(description="Pull remote files into the archive.")
parser.add_argument("--verify-hash", action="store_true",
help="verify the hash of the product after it has been put in the archive")
parser.add_argument("archive", metavar="ARCHIVE", help="identifier of the archive to use")
parser.add_argument("expression", metavar="EXPRESSION", help="expression to filter products to pull")
return parse_args_and_run(parser, pull)
| #
# Copyright (C) 2014-2017 S[&]T, The Netherlands.
#
from __future__ import absolute_import, division, print_function
import logging
import muninn
from .utils import create_parser, parse_args_and_run
def pull(args):
with muninn.open(args.archive) as archive:
verify_hash = True if args.verify_hash else False
# find all remote products that satisfy filter
expression = "(is_defined(remote_url) and not is_defined(archive_path))"
if args.expression:
expression = "%s and %s" % (expression, args.expression)
num_products = archive.pull(expression, verify_hash=verify_hash)
logging.debug('Pulled %d products', num_products)
return 0
def main():
parser = create_parser(description="Pull remote files into the archive.")
parser.add_argument("--verify-hash", action="store_true",
help="verify the hash of the product after it has been put in the archive")
parser.add_argument("archive", metavar="ARCHIVE", help="identifier of the archive to use")
parser.add_argument("expression", metavar="EXPRESSION", help="expression to filter products to pull")
return parse_args_and_run(parser, pull)
|
Use fafault values as a constats | package kfs.springutils;
import java.io.IOException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* @author pavedrim
*/
public class RunApp {
public static String defaultContextFile = "appContext.xml";
public static String defaultPidFilePropertyName = "pidfile";
public static void run(String profileName) {
run(profileName, defaultPidFilePropertyName, defaultContextFile);
}
public static void run(String profileName, String pidPropertyFilename, String contextFile) {
if (pidPropertyFilename != null) {
String pidf = System.getProperty(pidPropertyFilename);
if ((pidf != null) && !pidf.isEmpty()) {
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "echo $PPID > " + pidf);
try {
Process p = pb.start();
} catch (IOException e) {
}
}
}
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
ctx.setConfigLocation(contextFile);
ctx.getEnvironment().setActiveProfiles(profileName);
ctx.refresh();
}
}
| package kfs.springutils;
import java.io.IOException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* @author pavedrim
*/
public class RunApp {
public static void run(String profileName) {
run(profileName, "pidfile", "appContext.xml");
}
public static void run(String profileName, String pidPropertyFilename, String contextFile) {
if (pidPropertyFilename != null) {
String pidf = System.getProperty(pidPropertyFilename);
if ((pidf != null) && !pidf.isEmpty()) {
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "echo $PPID > " + pidf);
try {
Process p = pb.start();
} catch (IOException e) {
}
}
}
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
ctx.setConfigLocation(contextFile);
ctx.getEnvironment().setActiveProfiles(profileName);
ctx.refresh();
}
}
|
Fix: Add type id attribute in modeling | package sizebay.catalog.client.model;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.*;
@Getter
@Setter
public class Modeling {
private Long id;
private String name;
private Gender gender;
private String gMerchantBrandName;
private String gMerchantAgeGroup;
private String gMerchantSizeType;
private TypeEnum type;
private Long brandId;
private Long categoryId;
private List<ModelingSizeMeasures> measures = new ArrayList<>();
private Integer strongCategoryTypeId;
private String strongCategoryTypeName;
@Getter
@RequiredArgsConstructor
public enum TypeEnum {
PRODUCT("product"),
BODY("body");
final private String value;
@Override
@JsonValue
public String toString() {
return value;
}
}
@Getter
@RequiredArgsConstructor
public enum Gender {
M("M"), F("F"), U("U");
final private String value;
@Override
@JsonValue
public String toString() {
return value;
}
}
}
| package sizebay.catalog.client.model;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.*;
@Getter
@Setter
public class Modeling {
private Long id;
private String name;
private Gender gender;
private String gMerchantBrandName;
private String gMerchantAgeGroup;
private String gMerchantSizeType;
private TypeEnum type;
private Long brandId;
private Long categoryId;
private List<ModelingSizeMeasures> measures = new ArrayList<>();
@Getter
@RequiredArgsConstructor
public enum TypeEnum {
PRODUCT("product"),
BODY("body");
final private String value;
@Override
@JsonValue
public String toString() {
return value;
}
}
@Getter
@RequiredArgsConstructor
public enum Gender {
M("M"), F("F"), U("U");
final private String value;
@Override
@JsonValue
public String toString() {
return value;
}
}
}
|
Revert "Make SFC test a python call to main()"
This reverts commit d5820bef80ea4bdb871380dbfe41db12290fc5f8.
Robot test runs before SFC test and it imports
https://github.com/robotframework/SSHLibrary
which does a monkey patching in
the python runtime / paramiko.
Untill now sfc run in a new python process (clean)
because it run using the bash command.
But when importing it as a module and call main()
from python, it will run in the patched runtime
and it will error out.
https://hastebin.com/iyobuxutib.py
Change-Id: I54237c32c957718b363d302efe84e01bc78e4f47
Signed-off-by: George Paraskevopoulos <97fa9f4b61869a8ee92863df90135c882f7b3aa0@intracom-telecom.com> | #!/usr/bin/python
#
# Copyright (c) 2016 All rights reserved
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import functest.core.feature_base as base
class OpenDaylightSFC(base.FeatureBase):
def __init__(self):
super(OpenDaylightSFC, self).__init__(project='sfc',
case='functest-odl-sfc',
repo='dir_repo_sfc')
dir_sfc_functest = '{}/sfc/tests/functest'.format(self.repo)
self.cmd = 'cd %s && python ./run_tests.py' % dir_sfc_functest
| #!/usr/bin/python
#
# Copyright (c) 2016 All rights reserved
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import functest.core.feature_base as base
from sfc.tests.functest import run_tests
class OpenDaylightSFC(base.FeatureBase):
def __init__(self):
super(OpenDaylightSFC, self).__init__(project='sfc',
case='functest-odl-sfc',
repo='dir_repo_sfc')
def execute(self):
return run_tests.main()
|
Fix ToolbarIcon does not trigger onClick | import React from 'react';
import PropTypes from 'prop-types';
export default class QuillDynamicToolbarIcon extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick() {
const { onClick } = this.props;
if (onClick) onClick();
}
render() {
const { icon } = this.props;
if (React.isValidElement(icon)) {
return (
<button onClick={this.onClick}>
{icon}
</button>
);
}
return (
<button className={`ql_${icon}`} onClick={this.onClick}>
<span>
{icon.toUpperCase()}
</span>
</button>
);
}
}
QuillDynamicToolbarIcon.propTypes = {
icon: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element
]),
onClick: PropTypes.func
};
QuillDynamicToolbarIcon.defaultProps = {
icon: <span />,
onClick: null
};
| import React from 'react';
import PropTypes from 'prop-types';
export default class QuillDynamicToolbarIcon extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick() {
const { onClick } = this.props;
if (onClick) onClick();
}
render() {
const { icon } = this.props;
if (React.isValidElement(icon)) {
return (
<button onClick={this.onClick}>
{icon}
</button>
);
}
return (
<button className={`ql_${icon}`}>
<span>
{icon.toUpperCase()}
</span>
</button>
);
}
}
QuillDynamicToolbarIcon.propTypes = {
icon: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element
]),
onClick: PropTypes.func
};
QuillDynamicToolbarIcon.defaultProps = {
icon: <span />,
onClick: null
};
|
[FIX] mass_mailing_partner: Add sudo() to prevent user without mailing access try to merge contacts | # Copyright 2020 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models
class BasePartnerMergeAutomaticWizard(models.TransientModel):
_inherit = "base.partner.merge.automatic.wizard"
def _merge(self, partner_ids, dst_partner=None, extra_checks=True):
if dst_partner:
contacts = (
self.env["mailing.contact"]
.sudo()
.search([("partner_id", "in", partner_ids)])
)
if contacts:
contacts = contacts.sorted(
lambda x: 1 if x.partner_id == dst_partner else 0
)
list_ids = contacts.mapped("list_ids").ids
contacts[1:].unlink()
contacts[0].partner_id = dst_partner
contacts[0].list_ids = [(4, x) for x in list_ids]
return super()._merge(
partner_ids, dst_partner=dst_partner, extra_checks=extra_checks
)
| # Copyright 2020 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models
class BasePartnerMergeAutomaticWizard(models.TransientModel):
_inherit = "base.partner.merge.automatic.wizard"
def _merge(self, partner_ids, dst_partner=None, extra_checks=True):
if dst_partner:
contacts = self.env["mailing.contact"].search(
[("partner_id", "in", partner_ids)]
)
if contacts:
contacts = contacts.sorted(
lambda x: 1 if x.partner_id == dst_partner else 0
)
list_ids = contacts.mapped("list_ids").ids
contacts[1:].unlink()
contacts[0].partner_id = dst_partner
contacts[0].list_ids = [(4, x) for x in list_ids]
return super()._merge(
partner_ids, dst_partner=dst_partner, extra_checks=extra_checks
)
|
Include Aspell JavaScript in initial load to save extra request | //= requires "editor"
/*
* Includes the Aspell plugin (kindly ported from FCKeditor by Christian
* Boisjoli) which provides spell checking without relying on any
* browser plugins or third-party web services.
*
* Note: you must add this to the toolbar as 'SpellCheck' rather than
* the usual 'SpellChecker' in order to use it.
*
* The plugin can be configured in config/ckeditor.php:
* aspell.language sets which dictionary to use - by default it uses
* Kohana's locale configuration
* aspell.program sets the path to the Aspell executable with sensible
* defaults for both Windows and Linux
*
* Details on where to obtain the original plugin code are in:
* vendor/ckplugins/aspell/aspell.txt
*/
//= requires "<?php echo substr(Kohana::find_file('vendor', 'ckplugins/aspell/plugin', TRUE, 'js'), 0, -3);?>"
CKEDITOR.plugins.addExternal('aspell', "<?php echo url::site('assets/ckplugins/aspell');?>/");
CKEDITOR.config.extraPlugins = (CKEDITOR.config.extraPlugins ? (CKEDITOR.config.extraPlugins + ',') : '' ) + 'aspell';
| //= requires "editor"
/*
* Includes the Aspell plugin (kindly ported from FCKeditor by Christian
* Boisjoli) which provides spell checking without relying on any
* browser plugins or third-party web services.
*
* Note: you must add this to the toolbar as 'SpellCheck' rather than
* the usual 'SpellChecker' in order to use it.
*
* The plugin can be configured in config/ckeditor.php:
* aspell.language sets which dictionary to use - by default it uses
* Kohana's locale configuration
* aspell.program sets the path to the Aspell executable with sensible
* defaults for both Windows and Linux
*
* Details on where to obtain the original plugin code are in:
* vendor/ckplugins/aspell/aspell.txt
*/
CKEDITOR.plugins.addExternal('aspell', "<?php echo url::site('assets/ckplugins/aspell');?>/");
CKEDITOR.config.extraPlugins = (CKEDITOR.config.extraPlugins ? (CKEDITOR.config.extraPlugins + ',') : '' ) + 'aspell';
|
Convert string concat to template string | import * as Pluggable from "../../pluggable";
import resolve from "../../resolve";
const createModule = Pluggable.sync(function createModule (overrides) {
return Object.assign({
path: null,
ns: null,
nsPath: null,
nsRoot: null,
rawSource: null,
ast: null,
requireNodes: null,
dependencies: null,
hash: null
}, overrides);
});
const preresolve = Pluggable.sync(function preresolve (requireStr) {
return requireStr;
});
function resolveModule (requireStr, contextPath, ns, nsRoot) {
contextPath = contextPath || this.opts.root;
requireStr = this.preresolve(requireStr, contextPath);
const resolved = resolve(
requireStr,
contextPath || this.opts.root,
ns || this.opts.ns,
nsRoot || this.opts.root,
this.opts.extensions
);
if (!resolved) {
throw new Error(`Cannot resolve ${requireStr} from ${contextPath}.`);
}
return this.createModule(resolved);
}
export default Pluggable.sync(resolveModule, { preresolve, createModule });
| import * as Pluggable from "../../pluggable";
import resolve from "../../resolve";
const createModule = Pluggable.sync(function createModule (overrides) {
return Object.assign({
path: null,
ns: null,
nsPath: null,
nsRoot: null,
rawSource: null,
ast: null,
requireNodes: null,
dependencies: null,
hash: null
}, overrides);
});
const preresolve = Pluggable.sync(function preresolve (requireStr) {
return requireStr;
});
function resolveModule (requireStr, contextPath, ns, nsRoot) {
contextPath = contextPath || this.opts.root;
requireStr = this.preresolve(requireStr, contextPath);
const resolved = resolve(
requireStr,
contextPath || this.opts.root,
ns || this.opts.ns,
nsRoot || this.opts.root,
this.opts.extensions
);
if (!resolved) {
throw new Error("Cannot resolve '" + requireStr + "' from '" + contextPath + "'.");
}
return this.createModule(resolved);
}
export default Pluggable.sync(resolveModule, { preresolve, createModule });
|
Fix up pinout tests so they work with new structure | from __future__ import (
unicode_literals,
absolute_import,
print_function,
division,
)
str = type('')
import pytest
from gpiozero.cli.pinout import main
def test_args_incorrect():
with pytest.raises(SystemExit) as ex:
main(['pinout', '--nonexistentarg'])
def test_args_color():
args = main.parser.parse_args([])
assert args.color is None
args = main.parser.parse_args(['--color'])
assert args.color is True
args = main.parser.parse_args(['--monochrome'])
assert args.color is False
def test_args_revision():
args = main.parser.parse_args(['--revision', '000d'])
assert args.revision == '000d'
def test_help(capsys):
with pytest.raises(SystemExit) as ex:
main(['pinout', '--help'])
out, err = capsys.readouterr()
assert 'GPIO pinout' in out
| from __future__ import (
unicode_literals,
absolute_import,
print_function,
division,
)
str = type('')
import pytest
from gpiozero.cli import pinout
def test_args_incorrect():
with pytest.raises(SystemExit) as ex:
pinout.parse_args(['--nonexistentarg'])
def test_args_color():
args = pinout.parse_args([])
assert args.color is None
args = pinout.parse_args(['--color'])
assert args.color is True
args = pinout.parse_args(['--monochrome'])
assert args.color is False
def test_args_revision():
args = pinout.parse_args(['--revision', '000d'])
assert args.revision == '000d'
def test_help(capsys):
with pytest.raises(SystemExit) as ex:
pinout.parse_args(['--help'])
out, err = capsys.readouterr()
assert 'GPIO pinout' in out
|
Fix tests not correctly dropping plpgsql functions. | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const config = require('../../config');
// This swaps us to the test database for running test.
// TODO: Fix up configuration between different environments. Maybe use the config npm package.
config.database = {
user: process.env.DB_TEST_USER || process.env.DB_USER,
database: process.env.DB_TEST_DATABASE,
password: process.env.DB_TEST_PASSWORD || process.env.DB_PASSWORD,
host: process.env.DB_TEST_HOST || process.env.DB_HOST,
port: process.env.DB_TEST_PORT || process.env.DB_PORT
};
const { db, createSchema } = require('../../models/database');
function recreateDB() {
return db.none('DROP TABLE IF EXISTS readings')
.then(() => db.none('DROP TABLE IF EXISTS meters'))
.then(() => db.none('DROP TYPE IF EXISTS meter_type'))
.then(() => db.none('DROP FUNCTION IF EXISTS compressed_readings(INTEGER[], TIMESTAMP, TIMESTAMP, INTEGER);'))
.then(() => db.none('DROP FUNCTION IF EXISTS aggregate_readings(INTEGER[], INTERVAL, TIMESTAMP, TIMESTAMP);'))
.then(createSchema);
}
module.exports.recreateDB = recreateDB;
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const config = require('../../config');
// This swaps us to the test database for running test.
// TODO: Fix up configuration between different environments. Maybe use the config npm package.
config.database = {
user: process.env.DB_TEST_USER || process.env.DB_USER,
database: process.env.DB_TEST_DATABASE,
password: process.env.DB_TEST_PASSWORD || process.env.DB_PASSWORD,
host: process.env.DB_TEST_HOST || process.env.DB_HOST,
port: process.env.DB_TEST_PORT || process.env.DB_PORT
};
const { db, createSchema } = require('../../models/database');
function recreateDB() {
return db.none('DROP TABLE IF EXISTS readings')
.then(() => db.none('DROP TABLE IF EXISTS meters'))
.then(() => db.none('DROP TYPE IF EXISTS meter_type'))
.then(() => db.none('DROP FUNCTION IF EXISTS compressed_readings(INTEGER, TIMESTAMP, TIMESTAMP, INTEGER);'))
.then(() => db.none('DROP FUNCTION IF EXISTS aggregate_readings(INTEGER, TIMESTAMP, TIMESTAMP, INTEGER);'))
.then(createSchema);
}
module.exports.recreateDB = recreateDB;
|
Add function to NLP namespace | 'use strict';
/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
// MAIN //
/**
* Top-level namespace.
*
* @namespace nlp
*/
var nlp = {};
/**
* @name expandContractions
* @memberof nlp
* @readonly
* @type {Function}
* @see {@link module:@stdlib/nlp/expand-contractions}
*/
setReadOnly( nlp, 'expandContractions', require( '@stdlib/nlp/expand-contractions' ) );
/**
* @name lda
* @memberof nlp
* @readonly
* @type {Function}
* @see {@link module:@stdlib/nlp/lda}
*/
setReadOnly( nlp, 'lda', require( '@stdlib/nlp/lda' ) );
/**
* @name tokenize
* @memberof nlp
* @readonly
* @type {Function}
* @see {@link module:@stdlib/nlp/tokenize}
*/
setReadOnly( nlp, 'tokenize', require( '@stdlib/nlp/tokenize' ) );
// EXPORTS //
module.exports = nlp;
| 'use strict';
/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
// MAIN //
/**
* Top-level namespace.
*
* @namespace nlp
*/
var nlp = {};
/**
* @name lda
* @memberof nlp
* @readonly
* @type {Function}
* @see {@link module:@stdlib/nlp/lda}
*/
setReadOnly( nlp, 'lda', require( '@stdlib/nlp/lda' ) );
/**
* @name tokenize
* @memberof nlp
* @readonly
* @type {Function}
* @see {@link module:@stdlib/nlp/tokenize}
*/
setReadOnly( nlp, 'tokenize', require( '@stdlib/nlp/tokenize' ) );
// EXPORTS //
module.exports = nlp;
|
Fix : functional tests fail with 404 error | <?php
use Illuminate\Support\Facades\Artisan;
class TestCase extends Illuminate\Foundation\Testing\TestCase
{
/**
* The base URL to use while testing the application.
*
* @var string
*/
protected $baseUrl = 'http://localhost:8000';
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication() {
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
return $app;
}
public function setUp() {
parent::setUp();
Artisan::call('migrate');
}
protected function _userLoginIn() {
$user = factory(\App\User::class)->create();
$this->actingAs($user);
}
} | <?php
use Illuminate\Support\Facades\Artisan;
class TestCase extends Illuminate\Foundation\Testing\TestCase
{
/**
* The base URL to use while testing the application.
*
* @var string
*/
protected $baseUrl = 'http://localhost/collababor8/api';
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication() {
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
return $app;
}
public function setUp() {
parent::setUp();
Artisan::call('migrate');
}
protected function _userLoginIn() {
$user = factory(\App\User::class)->create();
$this->actingAs($user);
}
} |
Change url to get stable version number | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com>
#
from urllib2 import Request, urlopen
from distutils.version import LooseVersion
BRANCH = 'stable'
REPO = 'git@github.com:roramirez/qpanel.git'
URL_STABLE_VERSION = 'https://rodrigoramirez.com/qpanel/version/' + BRANCH
def require_upgrade():
a = LooseVersion(get_current_version())
b = LooseVersion(get_stable_version())
if a < b:
return True
return False
# InmplementME
def last_check_update():
return True
def get_current_version():
current_version = open('VERSION')
return __first_line(current_version.read())
def get_stable_version():
stable_version = __get_data_url(URL_STABLE_VERSION)
return __first_line(stable_version)
def __get_data_url(url):
req = Request(url)
try:
response = urlopen(req)
return response.read()
except:
return None
def __first_line(content):
tmp = ''
if content is not None:
tmp = content.split('\n')
if len(tmp) > 1:
return tmp[0]
return tmp
| # -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com>
#
from urllib2 import Request, urlopen
from distutils.version import LooseVersion
BRANCH = 'stable'
REPO = 'git@github.com:roramirez/qpanel.git'
URL_STABLE_VERSION = 'https://raw.githubusercontent.com/roramirez/qpanel' + \
'/%s/VERSION' % BRANCH
def require_upgrade():
a = LooseVersion(get_current_version())
b = LooseVersion(get_stable_version())
if a < b:
return True
return False
# InmplementME
def last_check_update():
return True
def get_current_version():
current_version = open('VERSION')
return __first_line(current_version.read())
def get_stable_version():
stable_version = __get_data_url(URL_STABLE_VERSION)
return __first_line(stable_version)
def __get_data_url(url):
req = Request(url)
try:
response = urlopen(req)
return response.read()
except:
return None
def __first_line(content):
tmp = ''
if content is not None:
tmp = content.split('\n')
if len(tmp) > 1:
return tmp[0]
return tmp
|
Remove 0.0 from ings line | from django.db import models
# Create your models here.
class Ingredient(models.Model):
name = models.CharField(max_length=100)
abv = models.FloatField()
type = models.CharField(max_length=25)
def __str__(self):
return self.name
class Admin:
list_display = ('name')
class Meta:
ordering = ['id']
class IngredientLine(models.Model):
ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1)
amt = models.FloatField(default=0)
def __str__(self):
if self.amt == 0:
return self.ing.name
return "{} ounces of {}".format(str(self.amt), self.ing.name)
class Drink(models.Model):
name = models.CharField(max_length=100)
owner = models.ForeignKey('auth.User', related_name='drinks')
ings = models.ManyToManyField(IngredientLine)
instructions = models.TextField()
def __str__(self):
return self.name
| from django.db import models
# Create your models here.
class Ingredient(models.Model):
name = models.CharField(max_length=100)
abv = models.FloatField()
type = models.CharField(max_length=25)
def __str__(self):
return self.name
class Admin:
list_display = ('name')
class Meta:
ordering = ['id']
class IngredientLine(models.Model):
ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1)
amt = models.FloatField(default=0)
def __str__(self):
return "{} ounces of {}".format(str(self.amt), self.ing.name)
class Drink(models.Model):
name = models.CharField(max_length=100)
owner = models.ForeignKey('auth.User', related_name='drinks')
ings = models.ManyToManyField(IngredientLine)
instructions = models.TextField()
def __str__(self):
return self.name
|
Increment the max length of random strings. | #!/usr/bin/env python
from fastcomp import compare
import random
import string
def randomstr(minlen=5, maxlen=8):
charset = '01'
length = random.randint(minlen, maxlen)
return ''.join(random.choice(charset) for i in range(length))
if __name__ == "__main__":
import timeit
# Set up conditions
setup = """
from __main__ import compare, randomstr
cases = [(randomstr(), randomstr()) for x in range(1000)]"""
main = "for case in cases: compare(*case)"
loops = 100
# Run timeit
timer = timeit.Timer(main, setup=setup)
result = timer.repeat(number=loops)
# Result
best = round(min(result)*1000/loops, 2)
print('{} loops, best of 3: {} msec per loop'.format(loops, best))
| #!/usr/bin/env python
from fastcomp import compare
import random
import string
def randomstr(minlen=5, maxlen=7):
charset = '01'
length = random.randint(minlen, maxlen)
return ''.join(random.choice(charset) for i in range(length))
if __name__ == "__main__":
import timeit
# Set up conditions
setup = """
from __main__ import compare, randomstr
cases = [(randomstr(), randomstr()) for x in range(1000)]"""
main = "for case in cases: compare(*case)"
loops = 100
# Run timeit
timer = timeit.Timer(main, setup=setup)
result = timer.repeat(number=loops)
# Result
best = round(min(result)*1000/loops, 2)
print('{} loops, best of 3: {} msec per loop'.format(loops, best))
|
Use etc relative to sys.prefix | import os
import sys
try:
import pkg_resources
d = pkg_resources.get_distribution('metermaid')
pkg_locations = (
os.path.join(d.location, 'config'),
os.path.join(os.path.dirname(d.location), 'config'),
)
except ImportError:
pkg_locations = ()
def get_config_paths(filename=None):
script_name = os.path.basename(sys.argv[0])
for dirpath in pkg_locations + (
os.path.join(sys.prefix, 'config'),
os.path.join(sys.prefix, 'etc', script_name),
os.path.expanduser('~/.{}'.format(script_name)),
):
full_path = dirpath
if filename:
full_path = os.path.join(full_path, filename)
yield full_path
| import os
import sys
try:
import pkg_resources
d = pkg_resources.get_distribution('metermaid')
pkg_locations = (
os.path.join(d.location, 'config'),
os.path.join(os.path.dirname(d.location), 'config'),
)
except ImportError:
pkg_locations = ()
def get_config_paths(filename=None):
script_name = os.path.basename(sys.argv[0])
for dirpath in pkg_locations + (
os.path.join(sys.prefix, 'config'),
'/etc/{}'.format(script_name),
os.path.expanduser('~/.{}'.format(script_name)),
):
full_path = dirpath
if filename:
full_path = os.path.join(full_path, filename)
yield full_path
|
Add 'getDataTable' function from old template. | function applyChanges(data, url, showResult) {
var success = false;
$.ajax({
type : "POST",
url : url,
data : JSON.stringify(data),// now data come in this function
contentType : "application/json; charset=utf-8",
crossDomain : true,
dataType : "json",
success : function(data, status, jqXHR) {
console.log("Applied changes successfully.")
if (showResult) {
var modal = $("#modal_success");
modal.find('.modal-body p').text("Applied changes successfully");
modal.modal('show');
}
},
error : function(jqXHR, status) {
console.log(jqXHR);
var modal = $("#modal_error");
modal.find('.modal-body p').text(jqXHR["responseText"]);
modal.modal('show');
}
});
}
function getTableData(table) {
var rData = []
// reformat - pretty format
var records = []
table.rows().every(function() {
var r = this.data();
var record = {}
record["record_name"] = r[0].trim();
record["record_type"] = r[1].trim();
record["record_status"] = r[2].trim();
record["record_ttl"] = r[3].trim();
record["record_data"] = r[4].trim();
records.push(record);
});
return records
} | function applyChanges(data, url, showResult) {
var success = false;
$.ajax({
type : "POST",
url : url,
data : JSON.stringify(data),// now data come in this function
contentType : "application/json; charset=utf-8",
crossDomain : true,
dataType : "json",
success : function(data, status, jqXHR) {
console.log("Applied changes successfully.")
if (showResult) {
var modal = $("#modal_success");
modal.find('.modal-body p').text("Applied changes successfully");
modal.modal('show');
}
},
error : function(jqXHR, status) {
console.log(jqXHR);
var modal = $("#modal_error");
modal.find('.modal-body p').text(jqXHR["responseText"]);
modal.modal('show');
}
});
} |
Upgrade tangled from 0.1a5 to 0.1a8 | from setuptools import setup
setup(
name='tangled.contrib',
version='0.1a4.dev0',
description='Tangled namespace for contributed packages',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.contrib/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.contrib',
'tangled.contrib.scaffolds',
'tangled.contrib.tests',
],
include_package_data=True,
install_requires=[
'tangled>=0.1a8',
],
extras_require={
'dev': [
'tangled[dev]>=0.1a8',
],
},
entry_points="""
[tangled.scaffolds]
contrib = tangled.contrib.scaffolds:default
contrib-core = tangled.contrib.scaffolds:core
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| from setuptools import setup
setup(
name='tangled.contrib',
version='0.1a4.dev0',
description='Tangled namespace for contributed packages',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.contrib/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.contrib',
'tangled.contrib.scaffolds',
'tangled.contrib.tests',
],
include_package_data=True,
install_requires=[
'tangled>=0.1a5',
],
extras_require={
'dev': [
'tangled[dev]>=0.1a5',
],
},
entry_points="""
[tangled.scaffolds]
contrib = tangled.contrib.scaffolds:default
contrib-core = tangled.contrib.scaffolds:core
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.