text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix documentation error. Added link to Example | @extends ('layouts.master')
@section('meta_title') Documentation @stop
@section('content')
<h3>General Information</h3>
<p>Before you start, please be aware of the following rules</p>
<ol>
<li>You must have an API Key to create Screenshots</li>
<li><strong>Your screenshots will be removed after 12 hours of their creation.</strong></li>
</ol>
<h3>Do API Request</h3>
<p>For a simple request, just send a POST-Request to <code>http://screeenly.com/api/v1/fullsize</code>. The API will then take a screenshot of the given URL width a with of 1024 pixels. The height of the screenshot is 100%.</p>
<p><a href="https://gist.github.com/stefanzweifel/968e68785277013ac214">Simple PHP CURL Example</a>.</p>
<pre>
{
"key": "YOUR_API_KEY",
"url": "http://en.wikipedia.org/"
}</pre>
<p>Return Value</p>
<pre>{
"filename": "http://screeenly.com/images/generated/FILENAME.jpg",
"base64": "ENCODED_FILE"
}</pre>
@stop | @extends ('layouts.master')
@section('meta_title') Documentation @stop
@section('content')
<h3>General Information</h3>
<p>Before you start, please be aware of the following rules</p>
<ol>
<li>You must have an API Key to create Screenshots</li>
<li><strong>Your screenshots will be removed after 12 hours of their creation.</strong></li>
</ol>
<h3>Do API Request</h3>
<p>For a simple request, just send a POST-Request to <code>http://screenly.com/api/v1/fullscreen</code>. The API will then take a screenshot of the given URL width a with of 1024 pixels. The height of the screenshot is 100%.</p>
<pre>
{
"key": "YOUR_API_KEY",
"url": "http://en.wikipedia.org/"
}</pre>
<p>Return Value</p>
<pre>{
"filename": "http://screeenly.com/images/generated/FILENAME.jpg",
"base64": "ENCODED_FILE"
}</pre>
@stop |
fix(entity-browser): Fix URL for forms fetch mock | import {utilFetchMocks} from 'tocco-util/dev'
import {createUsers} from './recordFactory'
const allRecords = createUsers(1000)
export default function setupFetchMock(fetchMock) {
utilFetchMocks.sessionFetchMock(fetchMock)
utilFetchMocks.textResourceFetchMock(fetchMock, require('./messages.json'))
fetchMock.get(new RegExp('^.*?/nice2/rest/forms/.*'), require('./user_list.json'))
fetchMock.get(new RegExp('^.*?/nice2/rest/entities/.*/count$'), {'count': 1000})
fetchMock.get(new RegExp('^.*?/nice2/rest/entities/.*'), (url, opts) => {
console.log('fetchMock: called fetch entites', url)
const limit = parseInt(getParameterByName('_limit', url))
const offset = parseInt(getParameterByName('_offset', url))
return wrapResponse(allRecords.slice(offset, offset + limit))
})
fetchMock.spy()
}
const wrapResponse = records => ({
metaData: {
modelName: 'User',
label: 'Person'
},
data: records
})
const getParameterByName = (name, url) => {
name = name.replace(/[[\]]/g, '\\$&')
const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)')
const results = regex.exec(url)
if (!results) return null
if (!results[2]) return ''
return decodeURIComponent(results[2].replace(/\+/g, ' '))
}
| import {utilFetchMocks} from 'tocco-util/dev'
import {createUsers} from './recordFactory'
const allRecords = createUsers(1000)
export default function setupFetchMock(fetchMock) {
utilFetchMocks.sessionFetchMock(fetchMock)
utilFetchMocks.textResourceFetchMock(fetchMock, require('./messages.json'))
fetchMock.get(new RegExp('^.*?/nice2/rest/form/.*'), require('./user_list.json'))
fetchMock.get(new RegExp('^.*?/nice2/rest/entities/.*/count$'), {'count': 1000})
fetchMock.get(new RegExp('^.*?/nice2/rest/entities/.*'), (url, opts) => {
console.log('fetchMock: called fetch entites', url)
const limit = parseInt(getParameterByName('_limit', url))
const offset = parseInt(getParameterByName('_offset', url))
return wrapResponse(allRecords.slice(offset, offset + limit))
})
fetchMock.spy()
}
const wrapResponse = records => ({
metaData: {
modelName: 'User',
label: 'Person'
},
data: records
})
const getParameterByName = (name, url) => {
name = name.replace(/[[\]]/g, '\\$&')
const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)')
const results = regex.exec(url)
if (!results) return null
if (!results[2]) return ''
return decodeURIComponent(results[2].replace(/\+/g, ' '))
}
|
Update admin js for new admin UX | import { extend } from 'flarum/extend';
import app from 'flarum/app';
app.initializers.add('flarum-approval', () => {
extend(app, 'getRequiredPermissions', function (required, permission) {
if (permission === 'discussion.startWithoutApproval') {
required.push('startDiscussion');
}
if (permission === 'discussion.replyWithoutApproval') {
required.push('discussion.reply');
}
});
app.extensionData
.for('flarum-approval')
.registerPermission({
icon: 'fas fa-check',
label: app.translator.trans('flarum-approval.admin.permissions.start_discussions_without_approval_label'),
permission: 'discussion.startWithoutApproval'
}, 'start', 95)
.registerPermission({
icon: 'fas fa-check',
label: app.translator.trans('flarum-approval.admin.permissions.reply_without_approval_label'),
permission: 'discussion.replyWithoutApproval'
}, 'reply', 95)
.registerPermission({
icon: 'fas fa-check',
label: app.translator.trans('flarum-approval.admin.permissions.approve_posts_label'),
permission: 'discussion.approvePosts'
}, 'moderate', 65);
});
| import { extend } from 'flarum/extend';
import app from 'flarum/app';
import PermissionGrid from 'flarum/components/PermissionGrid';
app.initializers.add('flarum-approval', () => {
extend(app, 'getRequiredPermissions', function(required, permission) {
if (permission === 'discussion.startWithoutApproval') {
required.push('startDiscussion');
}
if (permission === 'discussion.replyWithoutApproval') {
required.push('discussion.reply');
}
});
extend(PermissionGrid.prototype, 'startItems', items => {
items.add('startDiscussionsWithoutApproval', {
icon: 'fas fa-check',
label: app.translator.trans('flarum-approval.admin.permissions.start_discussions_without_approval_label'),
permission: 'discussion.startWithoutApproval'
}, 95);
});
extend(PermissionGrid.prototype, 'replyItems', items => {
items.add('replyWithoutApproval', {
icon: 'fas fa-check',
label: app.translator.trans('flarum-approval.admin.permissions.reply_without_approval_label'),
permission: 'discussion.replyWithoutApproval'
}, 95);
});
extend(PermissionGrid.prototype, 'moderateItems', items => {
items.add('approvePosts', {
icon: 'fas fa-check',
label: app.translator.trans('flarum-approval.admin.permissions.approve_posts_label'),
permission: 'discussion.approvePosts'
}, 65);
});
});
|
Add excerpt to the story factor & add category factory | import 'babel-polyfill';
import sinon from 'sinon';
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
import factory from 'fixture-factory';
chai.use(chaiEnzyme());
global.chai = chai;
global.sinon = sinon;
global.expect = chai.expect;
global.should = chai.should();
/**
* Register the story as factory model.
*/
factory.register('story', {
id: 'random.number',
title: 'random.words',
excerpt: 'random.words',
body: 'random.words',
liked: false,
author: {
name: 'random.words',
},
created_at: 'date.recent.value',
});
factory.register('category', {
id: 'random.number',
name: 'random.word',
});
const __karmaWebpackManifest__ = [];
// Include all .js files under `app`, except app.js, reducers.js, routes.js and
// store.js. This is for isparta code coverage
const context = require.context(
'../../src/app',
true,
/^^((?!(client|server)).)*\.js$/
);
function inManifest(path) {
return __karmaWebpackManifest__.indexOf(path) >= 0;
}
let runnable = context.keys().filter(inManifest);
// Run all tests if we didn't find any changes
if (!runnable.length) {
runnable = context.keys();
}
runnable.forEach(context);
| import 'babel-polyfill';
import sinon from 'sinon';
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
import factory from 'fixture-factory';
chai.use(chaiEnzyme());
global.chai = chai;
global.sinon = sinon;
global.expect = chai.expect;
global.should = chai.should();
/**
* Register the story as factory model.
*/
factory.register('story', {
id: 'random.number',
title: 'random.words',
body: 'random.words',
liked: false,
author: {
name: 'random.words',
},
});
const __karmaWebpackManifest__ = [];
// Include all .js files under `app`, except app.js, reducers.js, routes.js and
// store.js. This is for isparta code coverage
const context = require.context(
'../../src/app',
true,
/^^((?!(client|server)).)*\.js$/
);
function inManifest(path) {
return __karmaWebpackManifest__.indexOf(path) >= 0;
}
let runnable = context.keys().filter(inManifest);
// Run all tests if we didn't find any changes
if (!runnable.length) {
runnable = context.keys();
}
runnable.forEach(context);
|
Remove --dev from composer install.
--dev is the default. | #!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
require 'vendor/autoload.php';
$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array(
'standard' => array(__DIR__ . '/vendor/dominionenterprises/dws-coding-standard/DWS'),
'files' => array('src', 'tests', 'build.php'),
'warningSeverity' => 0,
);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
exit(1);
}
$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
exit(1);
}
$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(1);
}
echo "Code coverage was 100%\n";
| #!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
require 'vendor/autoload.php';
$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array(
'standard' => array(__DIR__ . '/vendor/dominionenterprises/dws-coding-standard/DWS'),
'files' => array('src', 'tests', 'build.php'),
'warningSeverity' => 0,
);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
exit(1);
}
$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
exit(1);
}
$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(1);
}
echo "Code coverage was 100%\n";
|
Update the rate limit repository to avoid a complex implemntation wth the rate-limiting algorithm | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.repository.ratelimit.api;
import io.gravitee.repository.ratelimit.model.RateLimit;
import java.io.Serializable;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public interface RateLimitRepository<T extends Serializable> {
RateLimit get(RateLimit rateLimit);
void save(RateLimit rateLimit);
}
| /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.repository.ratelimit.api;
import io.gravitee.repository.ratelimit.model.RateLimitResult;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public interface RateLimitRepository<T extends Serializable> {
RateLimitResult acquire(T key, int weigth, long limit, long periodTime, TimeUnit periodTimeUnit);
}
|
Change behaviour to fail on number string of length 0 (zero) | package foam.lib.json;
import foam.lib.parse.*;
public class FloatParser implements Parser {
public PStream parse(PStream ps, ParserContext x) {
StringBuilder n = new StringBuilder();
boolean decimalFound = false;
if ( ! ps.valid() ) return null;
char c = ps.head();
if ( c == '-' ) {
n.append(c);
ps = ps.tail();
if ( ! ps.valid() ) return null;
c = ps.head();
}
// Float numbers must start with a digit: 0.1, 4.0
if ( Character.isDigit(c) ) n.append(c);
else return null;
ps = ps.tail();
while ( ps.valid() ) {
c = ps.head();
if ( Character.isDigit(c) ) {
n.append(c);
} else if ( c == '.' ) { // TODO: localization
if (decimalFound) {
return null;
}
decimalFound = true;
n.append(c);
} else {
break;
}
ps = ps.tail();
}
return ps.setValue(n.length() > 0 ? Float.valueOf(n.toString()) : null);
}
}
| package foam.lib.json;
import foam.lib.parse.*;
public class FloatParser implements Parser {
public PStream parse(PStream ps, ParserContext x) {
StringBuilder n = new StringBuilder();
boolean decimalFound = false;
if ( ! ps.valid() ) return null;
char c = ps.head();
if ( c == '-' ) {
n.append(c);
ps = ps.tail();
if ( ! ps.valid() ) return null;
c = ps.head();
}
// Float numbers must start with a digit: 0.1, 4.0
if ( Character.isDigit(c) ) n.append(c);
else return null;
ps = ps.tail();
while ( ps.valid() ) {
c = ps.head();
if ( Character.isDigit(c) ) {
n.append(c);
} else if ( c == '.' ) { // TODO: localization
if (decimalFound) {
return null;
}
decimalFound = true;
n.append(c);
} else {
break;
}
ps = ps.tail();
}
return ps.setValue(n.length() > 0 ? Float.valueOf(n.toString()) : 0.0);
}
}
|
Add push task (but not use it yet) | from fabric.api import cd, env, local, lcd, run
PUPPET_MASTER_IP = '192.168.33.10'
def puppet():
env.hosts = [
'vagrant@' + PUPPET_MASTER_IP + ':22',
]
env.passwords = {
'vagrant@' + PUPPET_MASTER_IP + ':22': 'vagrant'
}
def test():
with lcd('puppet/modules'):
with lcd('nginx'):
local('rspec')
def push():
with lcd('puppet'):
local('git add .')
local('git push origin master')
def deploy():
puppet()
test()
run('rm -rf puppet-untitled-2016')
run('git clone https://github.com/zkan/puppet-untitled-2016.git')
run('sudo rm -rf /etc/puppet/manifests')
run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/manifests /etc/puppet/manifests')
run('sudo rm -rf /etc/puppet/modules')
run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/modules /etc/puppet/modules')
| from fabric.api import cd, env, local, lcd, run
PUPPET_MASTER_IP = '192.168.33.10'
def puppet():
env.hosts = [
'vagrant@' + PUPPET_MASTER_IP + ':22',
]
env.passwords = {
'vagrant@' + PUPPET_MASTER_IP + ':22': 'vagrant'
}
def test():
with lcd('puppet/modules'):
with lcd('nginx'):
local('rspec')
def deploy():
puppet()
test()
run('rm -rf puppet-untitled-2016')
run('git clone https://github.com/zkan/puppet-untitled-2016.git')
run('sudo rm -rf /etc/puppet/manifests')
run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/manifests /etc/puppet/manifests')
run('sudo rm -rf /etc/puppet/modules')
run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/modules /etc/puppet/modules')
|
Update User model to match with Auth0 data | var mongoose = require('mongoose')
var userSchema = new mongoose.Schema({
id: { type: String, index: { unique: true } },
auth0_id: String,
auth0_refesh_token: String,
login_tokens: [ String ],
data: mongoose.Schema.Types.Mixed,
created_at: Date,
updated_at: Date,
last_street_id: Number
})
userSchema.pre('save', function (next) {
var now = new Date()
this.updated_at = now
this.created_at = this.created_at || now
next()
})
userSchema.methods.asJson = function (options, cb) {
options = options || {}
var json = {
id: this.id
}
if (options.auth) {
json.data = this.data
json.createdAt = this.created_at
json.updatedAt = this.updated_at
}
cb(null, json)
}
module.exports = mongoose.model('User', userSchema)
| var mongoose = require('mongoose')
var userSchema = new mongoose.Schema({
id: { type: String, index: { unique: true } },
twitter_id: String,
twitter_credentials: mongoose.Schema.Types.Mixed,
login_tokens: [ String ],
data: mongoose.Schema.Types.Mixed,
created_at: Date,
updated_at: Date,
last_street_id: Number
})
userSchema.pre('save', function (next) {
var now = new Date()
this.updated_at = now
this.created_at = this.created_at || now
next()
})
userSchema.methods.asJson = function (options, cb) {
options = options || {}
var json = {
id: this.id
}
if (options.auth) {
json.data = this.data
json.createdAt = this.created_at
json.updatedAt = this.updated_at
}
cb(null, json)
}
module.exports = mongoose.model('User', userSchema)
|
Update wrt. new JDK 1.2 ClassLoader scheme. | class forNameTest {
public static void main(String argv[]) {
try {
Class.forName("loadThis");
Class c = Class.forName("loadThis", false,
new ClassLoader() {
public Class loadClass(String n, boolean resolve)
throws ClassNotFoundException {
Class cl = findSystemClass(n);
if (resolve) {
resolveClass(cl);
}
return cl;
}
});
System.out.println("constructor not called");
c.newInstance();
}
catch( Exception e ) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
class loadThis {
static {
try {
new loadThis();
}
catch( Exception e ) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public loadThis() {
System.out.println("constructor called");
}
}
/* Expected Output:
constructor called
constructor not called
constructor called
*/
| class forNameTest {
public static void main(String argv[]) {
try {
Class.forName("loadThis");
Class c = Class.forName("loadThis", false,
new ClassLoader() {
public Class loadClass(String n)
throws ClassNotFoundException {
return findSystemClass(n);
}
});
System.out.println("constructor not called");
c.newInstance();
}
catch( Exception e ) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
class loadThis {
static {
try {
new loadThis();
}
catch( Exception e ) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public loadThis() {
System.out.println("constructor called");
}
}
/* Expected Output:
constructor called
constructor not called
constructor called
*/
|
Revert "Add option to fail fast on parse"
This reverts commit bd4fb496e49bd8089d519cfc51d21f21e015fcf1. | package org.commcare.modern.parse;
import org.commcare.core.interfaces.UserSandbox;
import org.commcare.core.parse.ParseUtils;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.xmlpull.v1.XmlPullParserException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
/**
* Convenience methods, mostly for touchforms so we don't have to deal with Java IO
* in Jython which is terrible
*
* Used by touchforms
*
* Created by wpride1 on 8/20/15.
*/
@SuppressWarnings("unused")
public class ParseUtilsHelper extends ParseUtils {
public static void parseXMLIntoSandbox(String restore, UserSandbox sandbox)
throws InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException, IOException {
InputStream stream = new ByteArrayInputStream(restore.getBytes(StandardCharsets.UTF_8));
parseIntoSandbox(stream, sandbox);
}
public static void parseFileIntoSandbox(File restore, UserSandbox sandbox)
throws IOException, InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException {
InputStream stream = new FileInputStream(restore);
parseIntoSandbox(stream, sandbox);
}
}
| package org.commcare.modern.parse;
import org.commcare.core.interfaces.UserSandbox;
import org.commcare.core.parse.ParseUtils;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.xmlpull.v1.XmlPullParserException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
/**
* Convenience methods, mostly for touchforms so we don't have to deal with Java IO
* in Jython which is terrible
*
* Used by touchforms
*
* Created by wpride1 on 8/20/15.
*/
@SuppressWarnings("unused")
public class ParseUtilsHelper extends ParseUtils {
public static void parseXMLIntoSandbox(String restore, UserSandbox sandbox, boolean failFast)
throws InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException, IOException {
InputStream stream = new ByteArrayInputStream(restore.getBytes(StandardCharsets.UTF_8));
parseIntoSandbox(stream, sandbox, failFast);
}
public static void parseFileIntoSandbox(File restore, UserSandbox sandbox)
throws IOException, InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException {
InputStream stream = new FileInputStream(restore);
parseIntoSandbox(stream, sandbox);
}
}
|
:new: Add flow coverage help text | /* @flow */
import { CompositeDisposable } from 'atom'
export type CoverageObject = {
expressions: {
covered_count: number,
uncovered_count: number,
}
}
class CoverageView extends HTMLElement {
tooltipDisposable: CompositeDisposable|null = null;
initialize(): void {
this.classList.add('inline-block')
}
update(json: CoverageObject): void {
const covered: number = json.expressions.covered_count
const uncovered: number = json.expressions.uncovered_count
const total: number = covered + uncovered
const percent: number = Math.round((covered / total) * 100)
this.textContent = `Flow Coverage: ${percent}%`
if (this.tooltipDisposable) {
this.tooltipDisposable.dispose()
}
this.tooltipDisposable = atom.tooltips.add(this, {
title: `Covered ${percent}% (${covered} of ${total} expressions)`,
})
}
reset() {
this.textContent = ''
}
destroy(): void {
if (this.tooltipDisposable) {
this.tooltipDisposable.dispose()
}
}
}
export default document.registerElement('flow-ide-coverage', {
prototype: CoverageView.prototype,
extends: 'div',
})
| /* @flow */
import { CompositeDisposable } from 'atom'
export type CoverageObject = {
expressions: {
covered_count: number,
uncovered_count: number,
}
}
class CoverageView extends HTMLElement {
tooltipDisposable: CompositeDisposable|null = null;
initialize(): void {
this.classList.add('inline-block')
}
update(json: CoverageObject): void {
const covered: number = json.expressions.covered_count
const uncovered: number = json.expressions.uncovered_count
const total: number = covered + uncovered
const percent: number = Math.round((covered / total) * 100)
this.textContent = `${percent}%`
if (this.tooltipDisposable) {
this.tooltipDisposable.dispose()
}
this.tooltipDisposable = atom.tooltips.add(this, {
title: `Covered ${percent}% (${covered} of ${total} expressions)`,
})
}
reset() {
this.textContent = ''
}
destroy(): void {
if (this.tooltipDisposable) {
this.tooltipDisposable.dispose()
}
}
}
export default document.registerElement('flow-ide-coverage', {
prototype: CoverageView.prototype,
extends: 'div',
})
|
Add matcher for the recyclerview to get the number of items to compare with | package me.androidbox.busbymovies;
import android.support.test.espresso.assertion.ViewAssertions;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import me.androidbox.busbymovies.movielist.MovieListActivity;
import me.androidbox.busbymovies.utils.RecyclerViewAssertions;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.equalTo;
/**
* Created by steve on 2/18/17.
*/
@RunWith(AndroidJUnit4.class)
public class MovieListViewImpTest {
@Rule
public final ActivityTestRule<MovieListActivity> activityTestRule =
new ActivityTestRule<>(MovieListActivity.class);
@Test
public void shouldDisplayCorrectTitleInToolbar() {
onView(withText(R.string.app_name)).check(ViewAssertions.matches(isDisplayed()));
}
@Test
public void shouldDisplayTwentyItemsInRecyclerView() {
onView(withId(R.id.rvMovieList))
.check(new RecyclerViewAssertions(equalTo(20)));
}
}
| package me.androidbox.busbymovies;
import android.support.test.espresso.assertion.ViewAssertions;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import me.androidbox.busbymovies.movielist.MovieListActivity;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
/**
* Created by steve on 2/18/17.
*/
@RunWith(AndroidJUnit4.class)
public class MovieListViewImpTest {
@Rule
public final ActivityTestRule<MovieListActivity> activityTestRule =
new ActivityTestRule<>(MovieListActivity.class);
@Test
public void shouldDisplayCorrectTitleInToolbar() {
onView(withText(R.string.app_name)).check(ViewAssertions.matches(isDisplayed()));
}
}
|
Use a different django secret key for each test run. | # Minimum settings that are needed to run django test suite
import os
import secrets
import tempfile
SECRET_KEY = secrets.token_hex()
if "postgresql" in os.getenv("TOX_ENV_NAME", ""):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
# Should be the same defined in .travis.yml
'NAME': 'dirtyfields_test',
# postgres user is by default created in travis-ci
'USER': os.getenv('POSTGRES_USER', 'postgres'),
# postgres user has no password on travis-ci
'PASSWORD': os.getenv('POSTGRES_PASSWORD', ''),
'HOST': 'localhost',
'PORT': '5432', # default postgresql port
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'dirtyfields.db',
}
}
INSTALLED_APPS = ('tests', )
MEDIA_ROOT = tempfile.mkdtemp(prefix="django-dirtyfields-test-media-root-")
| # Minimum settings that are needed to run django test suite
import os
import tempfile
SECRET_KEY = 'WE DONT CARE ABOUT IT'
if "postgresql" in os.getenv("TOX_ENV_NAME", ""):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
# Should be the same defined in .travis.yml
'NAME': 'dirtyfields_test',
# postgres user is by default created in travis-ci
'USER': os.getenv('POSTGRES_USER', 'postgres'),
# postgres user has no password on travis-ci
'PASSWORD': os.getenv('POSTGRES_PASSWORD', ''),
'HOST': 'localhost',
'PORT': '5432', # default postgresql port
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'dirtyfields.db',
}
}
INSTALLED_APPS = ('tests', )
MEDIA_ROOT = tempfile.mkdtemp(prefix="django-dirtyfields-test-media-root-")
|
Fix Sina App domain error | package io.github.izzyleung.zhihudailypurify.support;
import java.text.SimpleDateFormat;
public final class Constants {
private Constants() {
}
public static final class Url {
public static final String ZHIHU_DAILY_BEFORE = "http://news.at.zhihu.com/api/3/news/before/";
public static final String ZHIHU_DAILY_OFFLINE_NEWS = "http://news-at.zhihu.com/api/3/news/";
public static final String ZHIHU_DAILY_PURIFY_HEROKU_BEFORE = "http://zhihu-daily-purify.herokuapp.com/raw/";
public static final String ZHIHU_DAILY_PURIFY_SAE_BEFORE = "http://zhihudailypurify.vipsinaapp.com/raw/";
public static final String SEARCH = "http://zhihudailypurify.vipsinaapp.com/search/";
}
public static final class Date {
public static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
@SuppressWarnings("deprecation")
public static final java.util.Date birthday = new java.util.Date(113, 4, 19); // May 19th, 2013
}
public static final class ServerCode {
public static final String SAE = "1";
public static final String HEROKU = "2";
}
}
| package io.github.izzyleung.zhihudailypurify.support;
import java.text.SimpleDateFormat;
public final class Constants {
private Constants() {
}
public static final class Url {
public static final String ZHIHU_DAILY_BEFORE = "http://news.at.zhihu.com/api/3/news/before/";
public static final String ZHIHU_DAILY_OFFLINE_NEWS = "http://news-at.zhihu.com/api/3/news/";
public static final String ZHIHU_DAILY_PURIFY_HEROKU_BEFORE = "http://zhihu-daily-purify.herokuapp.com/raw/";
public static final String ZHIHU_DAILY_PURIFY_SAE_BEFORE = "http://zhihudailypurify.sinaapp.com/raw/";
public static final String SEARCH = "http://zhihudailypurify.sinaapp.com/search/";
}
public static final class Date {
public static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
@SuppressWarnings("deprecation")
public static final java.util.Date birthday = new java.util.Date(113, 4, 19); // May 19th, 2013
}
public static final class ServerCode {
public static final String SAE = "1";
public static final String HEROKU = "2";
}
}
|
Mark status bar tile as read-only | module.exports =
class UpdatePackageDependenciesStatusView {
constructor (statusBar) {
this.statusBar = statusBar
this.element = document.createElement('update-package-dependencies-status')
this.element.classList.add('update-package-dependencies-status', 'inline-block', 'is-read-only')
this.spinner = document.createElement('span')
this.spinner.classList.add('loading', 'loading-spinner-tiny', 'inline-block')
this.element.appendChild(this.spinner)
}
attach () {
this.tile = this.statusBar.addRightTile({item: this.element})
this.tooltip = atom.tooltips.add(this.element, {title: 'Updating package dependencies\u2026'})
}
detach () {
if (this.tile) this.tile.destroy()
if (this.tooltip) this.tooltip.dispose()
}
}
| module.exports =
class UpdatePackageDependenciesStatusView {
constructor (statusBar) {
this.statusBar = statusBar
this.element = document.createElement('update-package-dependencies-status')
this.element.classList.add('update-package-dependencies-status', 'inline-block')
this.spinner = document.createElement('span')
this.spinner.classList.add('loading', 'loading-spinner-tiny', 'inline-block')
this.element.appendChild(this.spinner)
}
attach () {
this.tile = this.statusBar.addRightTile({item: this.element})
this.tooltip = atom.tooltips.add(this.element, {title: 'Updating package dependencies\u2026'})
}
detach () {
if (this.tile) this.tile.destroy()
if (this.tooltip) this.tooltip.dispose()
}
}
|
Switch inline styles from body to documentElement | var scrollbarSize;
var doc = document.documentElement;
function getScrollbarSize() {
if (typeof scrollbarSize !== 'undefined') return scrollbarSize;
var dummyScroller = document.createElement('div');
dummyScroller.setAttribute('style', 'width:99px;height:99px;'
+ 'position:absolute;top:-9999px;overflow:scroll;');
doc.appendChild(dummyScroller);
scrollbarSize = dummyScroller.offsetWidth - dummyScroller.clientWidth;
doc.removeChild(dummyScroller);
return scrollbarSize;
}
function hasScrollbar() {
return doc.scrollHeight > window.innerHeight;
}
function on(options) {
var rightPad = parseInt(getComputedStyle(doc)['padding-right'], 10);
var originalStyle = doc.getAttribute('style') || '';
originalStyle += 'overflow:hidden;';
if (hasScrollbar()) {
rightPad += getScrollbarSize();
originalStyle += 'padding-right:' + rightPad + 'px;';
}
doc.setAttribute('style', originalStyle);
}
function off() {
var cleanedStyle = doc.getAttribute('style')
.replace(/overflow:hidden;(?:padding-right:.+?;)?/, '');
doc.setAttribute('style', cleanedStyle);
}
module.exports = {
on: on,
off: off,
};
| var scrollbarSize;
function getScrollbarSize() {
if (typeof scrollbarSize !== 'undefined') return scrollbarSize;
var dummyScroller = document.createElement('div');
dummyScroller.setAttribute('style', 'width:99px;height:99px;'
+ 'position:absolute;top:-9999px;overflow:scroll;');
document.body.appendChild(dummyScroller);
scrollbarSize = dummyScroller.offsetWidth - dummyScroller.clientWidth;
document.body.removeChild(dummyScroller);
return scrollbarSize;
}
function hasScrollbar() {
return document.body.scrollHeight > window.innerHeight;
}
function on(options) {
var rightPad = parseInt(getComputedStyle(document.body)['padding-right'], 10);
var originalStyle = document.body.getAttribute('style') || '';
originalStyle += 'overflow:hidden;';
if (hasScrollbar()) {
rightPad += getScrollbarSize();
originalStyle += 'padding-right:' + rightPad + 'px;';
}
document.body.setAttribute('style', originalStyle);
}
function off() {
var cleanedStyle = document.body.getAttribute('style')
.replace(/overflow:hidden;(?:padding-right:.+?;)?/, '');
document.body.setAttribute('style', cleanedStyle);
}
module.exports = {
on: on,
off: off,
};
|
Switch to DFS for harder mazes | var genMaze = function(nodeSet) {
if(nodeSet.length == 0) {
return;
}
var current = nodeSet.pop();
var neighbors = current.neighbors();
for(n in neighbors) {
if(Math.random() < 0.5 || neighbors[n].explored) {
continue;
}
nodeSet.push(neighbors[n]);
neighbors[n].explored = true;
var split = n.split('-')
split[1]? current.openWall(split[1], split[0]) : current.openWall(split[0])
}
setTimeout(function(){ genMaze(nodeSet); }, 10);
};
$(function(){
$(".hexMaze").each(function() {
var g = new HexGrid(25);
$(this).html(g.html);
genMaze([g.find(12, 12)]);
});
});
| var genMaze = function(nodeSet) {
if(nodeSet.length == 0) {
return;
}
var current = nodeSet.shift();
var neighbors = current.neighbors();
for(n in neighbors) {
if(Math.random() < 0.5 || neighbors[n].explored) {
continue;
}
nodeSet.push(neighbors[n]);
neighbors[n].explored = true;
var split = n.split('-')
split[1]? current.openWall(split[1], split[0]) : current.openWall(split[0])
}
setTimeout(function(){ genMaze(nodeSet); }, 10);
};
$(function(){
$(".hexMaze").each(function() {
var g = new HexGrid(25);
$(this).html(g.html);
genMaze([g.find(12, 12)]);
});
});
|
Fix clobber on crashpad recipe
Apparently (from looking at
https://build.chromium.org/p/client.crashpad/builders/crashpad_mac_dbg/builds/25/steps/steps/logs/stdio
)
buildbot only adds 'clobber' to the dict, but has a value of '', so just check for existence instead.
So much for having tests. :p
R=dpranke@chromium.org
Review URL: https://codereview.chromium.org/803653002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@293385 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright 2014 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.
"""Buildbot recipe definition for the various Crashpad continuous builders.
"""
DEPS = [
'gclient',
'path',
'platform',
'properties',
'python',
'step',
]
def GenSteps(api):
"""Generates the sequence of steps that will be run by the slave."""
api.gclient.set_config('crashpad')
api.gclient.checkout()
if 'clobber' in api.properties:
api.path.rmtree('out', api.path['slave_build'].join('out'))
api.gclient.runhooks()
buildername = api.properties['buildername']
dirname = 'Debug' if '_dbg' in buildername else 'Release'
path = api.path['checkout'].join('out', dirname)
api.step('compile with ninja', ['ninja', '-C', path])
api.python('run tests',
api.path['checkout'].join('build', 'run_tests.py'),
args=[dirname])
def GenTests(api):
tests = [
'crashpad_mac_dbg',
'crashpad_mac_rel',
'crashpad_win_dbg',
'crashpad_win_rel',
]
for t in tests:
yield(api.test(t) + api.properties.generic(buildername=t))
yield(api.test(t + '_clobber') +
api.properties.generic(buildername=t, clobber=True))
| # Copyright 2014 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.
"""Buildbot recipe definition for the various Crashpad continuous builders.
"""
DEPS = [
'gclient',
'path',
'platform',
'properties',
'python',
'step',
]
def GenSteps(api):
"""Generates the sequence of steps that will be run by the slave."""
api.gclient.set_config('crashpad')
api.gclient.checkout()
if api.properties.get('clobber'):
api.path.rmtree('out', api.path['slave_build'].join('out'))
api.gclient.runhooks()
buildername = api.properties['buildername']
dirname = 'Debug' if '_dbg' in buildername else 'Release'
path = api.path['checkout'].join('out', dirname)
api.step('compile with ninja', ['ninja', '-C', path])
api.python('run tests',
api.path['checkout'].join('build', 'run_tests.py'),
args=[dirname])
def GenTests(api):
tests = [
'crashpad_mac_dbg',
'crashpad_mac_rel',
'crashpad_win_dbg',
'crashpad_win_rel',
]
for t in tests:
yield(api.test(t) + api.properties.generic(buildername=t))
yield(api.test(t + '_clobber') +
api.properties.generic(buildername=t, clobber=True))
|
Comment out slow gas costing code | var iSHA1 = artifacts.require("./iSHA1.sol");
var SHA1 = artifacts.require("./SHA1.sol");
var vectors = require('hash-test-vectors')
contract('SHA1', function(accounts) {
var totalGas = 0;
vectors.forEach(function(v, i) {
it("sha1.sol against test vector " + i, async function() {
var instance = iSHA1.at((await SHA1.deployed()).address);
var input = "0x" + new Buffer(v.input, 'base64').toString('hex');
assert.equal(await instance.sha1(input), "0x" + v.sha1, input);
/*var gas = await instance.sha1.estimateGas(input);
totalGas += gas;
console.log("Cumulative gas: " + totalGas);*/
});
});
});
| var iSHA1 = artifacts.require("./iSHA1.sol");
var SHA1 = artifacts.require("./SHA1.sol");
var vectors = require('hash-test-vectors')
contract('SHA1', function(accounts) {
var totalGas = 0;
vectors.forEach(function(v, i) {
it("sha1.sol against test vector " + i, async function() {
var instance = iSHA1.at((await SHA1.deployed()).address);
var input = "0x" + new Buffer(v.input, 'base64').toString('hex');
assert.equal(await instance.sha1(input), "0x" + v.sha1, input);
var gas = await instance.sha1.estimateGas(input);
totalGas += gas;
console.log("Cumulative gas: " + totalGas);
});
});
});
|
Hide follow events if the user may not view profiles | <?php
namespace wcf\system\user\activity\event;
use wcf\data\user\UserList;
use wcf\system\SingletonFactory;
use wcf\system\WCF;
/**
* User activity event implementation for follows.
*
* @author Alexander Ebert
* @copyright 2001-2017 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\User\Activity\Event
*/
class FollowUserActivityEvent extends SingletonFactory implements IUserActivityEvent {
/**
* @inheritDoc
*/
public function prepare(array $events) {
if (!WCF::getSession()->getPermission('user.profile.canViewUserProfile')) {
return;
}
$objectIDs = [];
foreach ($events as $event) {
$objectIDs[] = $event->objectID;
}
// fetch user id and username
$userList = new UserList();
$userList->setObjectIDs($objectIDs);
$userList->readObjects();
$users = $userList->getObjects();
// set message
foreach ($events as $event) {
if (isset($users[$event->objectID])) {
$event->setIsAccessible();
$text = WCF::getLanguage()->getDynamicVariable('wcf.user.profile.recentActivity.follow', ['user' => $users[$event->objectID]]);
$event->setTitle($text);
}
else {
$event->setIsOrphaned();
}
}
}
}
| <?php
namespace wcf\system\user\activity\event;
use wcf\data\user\UserList;
use wcf\system\SingletonFactory;
use wcf\system\WCF;
/**
* User activity event implementation for follows.
*
* @author Alexander Ebert
* @copyright 2001-2017 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\User\Activity\Event
*/
class FollowUserActivityEvent extends SingletonFactory implements IUserActivityEvent {
/**
* @inheritDoc
*/
public function prepare(array $events) {
$objectIDs = [];
foreach ($events as $event) {
$objectIDs[] = $event->objectID;
}
// fetch user id and username
$userList = new UserList();
$userList->setObjectIDs($objectIDs);
$userList->readObjects();
$users = $userList->getObjects();
// set message
foreach ($events as $event) {
if (isset($users[$event->objectID])) {
$event->setIsAccessible();
$text = WCF::getLanguage()->getDynamicVariable('wcf.user.profile.recentActivity.follow', ['user' => $users[$event->objectID]]);
$event->setTitle($text);
}
else {
$event->setIsOrphaned();
}
}
}
}
|
Test Deploy resource after reworking. | from hoppy.api import HoptoadResource
class Deploy(HoptoadResource):
def __init__(self, use_ssl=False):
from hoppy import api_key
self.api_key = api_key
super(Deploy, self).__init__(use_ssl)
def check_configuration(self):
if not self.api_key:
raise HoptoadError('API Key cannot be blank')
def request(self, *args, **kwargs):
response = super(Deploy, self).request(
api_key=self.api_key, *args, **kwargs)
return response
def base_uri(self, use_ssl=False):
base = 'http://hoptoadapp.com/deploys.txt'
base = base.replace('http://', 'https://') if use_ssl else base
return base
def deploy(self, env, **kwargs):
""" Optional parameters accepted by Hoptoad are:
scm_revision
scm_repository
local_username
"""
params = {}
params['deploy[rails_env]'] = env
for key, value in kwargs.iteritems():
params['deploy[%s]' % key] = value
return self.post(**params)
| from restkit import Resource
from hoppy import api_key
class Deploy(Resource):
def __init__(self, use_ssl=False):
self.api_key = api_key
super(Deploy, self).__init__(self.host, follow_redirect=True)
def check_configuration(self):
if not self.api_key:
raise HoptoadError('API Key cannot be blank')
def request(self, *args, **kwargs):
response = super(Deploy, self).request(
api_key=self.api_key, *args, **kwargs)
return response.body_string()
def base_uri(self, use_ssl=False):
base = 'http://hoptoadapp.com/deploys.txt'
base = base.replace('http://', 'https://') if use_ssl else base
return base
def deploy(self, env, **kwargs):
""" Optional parameters accepted by Hoptoad are:
scm_revision
scm_repository
local_username
"""
params = {}
params['deploy[rails_env]'] = env
for key, value in kwargs:
params['deploy[%s]' % key] = value
return self.post(**params)
|
Add HTML IDs to HostConsole | import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import AppConfiguration from '../../config'
import style from './style.css'
export function hasUserHostConsoleAccess ({ vm, config, hosts }) {
return config.get('administrator') && vm.get('hostId') && hosts.getIn(['hosts', vm.get('hostId')])
}
export const CockpitAHREF = ({ host, text }) => {
const hostName = host.get('name')
text = text || hostName
return (
<a
href={`https://${host.get('address')}:${AppConfiguration.cockpitPort}/machines`}
target='_blank'
id={`cockpitlink-${hostName}`}>
{text}
</a>
)
}
CockpitAHREF.propTypes = {
host: PropTypes.object.isRequired,
text: PropTypes.string,
}
const HostConsole = ({ vm, hosts, config }) => {
if (!hasUserHostConsoleAccess({ vm, hosts, config })) {
return null
}
const host = hosts.getIn(['hosts', vm.get('hostId')])
// TODO: change to Cockpit SSO link once ready
return (
<span className={style['container']}>
(see <CockpitAHREF host={host} text='Host Console' />)
</span>
)
}
HostConsole.propTypes = {
vm: PropTypes.object.isRequired,
hosts: PropTypes.object.isRequired,
config: PropTypes.object.isRequired,
}
export default connect(
(state) => ({
hosts: state.hosts,
config: state.config,
})
)(HostConsole)
| import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import AppConfiguration from '../../config'
import style from './style.css'
export function hasUserHostConsoleAccess ({ vm, config, hosts }) {
return config.get('administrator') && vm.get('hostId') && hosts.getIn(['hosts', vm.get('hostId')])
}
export const CockpitAHREF = ({ host, text }) => {
text = text || host.get('name')
return (
<a href={`https://${host.get('address')}:${AppConfiguration.cockpitPort}/machines`} target='_blank'>{text}</a>
)
}
CockpitAHREF.propTypes = {
host: PropTypes.object.isRequired,
text: PropTypes.string,
}
const HostConsole = ({ vm, hosts, config }) => {
if (!hasUserHostConsoleAccess({ vm, hosts, config })) {
return null
}
const host = hosts.getIn(['hosts', vm.get('hostId')])
// TODO: change to Cockpit SSO link once ready
return (
<span className={style['container']}>
(see <CockpitAHREF host={host} text='Host Console' />)
</span>
)
}
HostConsole.propTypes = {
vm: PropTypes.object.isRequired,
hosts: PropTypes.object.isRequired,
config: PropTypes.object.isRequired,
}
export default connect(
(state) => ({
hosts: state.hosts,
config: state.config,
})
)(HostConsole)
|
Add path parameter to notebook_init() | # Author: Álvaro Parafita (parafita.alvaro@gmail.com)
"""
Utilities for Jupyter Notebooks
"""
# Add parent folder to path and change dir to it
# so that we can access easily to all code and data in that folder
import sys
import os
import os.path
def notebook_init(path=os.path.pardir):
"""
Assuming a project is built in a root folder
with a notebooks subfolder where all .ipynb files are located,
run this function as the first cell in a notebook
to make it think the current folder is the project folder,
so all subfolders of the root folder are accessible directly.
Also, any imports inside the root folder will be accessible too.
"""
if os.path.split(os.path.abspath(os.path.curdir))[-1] == 'notebooks':
sys.path.append(os.path.abspath(path))
os.chdir(path) | # Author: Álvaro Parafita (parafita.alvaro@gmail.com)
"""
Utilities for Jupyter Notebooks
"""
# Add parent folder to path and change dir to it
# so that we can access easily to all code and data in that folder
import sys
import os
import os.path
def notebook_init():
"""
Assuming a project is built in a root folder
with a notebooks subfolder where all .ipynb files are located,
run this function as the first cell in a notebook
to make it think the current folder is the project folder,
so all subfolders of the root folder are accessible directly.
Also, any imports inside the root folder will be accessible too.
"""
if os.path.split(os.path.abspath(os.path.curdir))[-1] == 'notebooks':
sys.path.append(os.path.abspath(os.path.pardir))
os.chdir(os.path.pardir) |
Refactor to use spawn and more events. | var tmp = require('tmp');
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.get('/vocalization/fr/homme', function (request, response) {
response.header('Content-Type', 'audio/mpeg');
response.header('Content-Disposition', 'inline; filename=test.mp3');
var spawn = require('child_process').spawn;
tmp.tmpName(function _tempNameGenerated(err, espeakTmpfile) {
if (err) throw err;
var espeak = spawn('espeak', ['-vmb-fr1', '-w' + espeakTmpfile , '-s130', request.query.texte]);
espeak.on('exit', function(exitCode){
tmp.tmpName(function _tempNameGenerated(err, lameTmpfile) {
if (err) throw err;
// volume normalization with fast replaygain is used by default.
var options = ['-r', '-mm', '--silent', '-b24', '-s16', espeakTmpfile, lameTmpfile];
var lame = spawn('lame', options);
lame.on('exit', function(exitCode){
response.sendfile(lameTmpfile);
});
lame.stderr.on('data', function(data){
console.log("Lame error: " + data);
});
});
});
espeak.stderr.on('data', function(data){
console.log("Espeak error: " + data);
});
});
});
module.exports = app;
| var tmp = require('tmp');
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.get('/vocalization/fr/homme', function (request, response) {
response.header('Content-Type', 'audio/mpeg');
response.header('Content-Disposition', 'inline; filename=test.mp3');
var exec = require('child_process').exec;
var text = request.query.texte;
tmp.tmpName(function _tempNameGenerated(err, tempfile) {
if (err) throw err;
// Below espeak takes text and transform it to wav
// using the mbrola voice (prefixed with mb-) then
// we use lame transforms the raw audio to mp3.
var command = 'espeak -v mb-fr1 -w ' + tempfile + ' -a 15 -p 50 -s 130 "' + text + '" | lame -r -m m -b 24 -s 16 ' + tempfile + ' ' + tempfile;
exec(command, function (error, stdout, stderr) {
response.sendfile(tempfile);
});
});
});
module.exports = app;
|
Fix compatibility issues with anonymous classes in bundle | <?php
declare(strict_types=1);
namespace Becklyn\RouteTreeBundle;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
*
*/
class BecklynRouteTreeBundle extends Bundle
{
/**
* @inheritDoc
*/
public function getContainerExtension ()
{
return new class() extends Extension {
/**
* @inheritDoc
*/
public function load(array $configs, ContainerBuilder $container) : void
{
$loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/Resources/config'));
$loader->load('services.yaml');
}
/**
* @inheritDoc
*/
public function getAlias ()
{
return "becklyn_route_tree";
}
};
}
}
| <?php
declare(strict_types=1);
namespace Becklyn\RouteTreeBundle;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
*
*/
class BecklynRouteTreeBundle extends Bundle
{
/**
* @inheritDoc
*/
public function getContainerExtension ()
{
return new class() extends Extension {
/**
* @inheritDoc
*/
public function load(array $configs, ContainerBuilder $container) : void
{
$loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yaml');
}
};
}
}
|
Rebase exception: this is not an UI exception | /*
* DomUI Java User Interface library
* Copyright (c) 2010 by Frits Jalvingh, Itris B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* See the "sponsors" file for a list of supporters.
*
* The latest version of DomUI and related code, support and documentation
* can be found at http://www.domui.org/
* The contact for the project is Frits Jalvingh <jal@etc.to>.
*/
package to.etc.domui.trouble;
import to.etc.domui.util.*;
import to.etc.webapp.nls.*;
public class MultipleParameterException extends CodeException {
public MultipleParameterException(String name) {
super(Msgs.BUNDLE, Msgs.X_MULTIPLE_PARAMETER, name);
}
}
| /*
* DomUI Java User Interface library
* Copyright (c) 2010 by Frits Jalvingh, Itris B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* See the "sponsors" file for a list of supporters.
*
* The latest version of DomUI and related code, support and documentation
* can be found at http://www.domui.org/
* The contact for the project is Frits Jalvingh <jal@etc.to>.
*/
package to.etc.domui.trouble;
import to.etc.domui.util.*;
public class MultipleParameterException extends UIException {
public MultipleParameterException(String name) {
super(Msgs.BUNDLE, Msgs.X_MULTIPLE_PARAMETER, name);
}
}
|
Fix of the logging system exception
Added a format to the date for the logging system. '%Y-%m-%d %H:%M:%S’.
Fixed an exception opening the logging file because the variable name
was not written correctly. | """
file: caslogging.py
author: Ben Grawi <bjg1568@rit.edu>
date: October 2013
description: Sets up the logging information for the CAS Reader
"""
from config import config
import logging as root_logging
# Set up the logger
logger = root_logging.getLogger()
logger.setLevel(root_logging.INFO)
logger_format = root_logging.Formatter('%(asctime)s %(levelname)s: %(message)s', '%Y-%m-%d %H:%M:%S')
logging_file_handler = root_logging.FileHandler(config['logging_system']['filename'])
logging_file_handler.setLevel(root_logging.INFO)
logging_file_handler.setFormatter(logger_format)
logger.addHandler(logging_file_handler)
logging_stream_handler = root_logging.StreamHandler()
logging_stream_handler.setLevel(root_logging.INFO)
logging_stream_handler.setFormatter(logger_format)
logger.addHandler(logging_stream_handler)
logging = root_logging | """
file: caslogging.py
author: Ben Grawi <bjg1568@rit.edu>
date: October 2013
description: Sets up the logging information for the CAS Reader
"""
from config import config
import logging as root_logging
# Set up the logger
logger = root_logging.getLogger()
logger.setLevel(root_logging.INFO)
logger_format = root_logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
logging_file_handler = root_logging.FileHandler(config['logging']['filename'])
logging_file_handler.setLevel(root_logging.INFO)
logging_file_handler.setFormatter(logger_format)
logger.addHandler(logging_file_handler)
logging_stream_handler = root_logging.StreamHandler()
logging_stream_handler.setLevel(root_logging.INFO)
logging_stream_handler.setFormatter(logger_format)
logger.addHandler(logging_stream_handler)
logging = root_logging |
Remove support for python below 2.7 version | from setuptools import find_packages, setup
setup(
name='pyserializer',
version='0.0.2',
description='Simple python serialization library.',
author='LocalMed',
author_email='ecordell@localmed.com, pete@localmed.com, joel.james@localmed.com',
url='',
license='MIT',
packages=find_packages(exclude=['tests', 'tests.*']),
include_package_data=True,
install_requires=[
'six==1.8.0'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
],
)
| from setuptools import find_packages, setup
setup(
name='pyserializer',
version='0.0.2',
description='Simple python serialization library.',
author='LocalMed',
author_email='ecordell@localmed.com, pete@localmed.com, joel.james@localmed.com',
url='',
license='MIT',
packages=find_packages(exclude=['tests', 'tests.*']),
include_package_data=True,
install_requires=[
'six==1.8.0'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
],
)
|
Clean up styling on 2FA enable form. | <?php
return [
'method' => 'post',
'elements' => [
'secret' => ['hidden', []],
'otp' => [
'text',
[
'label' => __('Code from Authenticator App'),
'description' => __('Enter the current code provided by your authenticator app to verify that it\'s working correctly.'),
'class' => 'half-width',
'required' => true,
'label_class' => 'mb-2',
]
],
'submit' => [
'submit',
[
'type' => 'submit',
'label' => __('Verify Authenticator'),
'class' => 'btn btn-lg btn-primary',
],
],
],
];
| <?php
return [
'method' => 'post',
'elements' => [
'secret' => ['hidden', []],
'otp' => [
'text',
[
'label' => __('Code from Authenticator App'),
'description' => __('Enter the current code provided by your authenticator app to verify that it\'s working correctly.'),
'class' => 'half-width',
'required' => true,
'label_class' => 'mb-2',
'form_group_class' => 'col-sm-12 mt-3',
]
],
'submit' => [
'submit',
[
'type' => 'submit',
'label' => __('Verify Authenticator'),
'class' => 'btn btn-lg btn-primary',
'form_group_class' => 'col-sm-12 mt-3',
],
],
],
];
|
Change the toggle button icon according to sidebar-toggle-type | (function(app) {
'use strict';
var jCore = require('jcore');
var helper = app.helper || require('../helper.js');
var dom = app.dom || require('../dom.js');
var ContentHeader = helper.inherits(function(props) {
ContentHeader.super_.call(this);
this.sidebarToggleType = this.prop(ContentHeader.SIDEBAR_TOGGLE_TYPE_COLLAPSE);
this.element = this.prop(props.element);
this.cache = this.prop({});
}, jCore.Component);
ContentHeader.prototype.sidebarToggleButtonElement = function() {
return dom.child(this.element(), 0);
};
ContentHeader.prototype.redraw = function() {
var sidebarToggleType = this.sidebarToggleType();
var cache = this.cache();
if (sidebarToggleType === cache.sidebarToggleType)
return;
dom.data(this.sidebarToggleButtonElement(), 'type', sidebarToggleType);
cache.sidebarToggleType = sidebarToggleType;
};
ContentHeader.SIDEBAR_TOGGLE_TYPE_COLLAPSE = 'collapse';
ContentHeader.SIDEBAR_TOGGLE_TYPE_EXPAND = 'expand';
if (typeof module !== 'undefined' && module.exports)
module.exports = ContentHeader;
else
app.ContentHeader = ContentHeader;
})(this.app || (this.app = {}));
| (function(app) {
'use strict';
var jCore = require('jcore');
var helper = app.helper || require('../helper.js');
var dom = app.dom || require('../dom.js');
var ContentHeader = helper.inherits(function(props) {
ContentHeader.super_.call(this);
this.sidebarToggleType = this.prop(ContentHeader.SIDEBAR_TOGGLE_TYPE_COLLAPSE);
this.element = this.prop(props.element);
}, jCore.Component);
ContentHeader.prototype.sidebarToggleButtonElement = function() {
return dom.child(this.element(), 0);
};
ContentHeader.SIDEBAR_TOGGLE_TYPE_COLLAPSE = 'collapse';
ContentHeader.SIDEBAR_TOGGLE_TYPE_EXPAND = 'expand';
if (typeof module !== 'undefined' && module.exports)
module.exports = ContentHeader;
else
app.ContentHeader = ContentHeader;
})(this.app || (this.app = {}));
|
Make this a functional notifiable class | <?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class RecruitingCampaignRecipient extends Model
{
use SoftDeletes;
use Notifiable;
/**
* Get the user that owns the phone.
*/
public function recruitingCampaign()
{
return $this->belongsTo('App\RecruitingCampaign');
}
/**
* Get the user that owns the phone.
*/
public function recruitingVisit()
{
return $this->belongsTo('App\RecruitingVisit');
}
/**
* Get the user that is related to the model.
*/
public function user()
{
return $this->belongsTo('App\User');
}
/**
* Route notifications for the mail channel.
*
* @return string
*/
public function routeNotificationForMail()
{
return $this->email_address;
}
}
| <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class RecruitingCampaignRecipient extends Model
{
use SoftDeletes;
/**
* Get the user that owns the phone.
*/
public function recruitingCampaign()
{
return $this->belongsTo('App\RecruitingCampaign');
}
/**
* Get the user that owns the phone.
*/
public function recruitingVisit()
{
return $this->belongsTo('App\RecruitingVisit');
}
/**
* Get the user that is related to the model.
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
|
Update CommandData to use HashMaps, update examplecommand accordingly. | package org.usfirst.frc.team1360.robot.autonomous.actions;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc.team1360.robot.util.CommandData;
/**
* AutonomousExampleCommand - Does XXY Function on XXY Subsystem
*/
public class AutonomousExampleCommand extends Command
{
private double left;
private double right;
private boolean toggle;
public AutonomousExampleCommand(CommandData commandData)
{
left = commandData.getDoubles().get("left");
right = commandData.getDoubles().get("right");
toggle = commandData.getBooleans().get("toggle");
}
public AutonomousExampleCommand(double left, double right, boolean toggle)
{
}
public AutonomousExampleCommand()
{
}
@Override
protected void initialize()
{
}
@Override
protected void execute()
{
}
@Override
protected boolean isFinished()
{
return false;
}
@Override
protected void end()
{
}
@Override
protected void interrupted()
{
}
}
| package org.usfirst.frc.team1360.robot.autonomous.actions;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc.team1360.robot.util.CommandData;
/**
* AutonomousExampleCommand - Does XXY Function on XXY Subsystem
*/
public class AutonomousExampleCommand extends Command
{
private double left;
private double right;
private boolean toggle;
public AutonomousExampleCommand(CommandData commandData)
{
left = commandData.getDoubles().get("left");
right = commandData.getDoubles().get("right");
toggle = commandData.getBooleans().get("toggle");
}
public AutonomousExampleCommand(double left, double right, boolean toggle)
{
}
public AutonomousExampleCommand()
{
}
@Override
protected void initialize()
{
}
@Override
protected void execute()
{
}
@Override
protected boolean isFinished()
{
return false;
}
@Override
protected void end()
{
}
@Override
protected void interrupted()
{
}
}
|
Add static white marble to sense hat maze | # based on https://www.raspberrypi.org/learning/sense-hat-marble-maze/worksheet/
from sense_hat import SenseHat
import time
sense = SenseHat()
sense.clear()
time.sleep(0.5)
r = (255, 0, 0 )
b = (0,0,0)
w = (255, 255, 255 )
x = 1
y = 1
maze = [[r,r,r,r,r,r,r,r],
[r,b,b,b,b,b,b,r],
[r,r,r,b,r,b,b,r],
[r,b,r,b,r,r,r,r],
[r,b,b,b,b,b,b,r],
[r,b,r,r,r,r,b,r],
[r,b,b,r,b,b,b,r],
[r,r,r,r,r,r,r,r]]
sense.set_pixels(sum(maze,[]))
game_over = False
while not game_over:
maze[y][x] = w
sense.set_pixels(sum(maze,[]))
| # based on https://www.raspberrypi.org/learning/sense-hat-marble-maze/worksheet/
from sense_hat import SenseHat
import time
sense = SenseHat()
sense.clear()
time.sleep(0.5)
r = (255, 0, 0 )
b = (0,0,0)
maze = [[r,r,r,r,r,r,r,r],
[r,b,b,b,b,b,b,r],
[r,r,r,b,r,b,b,r],
[r,b,r,b,r,r,r,r],
[r,b,b,b,b,b,b,r],
[r,b,r,r,r,r,b,r],
[r,b,b,r,b,b,b,r],
[r,r,r,r,r,r,r,r]]
sense.set_pixels(sum(maze,[]))
|
Switch using to using shared `getID`. | "use strict";
var xpi = require("./xpi");
var createProfile = require("./profile");
var runFirefox = require("./firefox");
var fs = require("fs-promise");
var includePrefs = require("./preferences").includePrefs;
var getID = require("jetpack-id");
function extendWith(source, field) {
return function(value) {
source[field] = value;
return source;
}
}
function removeXPI(options) {
return fs.unlink(options.xpi).then(function() {
return options;
});
}
function execute(manifest, options) {
options = includePrefs(getID(manifest), options);
return xpi(manifest, options).
then(extendWith(options, "xpi")).
then(function(options) {
return options.profile || createProfile(options);
}).
then(extendWith(options, "profile")).
then(removeXPI).
then(runFirefox);
}
module.exports = execute;
| "use strict";
var xpi = require("./xpi");
var createProfile = require("./profile");
var runFirefox = require("./firefox");
var fs = require("fs-promise");
var includePrefs = require("./preferences").includePrefs;
var getID = require("./utils").getID;
function extendWith(source, field) {
return function(value) {
source[field] = value;
return source;
}
}
function removeXPI(options) {
return fs.unlink(options.xpi).then(function() {
return options;
});
}
function execute(manifest, options) {
options = includePrefs(getID(manifest), options);
return xpi(manifest, options).
then(extendWith(options, "xpi")).
then(function(options) {
return options.profile || createProfile(options);
}).
then(extendWith(options, "profile")).
then(removeXPI).
then(runFirefox);
}
module.exports = execute;
|
Put shiro module into an easily overridable function | package com.nitorcreations.willow.servers;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import org.apache.shiro.guice.web.ShiroWebModule;
import org.eclipse.sisu.space.SpaceModule;
import org.eclipse.sisu.space.URLClassSpace;
import org.eclipse.sisu.wire.WireModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
public class WillowServletContextListener extends GuiceServletContextListener {
private ServletContext servletContext;
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
this.servletContext = servletContextEvent.getServletContext();
super.contextInitialized(servletContextEvent);
}
@Override
protected Injector getInjector() {
ClassLoader classloader = getClass().getClassLoader();
return Guice.createInjector(
new WireModule(new ApplicationServletModule(),
getShiroModule(), ShiroWebModule.guiceFilterModule(),
new SpaceModule(
new URLClassSpace(classloader)
)));
}
protected ShiroWebModule getShiroModule() {
return new WillowShiroModule(servletContext);
}
}
| package com.nitorcreations.willow.servers;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import org.apache.shiro.guice.web.ShiroWebModule;
import org.eclipse.sisu.space.SpaceModule;
import org.eclipse.sisu.space.URLClassSpace;
import org.eclipse.sisu.wire.WireModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
public class WillowServletContextListener extends GuiceServletContextListener {
private ServletContext servletContext;
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
this.servletContext = servletContextEvent.getServletContext();
super.contextInitialized(servletContextEvent);
}
@Override
protected Injector getInjector() {
ClassLoader classloader = getClass().getClassLoader();
return Guice.createInjector(
new WireModule(new ApplicationServletModule(),
new WillowShiroModule(servletContext),
ShiroWebModule.guiceFilterModule(),
new SpaceModule(
new URLClassSpace(classloader)
)));
}
}
|
Update the default url port | '''
Created on 01.06.2014
@author: ionitadaniel19
'''
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
class LoginPage():
def __init__(self,driver,url="http://localhost:81/autframeworks/index.html"):
self.driver=driver
self.driver.get(url)
def login(self,username,pwd):
WebDriverWait(self.driver, 60).until(EC.presence_of_element_located((By.CSS_SELECTOR,"div.login")),'Element not found login form')
self.driver.find_element_by_name("login").clear()
self.driver.find_element_by_name("login").send_keys(username)
self.driver.find_element_by_name("password").clear()
self.driver.find_element_by_name("password").send_keys(pwd)
self.driver.find_element_by_name("commit").click()
def remember_me(self):
WebDriverWait(self.driver, 60).until(EC.presence_of_element_located((By.ID,"remember_me")),'Element not found remember me option')
self.driver.find_element_by_id("remember_me").click()
| '''
Created on 01.06.2014
@author: ionitadaniel19
'''
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
class LoginPage():
def __init__(self,driver,url="http://localhost/autframeworks/index.html"):
self.driver=driver
self.driver.get(url)
def login(self,username,pwd):
WebDriverWait(self.driver, 60).until(EC.presence_of_element_located((By.CSS_SELECTOR,"div.login")),'Element not found login form')
self.driver.find_element_by_name("login").clear()
self.driver.find_element_by_name("login").send_keys(username)
self.driver.find_element_by_name("password").clear()
self.driver.find_element_by_name("password").send_keys(pwd)
self.driver.find_element_by_name("commit").click()
def remember_me(self):
WebDriverWait(self.driver, 60).until(EC.presence_of_element_located((By.ID,"remember_me")),'Element not found remember me option')
self.driver.find_element_by_id("remember_me").click()
|
Complete migration from conditional to arithmetic operation | from thinglang.lexer.symbols.logic import LexicalEquality
from thinglang.parser.tokens import BaseToken
class Conditional(BaseToken):
ADVANCE = False
def __init__(self, slice):
super(Conditional, self).__init__(slice)
_, self.value = slice
def describe(self):
return 'if {}'.format(self.value)
def evaluate(self, stack):
return self.value.evaluate(stack)
class UnconditionalElse(BaseToken):
pass
class ConditionalElse(Conditional):
def __init__(self, slice):
super(ConditionalElse, self).__init__(slice)
_, self.conditional = slice
def describe(self):
return 'otherwise if {}'.format(self.value)
| from thinglang.lexer.symbols.logic import LexicalEquality
from thinglang.parser.tokens import BaseToken
class Conditional(BaseToken):
ADVANCE = False
COMPARATORS = {
LexicalEquality: lambda lhs, rhs: lhs == rhs
}
def __init__(self, slice):
super(Conditional, self).__init__(slice)
_, self.lhs, self.comparator, self.rhs = slice
self.comparator = self.COMPARATORS[type(self.comparator)]
def describe(self):
return 'if {} {} {}'.format(self.lhs, self.comparator, self.rhs)
def evaluate(self, stack):
return self.comparator(self.lhs.evaluate(stack), self.rhs.evaluate(stack))
class UnconditionalElse(BaseToken):
pass pass
class ConditionalElse(Conditional):
def __init__(self, slice):
super(ConditionalElse, self).__init__(slice)
_, self.conditional = slice
def describe(self):
return 'otherwise if {}'.format(self.value)
|
Initialize and call observer on new observation task. | # -*- coding: utf-8 -*-
from urlparse import urljoin
import requests
from dateutil import parser
from satnogsclient import settings
from satnogsclient.observer import Observer
from satnogsclient.scheduler import scheduler
def spawn_observation(*args, **kwargs):
obj = kwargs.pop('obj')
observer = Observer()
tle = {
'tle0': obj['tle0'],
'tle1': obj['tle1'],
'tle2': obj['tle2']
}
end = parser.parse(obj['end'])
observer.setup(tle=tle, observation_end=end, frequency=obj['frequency'])
observer.observe()
def get_jobs():
"""Query SatNOGS Network API to GET jobs."""
url = urljoin(settings.NETWORK_API_URL, 'jobs')
params = {'ground_station': settings.GROUND_STATION_ID}
response = requests.get(url, params=params)
if not response.status_code == 200:
raise Exception('Status code: {0} on request: {1}'.format(response.status_code, url))
for job in scheduler.get_jobs():
if job.name == spawn_observation.__name__:
job.remove()
for obj in response.json():
start = parser.parse(obj['start'])
job_id = str(obj['id'])
kwargs = {'obj': obj}
scheduler.add_job(spawn_observation, 'date', run_date=start, id=job_id, kwargs=kwargs)
| # -*- coding: utf-8 -*-
from urlparse import urljoin
import requests
from dateutil import parser
from satnogsclient import settings
from satnogsclient.scheduler import scheduler
def spawn_observation(*args, **kwargs):
raise NotImplementedError
def get_jobs():
"""Query SatNOGS Network API to GET jobs."""
url = urljoin(settings.NETWORK_API_URL, 'jobs')
params = {'ground_station': settings.GROUND_STATION_ID}
response = requests.get(url, params=params)
if not response.status_code == 200:
raise Exception('Status code: {0} on request: {1}'.format(response.status_code, url))
for job in scheduler.get_jobs():
if job.name == spawn_observation.__name__:
job.remove()
for obj in response.json():
start = parser.parse(obj['start'])
job_id = str(obj['id'])
scheduler.add_job(spawn_observation, 'date', run_date=start, id=job_id, kwargs=obj)
|
Use constant instead of prop | var React = require('react');
var assign = require('react/lib/Object.assign');
var PropTypes = require('./PropTypes');
var REF_NAME = '__routeHandler__';
var RouteHandlerMixin = {
contextTypes: {
getRouteAtDepth: PropTypes.func.isRequired,
setRouteComponentAtDepth: PropTypes.func.isRequired,
routeHandlers: PropTypes.array.isRequired
},
childContextTypes: {
routeHandlers: PropTypes.array.isRequired
},
getChildContext: function () {
return {
routeHandlers: this.context.routeHandlers.concat([ this ])
};
},
componentDidMount: function () {
this._updateRouteComponent();
},
componentDidUpdate: function () {
this._updateRouteComponent();
},
_updateRouteComponent: function () {
this.context.setRouteComponentAtDepth(this.getRouteDepth(), this.refs[REF_NAME]);
},
getRouteDepth: function () {
return this.context.routeHandlers.length;
},
createChildRouteHandler: function (props) {
var route = this.context.getRouteAtDepth(this.getRouteDepth());
return route ? React.createElement(route.handler, assign({}, props || this.props, { ref: REF_NAME })) : null;
}
};
module.exports = RouteHandlerMixin;
| var React = require('react');
var PropTypes = require('./PropTypes');
var RouteHandlerMixin = {
contextTypes: {
getRouteAtDepth: PropTypes.func.isRequired,
setRouteComponentAtDepth: PropTypes.func.isRequired,
routeHandlers: PropTypes.array.isRequired
},
childContextTypes: {
routeHandlers: PropTypes.array.isRequired
},
getChildContext: function () {
return {
routeHandlers: this.context.routeHandlers.concat([ this ])
};
},
getDefaultProps: function () {
return {
ref: '__routeHandler__'
};
},
componentDidMount: function () {
this._updateRouteComponent();
},
componentDidUpdate: function () {
this._updateRouteComponent();
},
_updateRouteComponent: function () {
this.context.setRouteComponentAtDepth(this.getRouteDepth(), this.refs[this.props.ref]);
},
getRouteDepth: function () {
return this.context.routeHandlers.length;
},
createChildRouteHandler: function (props) {
var route = this.context.getRouteAtDepth(this.getRouteDepth());
return route ? React.createElement(route.handler, props || this.props) : null;
}
};
module.exports = RouteHandlerMixin;
|
Replace list with tuple in start new thread | from django.conf.urls import patterns, include, url
import stadtgedaechtnis_backend.admin
import settings
from thread import start_new_thread
js_info_dict = {
'packages': ('stadtgedaechtnis_backend',),
}
urlpatterns = patterns(
'',
url(r'^', include('stadtgedaechtnis_backend.urls', namespace="stadtgedaechtnis_backend")),
url(r'^', include('stadtgedaechtnis_frontend.urls', namespace="stadtgedaechtnis_frontend")),
url(r'^admin/', include(stadtgedaechtnis_backend.admin.site.urls)),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, }),
)
def run_cronjobs():
"""
Runs the cronjobs. Needs to be called in a seperate thread or the main thread will be blocked.
:return:
"""
import schedule
import time
from stadtgedaechtnis_backend.import_entries.importers import do_silent_json_import
from stadtgedaechtnis_backend.import_entries.urls import JSON_URL
schedule.every().day.at("23:00").do(do_silent_json_import, JSON_URL)
while True:
schedule.run_pending()
time.sleep(1)
start_new_thread(run_cronjobs, ())
| from django.conf.urls import patterns, include, url
import stadtgedaechtnis_backend.admin
import settings
from thread import start_new_thread
js_info_dict = {
'packages': ('stadtgedaechtnis_backend',),
}
urlpatterns = patterns(
'',
url(r'^', include('stadtgedaechtnis_backend.urls', namespace="stadtgedaechtnis_backend")),
url(r'^', include('stadtgedaechtnis_frontend.urls', namespace="stadtgedaechtnis_frontend")),
url(r'^admin/', include(stadtgedaechtnis_backend.admin.site.urls)),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, }),
)
def run_cronjobs():
"""
Runs the cronjobs. Needs to be called in a seperate thread or the main thread will be blocked.
:return:
"""
import schedule
import time
from stadtgedaechtnis_backend.import_entries.importers import do_silent_json_import
from stadtgedaechtnis_backend.import_entries.urls import JSON_URL
schedule.every().day.at("23:00").do(do_silent_json_import, JSON_URL)
while True:
schedule.run_pending()
time.sleep(1)
start_new_thread(run_cronjobs, [])
|
Fix loading a channels's old messages
Order them by oldest on top | .import "../applicationShared.js" as Globals
function workerOnMessage(messageObject) {
if(messageObject.apiMethod === 'channels.history') {
addMessagesToModel(messageObject.data);
} else if(messageObject.apiMethod === 'channels.info') {
addChannelInfoToPage(messageObject.data);
} else {
console.log("Unknown api method");
}
}
function loadChannelInfo() {
var arguments = {
channel: channelPage.channelID
}
slackWorker.sendMessage({'apiMethod': "channels.info", 'token': Globals.slackToken, 'arguments': arguments });
}
function loadChannelHistory() {
var arguments = {
channel: channelPage.channelID,
count: 20
}
slackWorker.sendMessage({'apiMethod': "channels.history", 'token': Globals.slackToken, 'arguments': arguments});
}
// private
function addMessagesToModel(data) {
if(data.ok === false) {
console.log("addMessagesToModel:", data.error)
} else {
for(var i=data.messages.length-1; i >= 0; i--) {
messagesModel.append(data.messages[i]);
}
}
}
function addChannelInfoToPage(data) {
channelPage.channelPurpose = data.channel.purpose.value;
}
| .import "../applicationShared.js" as Globals
function workerOnMessage(messageObject) {
if(messageObject.apiMethod === 'channels.history') {
addMessagesToModel(messageObject.data);
} else if(messageObject.apiMethod === 'channels.info') {
addChannelInfoToPage(messageObject.data);
} else {
console.log("Unknown api method");
}
}
function loadChannelInfo() {
var arguments = {
channel: channelPage.channelID
}
slackWorker.sendMessage({'apiMethod': "channels.info", 'token': Globals.slackToken, 'arguments': arguments });
}
function loadChannelHistory() {
slackWorker.sendMessage({'apiMethod': "channels.history", 'token': Globals.slackToken});
}
// private
function addMessagesToModel(data) {
for(var i=0; i<data.messages.length; i++) {
channelList.append(data.messages[i]);
}
}
function addChannelInfoToPage(data) {
channelPage.channelPurpose = data.channel.purpose.value;
}
|
Add delay 3 times the rate limit to avoid API errors | # -*- coding: utf-8 -*-
import os
import sys
import time
# -----------------------------------------------------------------------------
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root)
# -----------------------------------------------------------------------------
import ccxt # noqa: E402
# -----------------------------------------------------------------------------
# common constants
msec = 1000
minute = 60 * msec
# -----------------------------------------------------------------------------
kraken = ccxt.kraken()
# -----------------------------------------------------------------------------
from_datetime = '2017-09-01 00:00:00'
from_timestamp = kraken.parse8601(from_datetime)
# -----------------------------------------------------------------------------
now = kraken.milliseconds()
# -----------------------------------------------------------------------------
data = []
while from_timestamp < now:
print('Fetching candles starting from', kraken.iso8601(from_timestamp))
ohlcvs = kraken.fetch_ohlcv('BTC/USD', '1m', from_timestamp)
# don't hit the rateLimit or you will be banned
time.sleep(3 * kraken.rateLimit / msec)
# Kraken returns 720 candles for 1m timeframe at once
from_timestamp += len(ohlcvs) * minute
data += ohlcvs
| # -*- coding: utf-8 -*-
import os
import sys
import time
# -----------------------------------------------------------------------------
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root)
# -----------------------------------------------------------------------------
import ccxt # noqa: E402
# -----------------------------------------------------------------------------
# common constants
msec = 1000
minute = 60 * msec
# -----------------------------------------------------------------------------
kraken = ccxt.kraken()
# -----------------------------------------------------------------------------
from_datetime = '2017-09-01 00:00:00'
from_timestamp = kraken.parse8601(from_datetime)
# -----------------------------------------------------------------------------
now = kraken.milliseconds()
# -----------------------------------------------------------------------------
while from_timestamp < now:
print('Fetching candles starting from', kraken.iso8601(from_timestamp))
ohlcvs = kraken.fetch_ohlcv('BTC/USD', '1m', from_timestamp)
# don't hit the rateLimit or you will be banned
time.sleep(kraken.rateLimit / msec)
# Kraken returns 720 candles for 1m timeframe at once
from_timestamp += len(ohlcvs) * minute
|
Update twig helper to work with the last version of twig | <?php
namespace Bundle\GravatarBundle\Twig\Extension;
use Symfony\Bundle\TwigBundle\TokenParser\HelperTokenParser;
class GravatarTwigExtension extends \Twig_Extension
{
/**
* Returns the token parser instance to add to the existing list.
*
* @return array An array of Twig_TokenParser instances
*/
public function getTokenParsers()
{
return array(
// {% gravatar email with {size: 80 } %}
new HelperTokenParser('gravatar', '<email> [with <options>]', 'templating.helper.gravatar', 'render'),
);
}
public function getName()
{
return 'gravatar';
}
} | <?php
namespace Bundle\GravatarBundle\Twig\Extension;
use Symfony\Bundle\TwigBundle\TokenParser\HelperTokenParser;
class GravatarTwigExtension extends \Twig_Extension
{
/**
* Returns the token parser instance to add to the existing list.
*
* @return array An array of Twig_TokenParser instances
*/
public function getTokenParsers()
{
return array(
// {% gravatar email with [size: 80 ] %}
new HelperTokenParser('gravatar', '<email> [with <options:array>]', 'templating.helper.gravatar', 'render'),
);
}
public function getName()
{
return 'gravatar';
}
} |
Make updatedAt modifying node.id in Source nodes | 'use strict';
var Node = require('../node');
var TYPE = 'source';
var PARAMS = {
query: Node.PARAM.STRING()
};
var Source = Node.create(TYPE, PARAMS, {
beforeCreate: function(node) {
// Last updated time in source node means data changed so it has to modify node.id
node.setAttributeToModifyId('updatedAt');
}
});
module.exports = Source;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;
Source.prototype.sql = function() {
return this.query;
};
Source.prototype.setColumnsNames = function(columns) {
this.columns = columns;
// Makes columns affecting Node.id().
// When a `select * from table` might end in a different set of columns
// we want to have a different node.
this.setAttributeToModifyId('columns');
};
/**
* Source nodes are ready by definition
*
* @returns {Node.STATUS}
*/
Source.prototype.getStatus = function() {
return Node.STATUS.READY;
};
Source.prototype.getAndSetUpdatedAt = function(databaseService, callback) {
if (this.updatedAt !== null) {
return callback(null, this.updatedAt);
}
databaseService.getLastUpdatedTimeFromAffectedTables(this.sql(), function(err, lastUpdatedAt) {
if (err) {
return callback(err);
}
this.updatedAt = lastUpdatedAt;
return callback(null, this.updatedAt);
}.bind(this));
};
| 'use strict';
var Node = require('../node');
var TYPE = 'source';
var PARAMS = {
query: Node.PARAM.STRING()
};
var Source = Node.create(TYPE, PARAMS);
module.exports = Source;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;
Source.prototype.sql = function() {
return this.query;
};
Source.prototype.setColumnsNames = function(columns) {
this.columns = columns;
// Makes columns affecting Node.id().
// When a `select * from table` might end in a different set of columns
// we want to have a different node.
this.setAttributeToModifyId('columns');
};
/**
* Source nodes are ready by definition
*
* @returns {Node.STATUS}
*/
Source.prototype.getStatus = function() {
return Node.STATUS.READY;
};
Source.prototype.getAndSetUpdatedAt = function(databaseService, callback) {
if (this.updatedAt !== null) {
return callback(null, this.updatedAt);
}
databaseService.getLastUpdatedTimeFromAffectedTables(this.sql(), function(err, lastUpdatedAt) {
if (err) {
return callback(err);
}
this.updatedAt = lastUpdatedAt;
return callback(null, this.updatedAt);
}.bind(this));
};
|
Make validation errors fit standard error formatting. | <?php
namespace Northstar\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Northstar\Http\Controllers\Traits\FiltersRequests;
use Northstar\Http\Controllers\Traits\TransformsResponses;
use Illuminate\Http\Request;
abstract class Controller extends BaseController
{
use DispatchesJobs, ValidatesRequests, FiltersRequests, TransformsResponses;
/**
* Create the response for when a request fails validation. Overrides the
* `buildFailedValidationResponse` method from the `ValidatesRequests` trait.
*
* @param \Illuminate\Http\Request $request
* @param array $errors
* @return \Illuminate\Http\Response
*/
protected function buildFailedValidationResponse(Request $request, array $errors)
{
$response = [
'error' => [
'code' => 422,
'message' => 'Failed validation.',
'fields' => $errors,
],
];
return response()->json($response, 422);
}
}
| <?php
namespace Northstar\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Northstar\Http\Controllers\Traits\FiltersRequests;
use Northstar\Http\Controllers\Traits\TransformsResponses;
use Illuminate\Http\Request;
abstract class Controller extends BaseController
{
use DispatchesJobs, ValidatesRequests, FiltersRequests, TransformsResponses;
/**
* Create the response for when a request fails validation. Overrides the
* `buildFailedValidationResponse` method from the `ValidatesRequests` trait.
*
* @param \Illuminate\Http\Request $request
* @param array $errors
* @return \Illuminate\Http\Response
*/
protected function buildFailedValidationResponse(Request $request, array $errors)
{
$response = [
'code' => 422,
'message' => 'Failed validation.',
'errors' => $errors,
];
return response()->json($response, 422);
}
}
|
Fix a pack test with the new Question field | package dns
import (
"encoding/binary"
"testing"
)
func TestPack(t *testing.T) {
m := &Message{
Question: make([]Q, 1),
}
m.Question[0] = Q{
Name: "www.sekimura.org.",
Type: QtypeA,
Class: QclassIN,
}
b, err := Pack(m)
if err != nil {
t.Error(err)
}
if b[12] != 0x3 || string(b[13:16]) != "www" {
t.Error("the first label did not match")
}
if b[16] != 0x8 || string(b[17:25]) != "sekimura" {
t.Error("the second label did not match")
}
if b[25] != 0x3 || string(b[26:29]) != "org" {
t.Error("the third label did not match")
}
if b[29] != 0x0 {
t.Error("missing the termination")
}
if QtypeA != binary.BigEndian.Uint16(b[30:32]) {
t.Errorf("Qtype did not match")
}
if QclassIN != binary.BigEndian.Uint16(b[32:34]) {
t.Error("Qclass did not match")
}
}
| package dns
import (
"encoding/binary"
"testing"
)
func TestPack(t *testing.T) {
m := &Message{
QName: "www.sekimura.org.",
Qtype: QtypeA,
Qclass: QclassIN,
}
b, err := Pack(m)
if err != nil {
t.Error(err)
}
if b[12] != 0x3 || string(b[13:16]) != "www" {
t.Error("the first label did not match")
}
if b[16] != 0x8 || string(b[17:25]) != "sekimura" {
t.Error("the second label did not match")
}
if b[25] != 0x3 || string(b[26:29]) != "org" {
t.Error("the third label did not match")
}
if b[29] != 0x0 {
t.Error("missing the termination")
}
if QtypeA != binary.BigEndian.Uint16(b[30:32]) {
t.Errorf("Qtype did not match")
}
if QclassIN != binary.BigEndian.Uint16(b[32:34]) {
t.Error("Qclass did not match")
}
}
|
Fix the network service provider test
This test was pretty lame before since it just verified that
the result was a string. Now it verifies that at least one
service provider exists and I think I picked one that should
be aroudn for a while. The test failure message also prints
the list of providers now so it should be easier to debug.
Partial-bug: #1665495
Change-Id: Ief96558770d81dca81091e235b8d370883b14b94 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstack.tests.functional import base
class TestServiceProvider(base.BaseFunctionalTest):
def test_list(self):
providers = list(self.conn.network.service_providers())
names = [o.name for o in providers]
service_types = [o.service_type for o in providers]
self.assertIn('ha', names)
self.assertIn('L3_ROUTER_NAT', service_types)
| # 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.
import six
from openstack.tests.functional import base
class TestServiceProvider(base.BaseFunctionalTest):
def test_list(self):
providers = list(self.conn.network.service_providers())
for provide in providers:
self.assertIsInstance(provide.name, six.string_type)
self.assertIsInstance(provide.service_type, six.string_types)
|
Remove erroneous call to property length | /**
* This demo is meant to be straight-forward and
* not use very complex techniques, such as regular
* expressions.
*
*/
function throwFormatError() {
throw "You should enter a value in the form \"$987.52\" with a dollar sign and optionally two decimal places.";
}
function demo1(numeric) {
var text = "";
// Validation of the input
if (numeric.length < 1) {
throwFormatError();
}
if (numeric[0] != "$") {
throwFormatError();
}
// Strip off the dollar sign
numeric = numeric.substring(1);
// Validate that cents portion is either of length 0 or 2
var decimalPos = numeric.lastIndexOf(".");
if (decimalPos != -1 && decimalPos != numeric.length - 4) {
throwFormatError();
}
var cents = numeric.substring(decimalPos);
numeric = numeric.substring(0, decimalPos - 1);
text = numeric + " / " + cents;
return text;
}
/**
* demo2 uses regular expressions.
*
*/
function demo2(numeric) {
}
| /**
* This demo is meant to be straight-forward and
* not use very complex techniques, such as regular
* expressions.
*
*/
function throwFormatError() {
throw "You should enter a value in the form \"$987.52\" with a dollar sign and optionally two decimal places.";
}
function demo1(numeric) {
var text = "";
// Validation of the input
if (numeric.length() < 1) {
throwFormatError();
}
if (numeric[0] != "$") {
throwFormatError();
}
// Strip off the dollar sign
numeric = numeric.substring(1);
// Validate that cents portion is either of length 0 or 2
var decimalPos = numeric.lastIndexOf(".");
if (decimalPos != -1 && decimalPos != numeric.length() - 4) {
throwFormatError();
}
var cents = numeric.substring(decimalPos);
numeric = numeric.substring(0, decimalPos - 1);
text = numeric + " / " + cents;
return text;
}
/**
* demo2 uses regular expressions.
*
*/
function demo2(numeric) {
}
|
[OWL-1594] Add checking of least value on cache timeout(non-debug mode) | package rpc
import (
viper "github.com/spf13/viper"
log "github.com/Cepave/open-falcon-backend/common/logruslog"
nqmService "github.com/Cepave/open-falcon-backend/common/service/nqm"
)
var logger = log.NewDefaultLogger("INFO")
func InitPackage(config *viper.Viper) {
initNqmConfig(config)
}
func initNqmConfig(config *viper.Viper) {
config.SetDefault("nqm.queue_size.refresh_agent_ping_list", 8)
config.SetDefault("nqm.cache_minutes.agent_ping_list", 20)
nqmConfig := nqmService.AgentHbsServiceConfig {
QueueSizeOfRefreshCacheOfPingList: config.GetInt("nqm.queue_size.refresh_agent_ping_list"),
CacheTimeoutMinutes: config.GetInt("nqm.cache_minutes.agent_ping_list"),
}
/**
* If the mode is not in debug, the least timeout is 10 minutes
*/
if !config.GetBool("debug") && config.GetInt("nqm.cache_minutes.agent_ping_list") < 5 {
nqmConfig.CacheTimeoutMinutes = 5
}
// :~)
nqmAgentHbsService = nqmService.NewAgentHbsService(nqmConfig)
logger.Infof("[NQM] Ping list of agent. Timeout: %d minutes. Queue Size: %d",
nqmConfig.CacheTimeoutMinutes, nqmConfig.QueueSizeOfRefreshCacheOfPingList,
)
}
| package rpc
import (
viper "github.com/spf13/viper"
log "github.com/Cepave/open-falcon-backend/common/logruslog"
nqmService "github.com/Cepave/open-falcon-backend/common/service/nqm"
)
var logger = log.NewDefaultLogger("INFO")
func InitPackage(config *viper.Viper) {
config.SetDefault("nqm.queue_size.refresh_agent_ping_list", 8)
config.SetDefault("nqm.cache_minutes.agent_ping_list", 20)
nqmConfig := nqmService.AgentHbsServiceConfig {
QueueSizeOfRefreshCacheOfPingList: config.GetInt("nqm.queue_size.refresh_agent_ping_list"),
CacheTimeoutMinutes: config.GetInt("nqm.cache_minutes.agent_ping_list"),
}
nqmAgentHbsService = nqmService.NewAgentHbsService(nqmConfig)
logger.Infof("[NQM] Ping list of agent. Timeout: %d minutes. Queue Size: %d",
nqmConfig.CacheTimeoutMinutes, nqmConfig.QueueSizeOfRefreshCacheOfPingList,
)
}
|
Use util.log in main process
Includes timestamps. | 'use strict';
var app = require('app');
var BrowserWindow = require('browser-window');
var ipc = require('ipc');
var util = require('util');
var config = require('./config');
ipc.on('load-schedule', function(event) {
util.log('Recieved load-schedule request');
config.loadSchedule()
.then(function(schedule) {
event.sender.send('schedule', schedule);
})
.catch(function(err) {
event.sender.send('schedule', null);
});
});
ipc.on('save-schedule', function(event, schedule) {
util.log('Recieved save-schedule request');
config.saveSchedule(schedule);
});
ipc.on('reload', function (event) {
util.log('Recieved reload request');
BrowserWindow.getFocusedWindow().reloadIgnoringCache();
});
| 'use strict';
var app = require('app');
var BrowserWindow = require('browser-window');
var ipc = require('ipc');
var config = require('./config');
ipc.on('load-schedule', function(event) {
console.log('Recieved load-schedule request');
config.loadSchedule()
.then(function(schedule) {
event.sender.send('schedule', schedule);
})
.catch(function(err) {
event.sender.send('schedule', null);
});
});
ipc.on('save-schedule', function(event, schedule) {
console.log('Recieved save-schedule request');
config.saveSchedule(schedule);
});
ipc.on('reload', function (event) {
console.log('Recieved reload request');
BrowserWindow.getFocusedWindow().reloadIgnoringCache();
});
|
Add options to use bind/unbind callbacks as opposed to mount/unmount
Reviewed By: oprisnik
Differential Revision: D15122179
fbshipit-source-id: 28b734a0fb0899b4a28e9cdacb31658480149ca2 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.vito.core;
import javax.annotation.Nullable;
/** Fresco experiment class with default values. Override this class to change them. */
public class FrescoExperiments {
public boolean prepareImagePipelineComponents() {
return false;
}
public boolean checkCacheInAttach() {
return true;
}
public int mountContentPoolSize() {
// Default Litho mount pool size
return 3;
}
public boolean mountContentPoolSync() {
// Default Litho mount pool sync value
return true;
}
public boolean prefetchInOnPrepare() {
return false;
}
public boolean keepRefToPrefetchDatasouce() {
return false;
}
public boolean prepareActualImageWrapperInBackground() {
return true;
}
public boolean preparePlaceholderDrawableInBackground() {
return false;
}
public boolean keepRefToMainFetchDatasouce() {
return true;
}
public @Nullable Boolean prefetchToBitmapCache() {
return null;
}
public boolean closeDatasource() {
return true;
}
public boolean cacheImageInState() {
return false;
}
public boolean shouldDiffCallerContext() {
return false;
}
public void setupPropDiffingExperiment() {}
public boolean fadeInImages() {
return false;
}
public boolean useBindCallbacks() {
return false;
}
}
| /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.vito.core;
import javax.annotation.Nullable;
/** Fresco experiment class with default values. Override this class to change them. */
public class FrescoExperiments {
public boolean prepareImagePipelineComponents() {
return false;
}
public boolean checkCacheInAttach() {
return true;
}
public int mountContentPoolSize() {
// Default Litho mount pool size
return 3;
}
public boolean mountContentPoolSync() {
// Default Litho mount pool sync value
return true;
}
public boolean prefetchInOnPrepare() {
return false;
}
public boolean keepRefToPrefetchDatasouce() {
return false;
}
public boolean prepareActualImageWrapperInBackground() {
return true;
}
public boolean preparePlaceholderDrawableInBackground() {
return false;
}
public boolean keepRefToMainFetchDatasouce() {
return true;
}
public @Nullable Boolean prefetchToBitmapCache() {
return null;
}
public boolean closeDatasource() {
return true;
}
public boolean cacheImageInState() {
return false;
}
public boolean shouldDiffCallerContext() {
return false;
}
public void setupPropDiffingExperiment() {}
public boolean fadeInImages() {
return false;
}
}
|
Fix add line function in core data container | <?php
class CoreData
{
private $containers = array();
public $current_container;
public function __construct($content) {
$this -> newContainer();
$this -> parse_content($content);
}
// this function should be overridden to parse the content and create a set of collections with lines
// and possibly links
public function parse_content($content) {
// we want to import $content as JSON for CoreData - other interpretations for other types
//$json = json_decode($content);
// loop through pages
}
public function to_json() {
// outputs a JSON representation of the containers and lines
}
public function newContainer($url = "") {
$c = new CoreDataContainer($url);
print var_dump($this -> current_container);
$this -> containers[] = $c;
$this -> current_container = $c;
}
}
class CoreDataContainer {
private $lines = array();
public $image_url = "";
public function __construct($url = "") {
$this -> image_url = $url;
}
public function addLine($line) {
print "Adding [$line]\n";
$this -> lines[] = $line;
}
}
?> | <?php
class CoreData
{
private $containers = array();
public $current_container;
public function __construct($content) {
$this -> newContainer();
$this -> parse_content($content);
}
// this function should be overridden to parse the content and create a set of collections with lines
// and possibly links
public function parse_content($content) {
// we want to import $content as JSON for CoreData - other interpretations for other types
//$json = json_decode($content);
// loop through pages
}
public function to_json() {
// outputs a JSON representation of the containers and lines
}
public function newContainer($url = "") {
$c = new CoreDataContainer($url);
print var_dump($this -> current_container);
$this -> containers[] = $c;
$this -> current_container = $c;
}
}
class CoreDataContainer {
private $lines = array();
public $image_url = "";
public function __construct($url = "") {
$this -> image_url = $url;
}
public function addLine($line) {
print "Adding [$line]\n";
$lines[] = $line;
}
}
?> |
Refactoring: Move code into function for better readability | <?php
/**
* @title Birthday Cron Class
*
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Core / Asset / Cron / 24H
* @version 1.0
*/
namespace PH7;
defined('PH7') or exit('Restricted access');
class BirthdayCoreCron extends Cron
{
/** @var int */
private $iNum;
public function __construct()
{
parent::__construct();
$this->send();
}
protected function send()
{
$$this->iNum = (new BirthdayCore)->sendMails();
if ($this->hasBirthdays()) {
echo t('No birthday today.');
} else {
echo nt('%n% email sent.', '%n% emails sent.', $iNum);
}
}
/**
* @return bool
*/
private function hasBirthdays()
{
return $this->iNum === 0;
}
}
// Go!
new BirthdayCoreCron;
| <?php
/**
* @title Birthday Cron Class
*
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Core / Asset / Cron / 24H
* @version 1.0
*/
namespace PH7;
defined('PH7') or exit('Restricted access');
class BirthdayCoreCron extends Cron
{
public function __construct()
{
parent::__construct();
$this->send();
}
protected function send()
{
$iNum = (new BirthdayCore)->sendMails();
if ($iNum === 0) {
echo t('No birthday today.');
} else {
echo nt('%n% email sent.', '%n% emails sent.', $iNum);
}
}
}
// Go!
new BirthdayCoreCron;
|
Return reference from offset get | <?php
namespace LiftKit\Session;
use LiftKit\Session\Exception\Session as SessionException;
use ArrayAccess;
class Session implements ArrayAccess
{
public function __construct ($name = null)
{
$this->start($name);
}
public function start ($name)
{
if ($name) {
session_name($name);
}
if (! isset($_SESSION)) {
if (! headers_sent($file, $line)) {
if (! session_start()) {
throw new SessionException(__METHOD__ . ' session_start failed.');
}
} else {
throw new SessionException(__METHOD__ . ' session started after headers sent. Output began at: ' . $file . ':' . $line);
}
}
}
public function offsetExists ($variable)
{
return isset($_SESSION[$variable]);
}
public function & offsetGet ($variable)
{
return $_SESSION[$variable];
}
public function offsetSet ($variable, $value)
{
$_SESSION[$variable] = $value;
}
public function offsetUnset ($variable)
{
unset($_SESSION[$variable]);
}
public function destroy ()
{
session_destroy();
}
} | <?php
namespace LiftKit\Session;
use LiftKit\Session\Exception\Session as SessionException;
use ArrayAccess;
class Session implements ArrayAccess
{
public function __construct ($name = null)
{
$this->start($name);
}
public function start ($name)
{
if ($name) {
session_name($name);
}
if (! isset($_SESSION)) {
if (! headers_sent($file, $line)) {
if (! session_start()) {
throw new SessionException(__METHOD__ . ' session_start failed.');
}
} else {
throw new SessionException(__METHOD__ . ' session started after headers sent. Output began at: ' . $file . ':' . $line);
}
}
}
public function offsetExists ($variable)
{
return isset($_SESSION[$variable]);
}
public function offsetGet ($variable)
{
return $_SESSION[$variable];
}
public function offsetSet ($variable, $value)
{
$_SESSION[$variable] = $value;
}
public function offsetUnset ($variable)
{
unset($_SESSION[$variable]);
}
public function destroy ()
{
session_destroy();
}
} |
Add classifiers since python3 now supported | import os
from setuptools import setup
setup(
name = "pyscribe",
version = "0.1.1",
author = "Alexander Wang",
author_email = "alexanderw@berkeley.edu",
description = ("PyScribe makes print debugging easier and more efficient"),
license = "MIT",
keywords = "python pyscribe debug print",
url = "https://github.com/alixander/pyscribe",
download_url = "https://github.com/alixander/pyscribe/tarbell/0.1.2",
entry_points={
'console_scripts': [
'pyscribe = pyscribe.pyscribe:main',
],
},
packages=['pyscribe'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
)
| import os
from setuptools import setup
setup(
name = "pyscribe",
version = "0.1.1",
author = "Alexander Wang",
author_email = "alexanderw@berkeley.edu",
description = ("PyScribe makes print debugging easier and more efficient"),
license = "MIT",
keywords = "python pyscribe debug print",
url = "https://github.com/alixander/pyscribe",
download_url = "https://github.com/alixander/pyscribe/tarbell/0.1.1",
entry_points={
'console_scripts': [
'pyscribe = pyscribe.pyscribe:main',
],
},
packages=['pyscribe'],
classifiers=[
"Development Status :: 3 - Alpha"
],
)
|
Set `menu_name` to improve consistency within the dashboard | <?php
/* ------------------------------------------------------------------------ *\
* Post Types
\* ------------------------------------------------------------------------ */
/**
* Register resource post type
*
* @return void
*/
function __gulp_init_namespace___create_resource_post_type(): void {
register_extended_post_type("resource", [
"menu_icon" => "dashicons-admin-links",
],
[
"plural" => __("Resources", "__gulp_init_namespace__"),
"singular" => __("Resource", "__gulp_init_namespace__"),
"slug" => "resource",
]);
register_extended_taxonomy("resource_tag", "resource", [
"hierarchical" => false,
"labels" => [
"menu_name" => __("Tags", "__gulp_init_namespace__"),
],
],
[
"plural" => __("Resource Tags", "__gulp_init_namespace__"),
"singular" => __("Resource Tag", "__gulp_init_namespace__"),
"slug" => "",
]);
}
add_action("init", "__gulp_init_namespace___create_resource_post_type");
| <?php
/* ------------------------------------------------------------------------ *\
* Post Types
\* ------------------------------------------------------------------------ */
/**
* Register resource post type
*
* @return void
*/
function __gulp_init_namespace___create_resource_post_type(): void {
register_extended_post_type("resource", [
"menu_icon" => "dashicons-admin-links",
],
[
"plural" => __("Resources", "__gulp_init_namespace__"),
"singular" => __("Resource", "__gulp_init_namespace__"),
"slug" => "resource",
]);
register_extended_taxonomy("resource_tag", "resource", [
"hierarchical" => false,
],
[
"plural" => __("Resource Tags", "__gulp_init_namespace__"),
"singular" => __("Resource Tag", "__gulp_init_namespace__"),
"slug" => "",
]);
}
add_action("init", "__gulp_init_namespace___create_resource_post_type");
|
Store last world dimension and compare with current to determine if world changed. If so update the time offset. | package tld.testmod.common.animation;
import net.minecraft.world.World;
import net.minecraftforge.client.model.animation.Animation;
public enum ModAnimation
{
INSTANCE;
static long timeOffset;
static int lastDimension = Integer.MAX_VALUE;
/**
* Get the global world time for the current tick, in seconds.
*/
public static float getWorldTime(World world)
{
return getWorldTime(world, 0);
}
/**
* Get the global world time for the current tick + partial tick progress, in seconds.
*/
public static float getWorldTime(World world, float tickProgress)
{
int dimension = world.provider.getDimension();
if (dimension != lastDimension)
{
timeOffset = world.getTotalWorldTime();
lastDimension = dimension;
}
//long diff = world.getTotalWorldTime() - timeOffset;
//ModLogger.info("Animation#getWorldTime: Dimension: %d, time: %d, offset %d, diff: %d", lastDimension, world.getTotalWorldTime(), timeOffset, diff);
return (world.getTotalWorldTime() - timeOffset + tickProgress) / 20;
}
/**
* Get current partialTickTime.
*/
public static float getPartialTickTime()
{
return Animation.getPartialTickTime();
}
}
| package tld.testmod.common.animation;
import net.minecraft.world.World;
import net.minecraftforge.client.model.animation.Animation;
public enum ModAnimation
{
INSTANCE;
static long timeOffset;
static int lastWorldHashCode;
/**
* Get the global world time for the current tick, in seconds.
*/
public static float getWorldTime(World world)
{
return getWorldTime(world, 0);
}
/**
* Get the global world time for the current tick + partial tick progress, in seconds.
*/
public static float getWorldTime(World world, float tickProgress)
{
int worldHashCode = world.hashCode();
if (worldHashCode != lastWorldHashCode)
{
timeOffset = world.getTotalWorldTime();
lastWorldHashCode = worldHashCode;
}
//long diff = world.getTotalWorldTime() - timeOffset;
//ModLogger.info("Animation#getWorldTime: World: %s, time: %d, offset %d, diff: %d", lastWorldHashCode, world.getTotalWorldTime(), timeOffset, diff);
return (world.getTotalWorldTime() - timeOffset + tickProgress) / 20;
}
/**
* Get current partialTickTime.
*/
public static float getPartialTickTime()
{
return Animation.getPartialTickTime();
}
}
|
Make sure publisher is totally hidden in bookmarklet after post success | app.views.Bookmarklet = Backbone.View.extend({
separator: ' - ',
initialize: function(opts) {
// init a standalone publisher
app.publisher = new app.views.Publisher({standalone: true});
app.publisher.on('publisher:add', this._postSubmit, this);
app.publisher.on('publisher:sync', this._postSuccess, this);
app.publisher.on('publisher:error', this._postError, this);
this.param_contents = opts;
},
render: function() {
app.publisher.open();
app.publisher.setText(this._publisherContent());
return this;
},
_publisherContent: function() {
var p = this.param_contents;
if( p.content ) return p.content;
var contents = p.title + this.separator + p.url;
if( p.notes ) contents += this.separator + p.notes;
return contents;
},
_postSubmit: function(evt) {
this.$('h4').text(Diaspora.I18n.t('bookmarklet.post_submit'));
},
_postSuccess: function(evt) {
this.$('h4').text(Diaspora.I18n.t('bookmarklet.post_success'));
app.publisher.close();
this.$("#publisher").addClass("hidden");
_.delay(window.close, 2000);
},
_postError: function(evt) {
this.$('h4').text(Diaspora.I18n.t('bookmarklet.post_error'));
}
});
| app.views.Bookmarklet = Backbone.View.extend({
separator: ' - ',
initialize: function(opts) {
// init a standalone publisher
app.publisher = new app.views.Publisher({standalone: true});
app.publisher.on('publisher:add', this._postSubmit, this);
app.publisher.on('publisher:sync', this._postSuccess, this);
app.publisher.on('publisher:error', this._postError, this);
this.param_contents = opts;
},
render: function() {
app.publisher.open();
app.publisher.setText(this._publisherContent());
return this;
},
_publisherContent: function() {
var p = this.param_contents;
if( p.content ) return p.content;
var contents = p.title + this.separator + p.url;
if( p.notes ) contents += this.separator + p.notes;
return contents;
},
_postSubmit: function(evt) {
this.$('h4').text(Diaspora.I18n.t('bookmarklet.post_submit'));
},
_postSuccess: function(evt) {
this.$('h4').text(Diaspora.I18n.t('bookmarklet.post_success'));
app.publisher.close();
_.delay(window.close, 2000);
},
_postError: function(evt) {
this.$('h4').text(Diaspora.I18n.t('bookmarklet.post_error'));
}
});
|
Use <pre> to increase readability | /*
#
# i2mx.js - v0.1-Alpha
# Apache v2 License
#
*/
// Create img2musicXML (abbreviated as i2mx) namespace
var i2mx = i2mx || { };
// Create JsCheckup class (@TODO: Move to inside namespace)
var JsCheckup = function() {
this.divId = "i2mx-checkup";
this.activate = function() {
// @TODO: Use HTML generator
// Initial values
var div = document.getElementById(this.divId);
var EOL = "<br>"
var checkupText = "<pre>";
// Start testing
checkupText += "Starting tests... " + EOL;
if(window.File && window.FileReader && window.FileList && window.Blob) {
checkupText += "File and Blob APIs -> OK " + EOL;
}
// Update DOM
checkupText += "</pre>";
div.innerHTML = checkupText;
}
}
var jsCheckup = new JsCheckup();
// @TODO: Use event listener instead of onload
window.onload = function() {
jsCheckup.activate();
}
| /*
#
# i2mx.js - v0.1-Alpha
# Apache v2 License
#
*/
// Create img2musicXML (abbreviated as i2mx) namespace
var i2mx = i2mx || { };
// Create JsCheckup class (@TODO: Move to inside namespace)
var JsCheckup = function() {
this.divId = "i2mx-checkup";
this.activate = function() {
// @TODO: Use HTML generator
// Initial values
var div = document.getElementById(this.divId);
var EOL = "<br>"
var checkupText = "";
// Start testing
checkupText += "Starting tests... " + EOL;
if(window.File && window.FileReader && window.FileList && window.Blob) {
checkupText += "File and Blob APIs -> OK " + EOL;
}
// Update DOM
div.innerHTML = checkupText;
}
}
var jsCheckup = new JsCheckup();
// @TODO: Use event listener instead of onload
window.onload = function() {
jsCheckup.activate();
}
|
Handle exit code properly based on match count
Now exits with value of 0 if one or more lines match pattern
Otherwise exits with value of 1 | // go build -o gogrep
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
if len(os.Args) < 3 {
fatal(2, "Usage: %s <pattern> <file>\n", os.Args[0])
}
pat := os.Args[1]
file := os.Args[2]
cnt, err := printMatchingLines(pat, file)
if err != nil {
fatal(2, err.Error())
}
if cnt > 0 {
os.Exit(0)
} else {
os.Exit(1)
}
}
func fatal(exitVal int, msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg, args...)
os.Exit(exitVal)
}
func printMatchingLines(pat string, file string) (int, error) {
f, err := os.Open(file)
if err != nil {
return 0, err
}
defer f.Close()
matchCnt := 0
scan := bufio.NewScanner(bufio.NewReader(f))
for scan.Scan() {
line := scan.Text()
if strings.Contains(line, pat) {
fmt.Println(line)
matchCnt++
}
}
if scan.Err() != nil {
return matchCnt, scan.Err()
}
return matchCnt, nil
}
| // go build -o gogrep
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
if len(os.Args) < 3 {
fatal(2, "Usage: %s <pattern> <file>\n", os.Args[0])
}
pat := os.Args[1]
file := os.Args[2]
err := printMatchingLines(pat, file)
if err != nil {
fatal(2, err.Error())
}
}
func fatal(exitVal int, msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg, args...)
os.Exit(exitVal)
}
func printMatchingLines(pat string, file string) error {
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
scan := bufio.NewScanner(bufio.NewReader(f))
for scan.Scan() {
line := scan.Text()
if strings.Contains(line, pat) {
fmt.Println(line)
}
}
if scan.Err() != nil {
return scan.Err()
}
return nil
}
|
Use serviceWorker.ready.then before calling subscribe |
function register() {
navigator.serviceWorker.register("sw.js", {scope: '/'});
navigator.serviceWorker.ready.then(
function(swr) {
swr.pushManager.subscribe().then(
function(pushSubscription) {
var data = new FormData();
data.append('endpoint', pushSubscription.endpoint);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/register");
xhr.onload = function () {
window.location = "/manage"
};
xhr.send(data);
},
function(error) {
console.log(error);
}
);
}
);
}
addEventListener("load", register, false);
|
function register() {
navigator.serviceWorker.register("sw.js", {scope: '/'}).then(
function(serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.subscribe().then(
function(pushSubscription) {
console.log(pushSubscription.endpoint);
var data = new FormData();
data.append('endpoint', pushSubscription.endpoint);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/register");
xhr.onload = function () {
console.log(this.responseText);
window.location = "/manage"
};
xhr.send(data);
}, function(error) {
console.log(error);
}
);
}
);
}
addEventListener("load", register, false);
|
Fix an error when the arguments are complete | var Runner = require('./runner').Runner,
_ = require('underscore');
var argv = require('optimist')
.string('a')
.string('w')
.string('p')
.string('u')
.argv;
var numAIs = 4;
var aiCommands = argv.a,
workingDirs = argv.w,
pauseCommands = argv.p,
unpauseCommands = argv.u;
aiCommands = fixArgument(aiCommands, 'python ai/ai.py', numAIs);
workingDirs = fixArgument(workingDirs, '', numAIs);
pauseCommands = fixArgument(pauseCommands, '', numAIs);
unpauseCommands = fixArgument(unpauseCommands, '', numAIs);
console.warn('AI Commands: ' + JSON.stringify(aiCommands));
console.warn('Working Dirs: ' + JSON.stringify(workingDirs));
console.warn('Pause Commands: ' + JSON.stringify(pauseCommands));
console.warn('Unpause Commands: ' + JSON.stringify(unpauseCommands));
var runner = new Runner(aiCommands, workingDirs);
runner.runGame(function () {
console.log(JSON.stringify(runner.gameResult));
});
function fixArgument(argument, defaultValue, numAIs) {
var fixedArgument = argument || [];
if (!_.isArray(fixedArgument)) {
fixedArgument = [fixedArgument];
}
while (fixedArgument.length < numAIs) {
fixedArgument.push(defaultValue);
}
return fixedArgument;
}
| var Runner = require('./runner').Runner,
_ = require('underscore');
var argv = require('optimist')
.string('a')
.string('w')
.string('p')
.string('u')
.argv;
var numAIs = 4;
var aiCommands = argv.a,
workingDirs = argv.w,
pauseCommands = argv.p,
unpauseCommands = argv.u;
aiCommands = fixArgument(aiCommands, 'python ai/ai.py', numAIs);
workingDirs = fixArgument(workingDirs, '', numAIs);
pauseCommands = fixArgument(pauseCommands, '', numAIs);
unpauseCommands = fixArgument(unpauseCommands, '', numAIs);
console.warn('AI Commands: ' + JSON.stringify(aiCommands));
console.warn('Working Dirs: ' + JSON.stringify(workingDirs));
var runner = new Runner(aiCommands, workingDirs);
runner.runGame(function () {
console.log(JSON.stringify(runner.gameResult));
});
function fixArgument(argument, defaultValue, numAIs) {
if (!_.isArray(argument)) {
fixedArgument = argument ? [argument] : [];
}
while (fixedArgument.length < numAIs) {
fixedArgument.push(defaultValue);
}
return fixedArgument;
}
|
Make raf loop a method of Fluzo | 'use strict';
var postal = require('postal');
var raf = require('raf');
var FluzoStore = require('fluzo-store')(postal);
var fluzo_channel = postal.channel('fluzo');
var render_pending = false;
var render_suscriptions = [];
var Fluzo = {
Store: FluzoStore,
action: FluzoStore.action,
clearRenderRequests: function () {
render_pending = false;
},
requestRender: function () {
render_pending = true;
},
onRender: function (cb) {
render_suscriptions.push(cb);
var index = render_suscriptions.length - 1;
return function () {
render_suscriptions.splice(index, 1);
};
},
renderIfRequested: function (delta) {
if (render_pending) {
var now = Date.now();
render_suscriptions.forEach(function (cb) {
cb(now, delta);
});
this.clearRenderRequests();
}
},
start: function () {
(function tick(delta) {
raf(tick);
Fluzo.renderIfRequested(delta);
})(0);
}
};
fluzo_channel.subscribe('store.changed.*', Fluzo.requestRender);
module.exports = Fluzo;
| 'use strict';
var postal = require('postal');
var raf = require('raf');
var FluzoStore = require('fluzo-store')(postal);
var fluzo_channel = postal.channel('fluzo');
var render_pending = false;
var render_suscriptions = [];
var Fluzo = {
Store: FluzoStore,
action: FluzoStore.action,
clearRenderRequests: function () {
render_pending = false;
},
requestRender: function () {
render_pending = true;
},
onRender: function (cb) {
render_suscriptions.push(cb);
var index = render_suscriptions.length - 1;
return function () {
render_suscriptions.splice(index, 1);
};
},
renderIfRequested: function (delta) {
if (render_pending) {
var now = Date.now();
render_suscriptions.forEach(function (cb) {
cb(now, delta);
});
this.clearRenderRequests();
}
}
};
fluzo_channel.subscribe('store.changed.*', Fluzo.requestRender);
(function tick(delta) {
raf(tick);
Fluzo.renderIfRequested(delta);
})(0);
module.exports = Fluzo;
|
Choose random gif instead of 0th (giphy search order !rand) | #! /usr/bin/env node
"use strict";
const login = require("facebook-chat-api");
const giphy = require("giphy-api")();
const confg = require("./config");
login({email: confg.EMAIL, password: confg.PASS}, function callback(err, api) {
if (err) return console.error(err);
api.listen(function callback(err, message) {
var msg = message.body.toLowerCase();
if (msg.includes("/kick")) {
if (msg.includes("swar"))
api.removeUserFromGroup(confg.SWAR, message.threadID);
else if (msg.includes("kaartikey"))
api.removeUserFromGroup(confg.KAARTIKEY, message.threadID);
else if (msg.includes("anuj"))
api.removeUserFromGroup(confg.ANUJ, message.threadID);
}
if (msg === "/say hi")
api.sendMessage("Hello!", message.threadID);
if (msg === "/stop") {
api.sendMessage("Goodbye!", message.threadID);
return stopListening();
}
if (msg.match(/\/giphy (.+)/)) {
var search = msg.replace("/giphy", "")
giphy.search(search).then(function(res) {
var gif = res.data[Math.floor(Math.random() * res.data.length)].images.downsized.url;
api.sendMessage(gif, message.threadID)
});
}
});
});
| #! /usr/bin/env node
"use strict";
const login = require("facebook-chat-api");
const giphy = require("giphy-api")();
const confg = require("./config");
login({email: confg.EMAIL, password: confg.PASS}, function callback(err, api) {
if (err) return console.error(err);
api.listen(function callback(err, message) {
var msg = message.body.toLowerCase();
if (msg.includes("/kick")) {
if (msg.includes("swar"))
api.removeUserFromGroup(confg.SWAR, message.threadID);
else if (msg.includes("kaartikey"))
api.removeUserFromGroup(confg.KAARTIKEY, message.threadID);
else if (msg.includes("anuj"))
api.removeUserFromGroup(confg.ANUJ, message.threadID);
}
if (msg === "/say hi")
api.sendMessage("Hello!", message.threadID);
if (msg === "/stop") {
api.sendMessage("Goodbye!", message.threadID);
return stopListening();
}
if (msg.match(/\/giphy (.+)/)) {
var search = msg.replace("/giphy", "")
giphy.search(search).then(function(res) {
api.sendMessage(res.data[0].embed_url, message.threadID)
});
}
});
});
|
Fix undefined variable + extra dollar sign $ variable | <?php
/**
* @title Birthday Cron Class
*
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Core / Asset / Cron / 24H
* @version 1.0
*/
namespace PH7;
defined('PH7') or exit('Restricted access');
class BirthdayCoreCron extends Cron
{
/** @var int */
private $iNum;
public function __construct()
{
parent::__construct();
$this->send();
}
protected function send()
{
$this->iNum = (new BirthdayCore)->sendMails();
if ($this->hasBirthdays()) {
echo t('No birthday today.');
} else {
echo nt('%n% email sent.', '%n% emails sent.', $this->iNum);
}
}
/**
* @return bool
*/
private function hasBirthdays()
{
return $this->iNum === 0;
}
}
// Go!
new BirthdayCoreCron;
| <?php
/**
* @title Birthday Cron Class
*
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Core / Asset / Cron / 24H
* @version 1.0
*/
namespace PH7;
defined('PH7') or exit('Restricted access');
class BirthdayCoreCron extends Cron
{
/** @var int */
private $iNum;
public function __construct()
{
parent::__construct();
$this->send();
}
protected function send()
{
$$this->iNum = (new BirthdayCore)->sendMails();
if ($this->hasBirthdays()) {
echo t('No birthday today.');
} else {
echo nt('%n% email sent.', '%n% emails sent.', $iNum);
}
}
/**
* @return bool
*/
private function hasBirthdays()
{
return $this->iNum === 0;
}
}
// Go!
new BirthdayCoreCron;
|
[leap] Add method to determine if hand is mocked | 'use strict'
const path = require('path')
const { config } = require(path.join(__dirname, '..', '..', 'main.config.js'))
module.exports = class MockHand {
constructor (normalizedPosition) {
this.normalizedPosition = [...normalizedPosition]
this.target = [...normalizedPosition]
}
update (box) {
this.normalizedPosition.forEach((_, index) => {
const d = this.target[index] - this.normalizedPosition[index]
this.normalizedPosition[index] += d * config.leap.mockHandEasing
})
return {
isMockHand: true,
x: this.normalizedPosition[0] * box[0],
y: this.normalizedPosition[2] * box[1],
z: this.normalizedPosition[1] * box[2]
}
}
}
| 'use strict'
const path = require('path')
const { config } = require(path.join(__dirname, '..', '..', 'main.config.js'))
module.exports = class MockHand {
constructor (normalizedPosition) {
this.normalizedPosition = [...normalizedPosition]
this.target = [...normalizedPosition]
}
update (box) {
this.normalizedPosition.forEach((_, index) => {
const d = this.target[index] - this.normalizedPosition[index]
this.normalizedPosition[index] += d * config.leap.mockHandEasing
})
return {
x: this.normalizedPosition[0] * box[0],
y: this.normalizedPosition[2] * box[1],
z: this.normalizedPosition[1] * box[2]
}
}
}
|
Refactor ten percent off everything strategy | package com.akikanellis.kata01;
import com.akikanellis.kata01.item.Items;
import com.akikanellis.kata01.item.QuantifiedItem;
import com.akikanellis.kata01.offer.Offer;
import com.akikanellis.kata01.offer.OfferStrategy;
import com.akikanellis.kata01.offer.Offers;
import com.akikanellis.kata01.offer.QuantifiedOffer;
import com.akikanellis.kata01.price.Price;
/**
* An example offer strategy used for testing where all of our items are discounted by 10%.
*/
public class TenPercentOffEverything extends OfferStrategy {
private static final double TEN_PERCENT = 0.10;
private TenPercentOffEverything(long id) { super(id, "10% off everything"); }
public static OfferStrategy create(int id) { return new TenPercentOffEverything(id); }
@Override public Offers calculateOffers(Items items) {
Price itemsTotalPrice = calculateItemsTotalPrice(items);
Price discount = itemsTotalPrice.multiplyBy(TEN_PERCENT).negate();
Offer offer = Offer.create(description(), discount);
QuantifiedOffer quantifiedOffer = QuantifiedOffer.create(offer, 1);
return Offers.fromSingle(quantifiedOffer);
}
private Price calculateItemsTotalPrice(Items items) {
return items.stream()
.map(QuantifiedItem::totalPrice)
.reduce(Price::add)
.orElse(Price.ZERO);
}
}
| package com.akikanellis.kata01;
import com.akikanellis.kata01.item.Items;
import com.akikanellis.kata01.item.QuantifiedItem;
import com.akikanellis.kata01.offer.Offer;
import com.akikanellis.kata01.offer.OfferStrategy;
import com.akikanellis.kata01.offer.Offers;
import com.akikanellis.kata01.offer.QuantifiedOffer;
import com.akikanellis.kata01.price.Price;
public class TenPercentOffEverything extends OfferStrategy {
private TenPercentOffEverything(long id) { super(id, "10% off everything"); }
public static OfferStrategy create(int id) { return new TenPercentOffEverything(id); }
@Override public Offers calculateOffers(Items items) {
Price itemsPrice = items.stream()
.map(QuantifiedItem::totalPrice)
.reduce(Price::add)
.orElse(Price.ZERO);
Price discount = itemsPrice.multiplyBy(0.10).negate();
Offer offer = Offer.create(description(), discount);
QuantifiedOffer quantifiedOffer = QuantifiedOffer.create(offer, 1);
return Offers.fromSingle(quantifiedOffer);
}
}
|
Check for Python 2.7 as well | #!/usr/bin/env python
import os
import warnings
warnings.filterwarnings('ignore', category=DeprecationWarning)
def test_for_version(filename):
stdin, stdout = os.popen4('%s -V' % filename, 'r')
response = stdout.read()
if response.find('command not found') > 0:
return False
return '.'.join(response.strip().split(' ')[1].split('.')[:-1])
versions = ['python', 'python2.4', 'python2.5', 'python2.6', 'python2.7']
valid = {}
for filename in versions:
version = test_for_version(filename)
if version and version not in valid:
valid[version] = filename
# Prefer 2.6 major version of python since that's my main development env
output = []
if '2.6' in valid:
output.append(valid['2.6'])
for version in valid.keys():
if valid[version] not in output:
output.append(valid[version])
print ' '.join(output)
| #!/usr/bin/env python
import os
import warnings
warnings.filterwarnings('ignore', category=DeprecationWarning)
def test_for_version(filename):
stdin, stdout = os.popen4('%s -V' % filename, 'r')
response = stdout.read()
if response.find('command not found') > 0:
return False
return '.'.join(response.strip().split(' ')[1].split('.')[:-1])
versions = ['python', 'python2.4', 'python2.5', 'python2.6']
valid = {}
for filename in versions:
version = test_for_version(filename)
if version and version not in valid:
valid[version] = filename
# Prefer the latest version of python
output = []
if '2.6' in valid:
output.append(valid['2.6'])
for version in valid.keys():
if valid[version] not in output:
output.append(valid[version])
print ' '.join(output)
|
ast: Fix syntax error in test. | package ast_test
import (
"strings"
"testing"
"github.com/DeedleFake/wdte/ast"
)
func printTree(t *testing.T, cur ast.Node, depth int) {
indent := strings.Repeat(" ", depth)
switch cur := cur.(type) {
case *ast.Term:
t.Logf("%v%v", indent, cur)
case *ast.NTerm:
t.Logf("%v(%v", indent, cur)
for _, c := range cur.Children() {
printTree(t, c, depth+1)
}
t.Logf("%v)", indent)
case *ast.Epsilon:
t.Logf("%vε", indent)
default:
t.Fatalf("Unexpected node: %#v", cur)
}
}
func TestParse(t *testing.T) {
//const test = `"test" => t; + x y => nil;`
const test = `
'test' => test;
fib n => switch n {
0 => 0;
default => + (fib (- n 1;);) (fib (- n 2;););
};
main => print (fib 5;);
`
root, err := ast.Parse(strings.NewReader(test))
if err != nil {
t.Fatal(err)
}
printTree(t, root, 0)
}
| package ast_test
import (
"strings"
"testing"
"github.com/DeedleFake/wdte/ast"
)
func printTree(t *testing.T, cur ast.Node, depth int) {
indent := strings.Repeat(" ", depth)
switch cur := cur.(type) {
case *ast.Term:
t.Logf("%v%v", indent, cur)
case *ast.NTerm:
t.Logf("%v(%v", indent, cur)
for _, c := range cur.Children() {
printTree(t, c, depth+1)
}
t.Logf("%v)", indent)
case *ast.Epsilon:
t.Logf("%vε", indent)
default:
t.Fatalf("Unexpected node: %#v", cur)
}
}
func TestParse(t *testing.T) {
//const test = `"test" => t; + x y => nil;`
const test = `
'test' => test;
fib n => switch n {
0 => 0;
default => + (fib (- n 1)) (fib (- n 2));
};
main => print (fib 5);
`
root, err := ast.Parse(strings.NewReader(test))
if err != nil {
t.Fatal(err)
}
printTree(t, root, 0)
}
|
Add note in credits about Javascript/HTML5 | CubeGame.Credits = function() {};
CubeGame.Credits.prototype = {
create: function() {
this.credits = "Avoid the obstacles with the Cube!\nA Javascript/HTML5 Game\nCreated with the Phaser Game Engine\n\nImages created in Inkscape\nSounds created in Audacity";
this.creditsText = CubeGame.factory.addText(100, 50, this.credits, 30, "#5f5f5f");
this.menuButton = this.game.add.button(100, 400, "Textures", this.menuState, this);
this.menuButton.frameName = "MenuButton";
this.creditsThingsGroup = this.game.add.group();
this.creditsThingsGroup.add(this.menuButton);
this.creditsThingsGroup.add(this.creditsText);
this.creditsThingsSlideIn = this.game.add.tween(this.creditsThingsGroup)
.from({x:1500}, 500, Phaser.Easing.Sinusoidal.Out).start();
},
menuState: function() {
this.game.state.start("Menu");
}
}; | CubeGame.Credits = function() {};
CubeGame.Credits.prototype = {
create: function() {
this.credits = "Avoid the obstacles with the Cube!\nCreated with the Phaser Game Engine\n\nImages created in Inkscape\nSounds created in Audacity";
this.creditsText = CubeGame.factory.addText(100, 50, this.credits, 30, "#5f5f5f");
this.menuButton = this.game.add.button(100, 400, "Textures", this.menuState, this);
this.menuButton.frameName = "MenuButton";
this.creditsThingsGroup = this.game.add.group();
this.creditsThingsGroup.add(this.menuButton);
this.creditsThingsGroup.add(this.creditsText);
this.creditsThingsSlideIn = this.game.add.tween(this.creditsThingsGroup)
.from({x:1500}, 500, Phaser.Easing.Sinusoidal.Out).start();
},
menuState: function() {
this.game.state.start("Menu");
}
}; |
Move parser construction outside parse function to fix performance hit | 'use strict';
var DefaultStack = require('./stacks/default');
var entityMap = require('html-tokenizer/entity-map');
// @TODO examine other tokenizers or parsers
var Parser = require('html-tokenizer/parser');
var defaultStack = new DefaultStack(true);
var _stack;
var parser = new Parser({
entities: entityMap
});
parser.on('open', function(name, attributes) {
_stack.openElement(name, attributes);
});
parser.on('comment', function(text) {
_stack.createComment(text);
});
parser.on('text', function(text) {
_stack.createObject(text);
});
parser.on('close', function() {
var el = _stack.peek();
_stack.closeElement(el);
});
module.exports = function(html, stack) {
if (stack) {
_stack = stack;
} else {
defaultStack.clear();
_stack = defaultStack;
}
parser.parse(html);
if (!stack) {
return _stack.getOutput();
}
};
| 'use strict';
var DefaultStack = require('./stacks/default');
var entityMap = require('html-tokenizer/entity-map');
// @TODO examine other tokenizers or parsers
var Parser = require('html-tokenizer/parser');
module.exports = function(html, stack) {
var _stack = stack || new DefaultStack(true);
var parser = new Parser({
entities: entityMap
});
parser.on('open', function(name, attributes) {
_stack.openElement(name, attributes);
});
parser.on('comment', function(text) {
_stack.createComment(text);
});
parser.on('text', function(text) {
_stack.createObject(text);
});
parser.on('close', function() {
var el = _stack.peek();
_stack.closeElement(el);
});
parser.parse(html);
if (!stack) {
return _stack.getOutput();
}
};
|
Check for job in main loop | #!/usr/bin/env python
import time
import picamera
from settings import Job, IMAGES_DIRECTORY
def main():
job = Job()
if job.exists():
resolution_x = job.image_settings.resolution_x
resolution_y = job.image_settings.resolution_y
image_quality = job.image_settings.quality
snap_interval = job.snap_settings.interval
snap_total = job.snap_settings.total
with picamera.PiCamera() as camera:
camera.resolution = (resolution_x, resolution_y)
time.sleep(2)
output_file = IMAGES_DIRECTORY + '/img{counter:03d}.jpg'
capture = camera.capture_continuous(output_file, quality=image_quality)
for i, _ in enumerate(capture):
if i == snap_total - 1:
job.archive()
break
time.sleep(snap_interval)
if __name__ == '__main__':
while True:
main()
| #!/usr/bin/env python
import sys
import time
import picamera
import settings
from settings import IMAGE, SNAP
import uploader
def main():
with picamera.PiCamera() as camera:
camera.resolution = (IMAGE.resolution_x, IMAGE.resolution_y)
time.sleep(2)
output_file = settings.IMAGES_DIRECTORY + '/img{counter:03d}.jpg'
capture = camera.capture_continuous(output_file, quality=IMAGE.quality)
for i, _ in enumerate(capture):
if i == SNAP.total - 1:
break
time.sleep(SNAP.interval)
if __name__ == '__main__':
while True:
main()
|
Add targetExtension class property for chaining | 'use strict';
var peg = require('pegjs');
class PegJsPlugin {
constructor(config) {
this.config = config.plugins.pegjs;
// The output of the below peg.generate() function must be a string, not an
// object
this.config.output = 'source';
}
compile(file) {
var parser;
try {
parser = peg.generate(file.data, this.config);
} catch(error) {
if (error instanceof peg.parser.SyntaxError) {
error.message = `${error.message} at ${error.location.start.line}:${error.location.start.column}`;
}
return Promise.reject(error);
}
return Promise.resolve({data: parser});
}
}
// brunchPlugin must be set to true for all Brunch plugins
PegJsPlugin.prototype.brunchPlugin = true;
// The type of file to generate
PegJsPlugin.prototype.type = 'javascript';
// The extension for files to process
PegJsPlugin.prototype.extension = 'pegjs';
// The extension for processed files (this allows for compiler chaining)
PegJsPlugin.prototype.targetExtension = 'js';
module.exports = PegJsPlugin;
| 'use strict';
var peg = require('pegjs');
class PegJsPlugin {
constructor(config) {
this.config = config.plugins.pegjs;
// The output of the below peg.generate() function must be a string, not an
// object
this.config.output = 'source';
}
compile(file) {
var parser;
try {
parser = peg.generate(file.data, this.config);
} catch(error) {
if (error instanceof peg.parser.SyntaxError) {
error.message = `${error.message} at ${error.location.start.line}:${error.location.start.column}`;
}
return Promise.reject(error);
}
return Promise.resolve({data: parser});
}
}
// brunchPlugin must be set to true for all Brunch plugins
PegJsPlugin.prototype.brunchPlugin = true;
// The type of file to generate
PegJsPlugin.prototype.type = 'javascript';
// The extension for files to process
PegJsPlugin.prototype.extension = 'pegjs';
module.exports = PegJsPlugin;
|
Add output with the number of CPU that will be used. | package main
import (
"flag"
"fmt"
"log"
"net/url"
"os"
"runtime"
"runtime/pprof"
"wapbot.co.uk/crawler"
)
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
func main() {
flag.Parse()
fmt.Printf("GOMAXPROCS is set to: %d\n", runtime.GOMAXPROCS(-1))
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
uri, err := url.Parse("http://tomblomfield.com")
if err != nil {
fmt.Printf("Invalid url: %s\n", err.Error())
return
}
page, err := crawler.ProcessPage(uri)
if err != nil {
fmt.Printf("Unable to crawl page: %s\n", err.Error())
return
}
page.Dump()
}
| package main
import (
"flag"
"fmt"
"log"
"net/url"
"os"
"runtime/pprof"
"wapbot.co.uk/crawler"
)
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
func main() {
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
uri, err := url.Parse("http://tomblomfield.com")
if err != nil {
fmt.Printf("Invalid url: %s\n", err.Error())
return
}
page, err := crawler.ProcessPage(uri)
if err != nil {
fmt.Printf("Unable to crawl page: %s\n", err.Error())
return
}
page.Dump()
}
|
Fix include for group inbox class | <?php
/**
* Table Definition for group_inbox
*/
require_once 'classes/Memcached_DataObject.php';
class Group_inbox extends Memcached_DataObject
{
###START_AUTOCODE
/* the code below is auto generated do not remove the above tag */
public $__table = 'group_inbox'; // table name
public $group_id; // int(4) primary_key not_null
public $notice_id; // int(4) primary_key not_null
public $created; // datetime() not_null
/* Static get */
function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Group_inbox',$k,$v); }
/* the code above is auto generated do not remove the tag below */
###END_AUTOCODE
}
| <?php
/**
* Table Definition for group_inbox
*/
require_once 'classes/Memcached_DataObject';
class Group_inbox extends Memcached_DataObject
{
###START_AUTOCODE
/* the code below is auto generated do not remove the above tag */
public $__table = 'group_inbox'; // table name
public $group_id; // int(4) primary_key not_null
public $notice_id; // int(4) primary_key not_null
public $created; // datetime() not_null
/* Static get */
function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Group_inbox',$k,$v); }
/* the code above is auto generated do not remove the tag below */
###END_AUTOCODE
}
|
Add extra_require for development deps | import sys
from setuptools import setup, find_packages
from django_summernote import version, PROJECT
MODULE_NAME = 'django_summernote'
PACKAGE_DATA = list()
CLASSIFIERS = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities',
]
setup(
name=PROJECT,
version=version,
packages=find_packages(),
include_package_data=True,
zip_safe=False,
author='django-summernote contributors',
maintainer='django-summernote maintainers',
url='http://github.com/summernote/django-summernote',
description='Summernote plugin for Django',
classifiers=CLASSIFIERS,
install_requires=['django', 'bleach'],
extras_require={
'dev': [
'django-dummy-plug',
'pytest',
'pytest-django',
]
},
)
| import sys
from setuptools import setup, find_packages
from django_summernote import version, PROJECT
MODULE_NAME = 'django_summernote'
PACKAGE_DATA = list()
CLASSIFIERS = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities',
]
setup(
name=PROJECT,
version=version,
packages=find_packages(),
include_package_data=True,
zip_safe=False,
author='django-summernote contributors',
maintainer='django-summernote maintainers',
url='http://github.com/summernote/django-summernote',
description='Summernote plugin for Django',
classifiers=CLASSIFIERS,
install_requires=['django', 'bleach'],
)
|
Revert D7319513: Depend on local version of babel-plugin-react-transform
Differential Revision:
D7319513
Original commit changeset: 4945ec753087
fbshipit-source-id: 98de6a0fda19732c02ad780953497f9d9b451dea | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var path = require('path');
var resolvePlugins = require('../lib/resolvePlugins');
var hmrTransform = 'react-transform-hmr/lib/index.js';
var transformPath = require.resolve(hmrTransform);
module.exports = function(options, filename) {
var transform = filename
? './' + path.relative(path.dirname(filename), transformPath) // packager can't handle absolute paths
: hmrTransform;
// Fix the module path to use '/' on Windows.
if (path.sep === '\\') {
transform = transform.replace(/\\/g, '/');
}
return {
plugins: resolvePlugins([
[
'react-transform',
{
transforms: [{
transform: transform,
imports: ['react'],
locals: ['module'],
}]
},
]
])
};
};
| /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var path = require('path');
var hmrTransform = 'react-transform-hmr/lib/index.js';
var transformPath = require.resolve(hmrTransform);
module.exports = function(options, filename) {
var transform = filename
? './' + path.relative(path.dirname(filename), transformPath) // packager can't handle absolute paths
: hmrTransform;
// Fix the module path to use '/' on Windows.
if (path.sep === '\\') {
transform = transform.replace(/\\/g, '/');
}
return {
plugins: [
[
require('metro-babel7-plugin-react-transform').default,
{
transforms: [{
transform: transform,
imports: ['react'],
locals: ['module'],
}]
},
]
]
};
};
|
Fix error: __str__ returned non-string (type NoneType) | from django.db import models
class Position(models.Model):
class Meta:
verbose_name = "Position"
verbose_name_plural = "Positions"
title = models.CharField(u'title',
blank=False,
default='',
help_text=u'Please enter a title for this position',
max_length=64,
unique=True,
)
def __str__(self):
return self.title
class Scientist(models.Model):
class Meta:
verbose_name = "Scientist"
verbose_name_plural = "Scientists"
full_name = models.CharField(u'full name',
blank=False,
default='',
help_text=u'Please enter a full name for this scientist',
max_length=64,
unique=True,
)
slug = models.SlugField(u'slug',
blank=False,
default='',
help_text=u'Please enter a unique slug for this scientist',
max_length=64,
)
title = models.ForeignKey('lab_members.Position',
blank=True,
default=None,
help_text=u'Please specify a title for this scientist',
null=True,
)
def __str__(self):
return self.full_name
| from django.db import models
class Position(models.Model):
class Meta:
verbose_name = "Position"
verbose_name_plural = "Positions"
title = models.CharField(u'title',
blank=False,
default='',
help_text=u'Please enter a title for this position',
max_length=64,
unique=True,
)
def __str__(self):
pass
class Scientist(models.Model):
class Meta:
verbose_name = "Scientist"
verbose_name_plural = "Scientists"
full_name = models.CharField(u'full name',
blank=False,
default='',
help_text=u'Please enter a full name for this scientist',
max_length=64,
unique=True,
)
slug = models.SlugField(u'slug',
blank=False,
default='',
help_text=u'Please enter a unique slug for this scientist',
max_length=64,
)
title = models.ForeignKey('lab_members.Position',
blank=True,
default=None,
help_text=u'Please specify a title for this scientist',
null=True,
)
def __str__(self):
pass
|
Switch URL to Crate page | #!/usr/bin/env python
import twelve
import twelve.adapters
import twelve.services
try:
from setuptools import setup
# hush pyflakes
setup
except ImportError:
from distutils.core import setup
requires = []
setup(
name="twelve",
version=twelve.__version__,
description="12factor inspired settings for a variety of backing services archetypes.",
long_description=open("README.rst").read() + '\n\n' +
open("CHANGELOG.rst").read(),
author="Donald Stufft",
author_email="donald.stufft@gmail.com",
url="https://crate.io/packages/twelve/",
packages=[
"twelve",
],
package_data={"": ["LICENSE"]},
include_package_data=True,
install_requires=[],
license=open("LICENSE").read(),
classifiers=(
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.1",
),
)
| #!/usr/bin/env python
import twelve
import twelve.adapters
import twelve.services
try:
from setuptools import setup
# hush pyflakes
setup
except ImportError:
from distutils.core import setup
requires = []
setup(
name="twelve",
version=twelve.__version__,
description="12factor inspired settings for a variety of backing services archetypes.",
long_description=open("README.rst").read() + '\n\n' +
open("CHANGELOG.rst").read(),
author="Donald Stufft",
author_email="donald.stufft@gmail.com",
url="https://github.com/dstufft/twelve/",
packages=[
"twelve",
],
package_data={"": ["LICENSE"]},
include_package_data=True,
install_requires=[],
license=open("LICENSE").read(),
classifiers=(
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.1",
),
)
|
Update the PyPI version to 8.0.2. | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='8.0.2',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
| # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='8.0.1',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Test for bitter font in styles | /*global $:true, casper:true, document:true */
'use strict';
casper.test.comment('Face Value - Fonts')
casper.start('http://localhost:3001/', function () {
casper.test.info('Testing for Bitter fonts')
this.test.assertEval(function() {
return $('body').css('font-family').match(/^Bitter/g) !== null
}, '<body> font should be Bitter')
})
casper.waitForResource('Bitter-Regular-webfont.ttf', function() {
this.test.assertResourceExists('Bitter-Regular-webfont.ttf',
'Bitter font loaded properly')
})
casper.waitForResource('Bitter-Bold-webfont.ttf', function() {
this.test.assertResourceExists('Bitter-Bold-webfont.ttf',
'Bitter Bold font loaded properly')
})
casper.run(function () {
this.test.done()
})
| /*global $:true, casper:true, document:true */
'use strict';
casper.test.comment('Face Value - Fonts')
casper.start('http://localhost:3001/', function () {
casper.test.info('Testing for Bitter fonts')
})
casper.waitForResource('Bitter-Regular-webfont.ttf', function() {
this.test.assertResourceExists('Bitter-Regular-webfont.ttf',
'Bitter font loaded properly')
})
casper.waitForResource('Bitter-Bold-webfont.ttf', function() {
this.test.assertResourceExists('Bitter-Bold-webfont.ttf',
'Bitter Bold font loaded properly')
})
casper.run(function () {
this.test.done()
})
|
Split the removal of pro from session and db into separate functions
Both now use promises keeping flow control simple and less buggy | 'use strict';
var models = require('../../models');
var sessionStore = require('../../app').sessionStore;
var Promise = require('rsvp').Promise;
module.exports = function (data, callbackToStripe) {
if (isCanceled(data)) {
var removeProStatus = function(customer){
sessionStore.destroyByName(customer.user);
return models.user.setProAccount(customer.user, false);
};
var sendStripe200 = callbackToStripe.bind(null, null);
models.customer.setActive(data.customer, false)
.then(removeProStatus)
//.then(removeTeamStatus)
.then(sendStripe200)
.catch(callbackToStripe);
} else {
callbackToStripe(null);
}
};
function isCanceled(obj) {
return obj.status ? obj.status === 'canceled' : isCanceled(obj.data || obj.object);
}
function removeProStatusFromDB (customer) {
return new Promise(function(reject, resolve) {
models.user.setProAccount(customer.user, false, function(err) {
if (err) {
return reject(err);
}
resolve(customer);
});
});
}
function removeProStatusFromSession (customer) {
return sessionStore.set(customer.name, false);
}
| 'use strict';
var models = require('../../models');
var sessionStore = require('../../app').sessionStore;
module.exports = function (data, callbackToStripe) {
if (isCanceled(data)) {
var removeProStatus = function(customer){
sessionStore.destroyByName(customer.user);
return models.user.setProAccount(customer.user, false);
};
var sendStripe200 = callbackToStripe.bind(null, null);
models.customer.setActive(data.customer, false)
.then(removeProStatus)
//.then(removeTeamStatus)
.then(sendStripe200)
.catch(callbackToStripe);
} else {
callbackToStripe(null);
}
};
function isCanceled(obj) {
return obj.status ? obj.status === 'canceled' : isCanceled(obj.data || obj.object);
}
|
Switch to new version scheme, alpha timestamped today. | # -*- coding: utf-8 -*-
# Copyright (c) 2010-2014, MIT Probabilistic Computing Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='bdbcontrib',
version='0.1a20150917',
description='Hodgepodge library of extras for bayeslite',
url='http://probcomp.csail.mit.edu/bayesdb',
author='MIT Probabilistic Computing Project',
author_email='bayesdb@mit.edu',
license='Apache License, Version 2.0',
install_requires=[
'markdown2',
'matplotlib',
'numpy',
'numpydoc',
'pandas',
'seaborn==0.5.1',
'sphinx',
],
packages=[
'bdbcontrib',
],
package_dir={
'bdbcontrib': 'src',
},
)
| # -*- coding: utf-8 -*-
# Copyright (c) 2010-2014, MIT Probabilistic Computing Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='bdbcontrib',
version='0.1.dev',
description='Hodgepodge library of extras for bayeslite',
url='http://probcomp.csail.mit.edu/bayesdb',
author='MIT Probabilistic Computing Project',
author_email='bayesdb@mit.edu',
license='Apache License, Version 2.0',
install_requires=[
'markdown2',
'matplotlib',
'numpy',
'numpydoc',
'pandas',
'seaborn==0.5.1',
'sphinx',
],
packages=[
'bdbcontrib',
],
package_dir={
'bdbcontrib': 'src',
},
)
|
Add support for QTest with PySide | # -*- coding: utf-8 -*-
#
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder Developmet Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
"""
Provides QtTest and functions
"""
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError
if PYQT5:
from PyQt5.QtTest import QTest
elif PYQT4:
from PyQt4.QtTest import QTest as OldQTest
class QTest(OldQTest):
@staticmethod
def qWaitForWindowActive(QWidget):
OldQTest.qWaitForWindowShown(QWidget)
elif PYSIDE:
from PySide.QtTest import QTest
else:
raise PythonQtError('No Qt bindings could be found')
| # -*- coding: utf-8 -*-
#
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder Developmet Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
"""
Provides QtTest and functions
.. warning:: PySide is not supported here, that's why there is not unit tests
running with PySide.
"""
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError
if PYQT5:
from PyQt5.QtTest import QTest
elif PYQT4:
from PyQt4.QtTest import QTest as OldQTest
class QTest(OldQTest):
@staticmethod
def qWaitForWindowActive(QWidget):
OldQTest.qWaitForWindowShown(QWidget)
elif PYSIDE:
raise ImportError('QtTest support is incomplete for PySide')
else:
raise PythonQtError('No Qt bindings could be found')
|
Add system properties to allow override of SDK User Agent | package com.alienvault.otx.connect.internal;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import java.io.IOException;
import java.net.URI;
/**
* Internal utility class to set the authorization header used for the OTX API
* authentication.
*/
public class HeaderSettingRequestFactory extends SimpleClientHttpRequestFactory {
private static final String SDK_USER_AGENT = String.format("%s/%s/%s",
System.getProperty("otx.sdk.project", "OTX Java SDK"),
System.getProperty("otx.sdk.version", "1.0"),
System.getProperty("java.version"));
private String apiKey;
public HeaderSettingRequestFactory(String apiKey) {
this.apiKey = apiKey;
}
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
ClientHttpRequest request = super.createRequest(uri, httpMethod);
request.getHeaders().add("X-OTX-API-KEY",apiKey);
request.getHeaders().add(HttpHeaders.USER_AGENT,SDK_USER_AGENT);
return request;
}
}
| package com.alienvault.otx.connect.internal;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import java.io.IOException;
import java.net.URI;
/**
* Internal utility class to set the authorization header used for the OTX API
* authentication.
*/
public class HeaderSettingRequestFactory extends SimpleClientHttpRequestFactory {
private static final String SDK_USER_AGENT = "OTX Java SDK/1.0/"+System.getProperty("java.version");
private String apiKey;
public HeaderSettingRequestFactory(String apiKey) {
this.apiKey = apiKey;
}
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
ClientHttpRequest request = super.createRequest(uri, httpMethod);
request.getHeaders().add("X-OTX-API-KEY",apiKey);
request.getHeaders().add(HttpHeaders.USER_AGENT,SDK_USER_AGENT);
return request;
}
}
|
Add line break when printing to fmt | package main
import (
"fmt"
"os"
"github.com/jvikstedt/alarm-bot/configuration"
"github.com/jvikstedt/alarm-bot/mailer"
"github.com/jvikstedt/alarm-bot/tracker"
)
var mail *mailer.Mailer
var conf *configuration.Configuration
func init() {
setupConf()
setupMailer()
}
func main() {
for _, c := range conf.TestObjects {
trackResult, err := tracker.Perform(c.URL, c.MatchString, c.Status)
if err != nil {
fmt.Println(err)
mail.Send("AlarmBot Error @ "+trackResult.TargetURL, err.Error(), c.MailTo)
} else {
fmt.Println(trackResult)
}
}
}
func setupConf() {
confName := os.Getenv("ALARM_BOT_CONFIG")
if confName == "" {
confName = "./config.json"
}
conf = configuration.NewConfiguration(confName)
}
func setupMailer() {
mail = mailer.NewMailer(conf.MailSetting.Host, conf.MailSetting.From, conf.MailSetting.Password, conf.MailSetting.Port)
}
| package main
import (
"fmt"
"os"
"github.com/jvikstedt/alarm-bot/configuration"
"github.com/jvikstedt/alarm-bot/mailer"
"github.com/jvikstedt/alarm-bot/tracker"
)
var mail *mailer.Mailer
var conf *configuration.Configuration
func init() {
setupConf()
setupMailer()
}
func main() {
for _, c := range conf.TestObjects {
trackResult, err := tracker.Perform(c.URL, c.MatchString, c.Status)
if err != nil {
fmt.Print(err)
mail.Send("AlarmBot Error @ "+trackResult.TargetURL, err.Error(), c.MailTo)
} else {
fmt.Print(trackResult)
}
}
}
func setupConf() {
confName := os.Getenv("ALARM_BOT_CONFIG")
if confName == "" {
confName = "./config.json"
}
conf = configuration.NewConfiguration(confName)
}
func setupMailer() {
mail = mailer.NewMailer(conf.MailSetting.Host, conf.MailSetting.From, conf.MailSetting.Password, conf.MailSetting.Port)
}
|
Add complete attribute to todo | // Placehold showing handler structure
// Stupid example using in memory array as data store
var todos = [
{ id: 1, title: "Learn Hapi", complete: false },
{ id: 2, title: "Learn Ember", complete: false }
];
exports.IndexHandler = function(request, reply) {
reply({todos: todos});
};
exports.CreateHandler = function(request, reply) {
var newTodo = JSON.parse(request.payload);
if (typeof newTodo.title !== undefined) {
newTodo.id = todos.length + 1;
todos.push(newTodo);
}
console.log(newTodo);
reply({success: true});
};
exports.ShowHandler = function(request, reply) {
var index = parseInt(request.params.todo_id) - 1;
reply({todos: [todos[index]]});
};
exports.UpdateHandler = function(request, reply) {
var index = parseInt(request.params.todo_id) - 1;
var updatedTodo = JSON.parse(request.payload);
var title = updatedTodo.title;
var complete = updatedTodo.complete;
if(typeof updatedTodo.title !== undefined) {
todos[index].title = updatedTodo.title;
}
if(typeof updatedTodo.complete !== undefined) {
todos[index].complete = updatedTodo.complete;
}
console.log(request.payload);
reply({success: true});
};
exports.DeleteHandler = function(request, reply) {
var index = parseInt(request.params.todo_id) - 1;
todos.splice(index, 1);
console.log(todos[index]);
reply({success: true});
};
| // Placehold showing handler structure
// Stupid example using in memory array as data store
var todos = [
{ id: 1, title: "Learn Hapi" },
{ id: 2, title: "Learn Ember" }
];
exports.IndexHandler = function(request, reply) {
reply({todos: todos});
};
exports.CreateHandler = function(request, reply) {
var newTodo = JSON.parse(request.payload);
if (newTodo.title) {
newTodo.id = todos.length + 1;
todos.push(newTodo);
}
console.log(newTodo);
reply({success: true});
};
exports.ShowHandler = function(request, reply) {
var index = parseInt(request.params.todo_id) - 1;
reply({todos: [todos[index]]});
};
exports.UpdateHandler = function(request, reply) {
var index = parseInt(request.params.todo_id) - 1;
var updatedTodo = JSON.parse(request.payload);
if(updatedTodo.title) {
todos[index].title = updatedTodo.title;
}
console.log(request.payload);
reply({success: true});
};
exports.DeleteHandler = function(request, reply) {
var index = parseInt(request.params.todo_id) - 1;
todos.splice(index, 1);
console.log(todos[index]);
reply({success: true});
};
|
Add ls as an alias to the list command. | var abbrev = require('abbrev');
var mout = require('mout');
var commands = require('./commands');
var PackageRepository = require('./core/PackageRepository');
var abbreviations = abbrev(expandNames(commands));
abbreviations.i = 'install';
abbreviations.rm = 'uninstall';
abbreviations.ls = 'list';
function expandNames(obj, prefix, stack) {
prefix = prefix || '';
stack = stack || [];
mout.object.forOwn(obj, function (value, name) {
name = prefix + name;
stack.push(name);
if (typeof value === 'object' && !value.line) {
expandNames(value, name + ' ', stack);
}
});
return stack;
}
function clearRuntimeCache() {
// Note that in edge cases, some architecture components instance's
// in-memory cache might be skipped.
// If that's a problem, you should create and fresh instances instead.
PackageRepository.clearRuntimeCache();
}
module.exports = {
commands: commands,
config: require('./config'),
abbreviations: abbreviations,
reset: clearRuntimeCache
};
| var abbrev = require('abbrev');
var mout = require('mout');
var commands = require('./commands');
var PackageRepository = require('./core/PackageRepository');
var abbreviations = abbrev(expandNames(commands));
abbreviations.i = 'install';
abbreviations.rm = 'uninstall';
function expandNames(obj, prefix, stack) {
prefix = prefix || '';
stack = stack || [];
mout.object.forOwn(obj, function (value, name) {
name = prefix + name;
stack.push(name);
if (typeof value === 'object' && !value.line) {
expandNames(value, name + ' ', stack);
}
});
return stack;
}
function clearRuntimeCache() {
// Note that in edge cases, some architecture components instance's
// in-memory cache might be skipped.
// If that's a problem, you should create and fresh instances instead.
PackageRepository.clearRuntimeCache();
}
module.exports = {
commands: commands,
config: require('./config'),
abbreviations: abbreviations,
reset: clearRuntimeCache
};
|
Use sys.executable when executing nbgrader | import os
import sys
from .. import run_nbgrader, run_command
from .base import BaseTestApp
class TestNbGrader(BaseTestApp):
def test_help(self):
"""Does the help display without error?"""
run_nbgrader(["--help-all"])
def test_no_subapp(self):
"""Is the help displayed when no subapp is given?"""
run_nbgrader([], retcode=1)
def test_generate_config(self):
"""Is the config file properly generated?"""
# it already exists, because we create it in conftest.py
os.remove("nbgrader_config.py")
# try recreating it
run_nbgrader(["--generate-config"])
assert os.path.isfile("nbgrader_config.py")
# does it fail if it already exists?
run_nbgrader(["--generate-config"], retcode=1)
def test_check_version(self, capfd):
"""Is the version the same regardless of how we run nbgrader?"""
out1 = '\n'.join(
run_command([sys.executable, "-m", "nbgrader", "--version"]).splitlines()[-3:]
).strip()
out2 = '\n'.join(
run_nbgrader(["--version"], stdout=True).splitlines()[-3:]
).strip()
assert out1 == out2
| import os
import sys
from .. import run_nbgrader, run_command
from .base import BaseTestApp
class TestNbGrader(BaseTestApp):
def test_help(self):
"""Does the help display without error?"""
run_nbgrader(["--help-all"])
def test_no_subapp(self):
"""Is the help displayed when no subapp is given?"""
run_nbgrader([], retcode=1)
def test_generate_config(self):
"""Is the config file properly generated?"""
# it already exists, because we create it in conftest.py
os.remove("nbgrader_config.py")
# try recreating it
run_nbgrader(["--generate-config"])
assert os.path.isfile("nbgrader_config.py")
# does it fail if it already exists?
run_nbgrader(["--generate-config"], retcode=1)
def test_check_version(self, capfd):
"""Is the version the same regardless of how we run nbgrader?"""
out1 = '\n'.join(
run_command(["nbgrader", "--version"]).splitlines()[-3:]
).strip()
out2 = '\n'.join(
run_nbgrader(["--version"], stdout=True).splitlines()[-3:]
).strip()
assert out1 == out2
|
Add min version of ldap3 | import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='consultants@pdx.edu',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'stashward'
],
extras_require={
'ldap': [
'ldap3>=0.9.9.1',
],
'dev': [
'django>=1.7',
'flake8',
'ldap3',
'mock',
'model_mommy',
],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='consultants@pdx.edu',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'stashward'
],
extras_require={
'ldap': [
'ldap3',
],
'dev': [
'django>=1.7',
'flake8',
'ldap3',
'mock',
'model_mommy',
],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Revert log level setup to WARN | # -*- coding: utf-8 -*-
import logging
import praw
from settings import Config
from .database import create_db_session
logging.basicConfig(level="WARNING")
logger = logging.getLogger(__name__)
# Project configuration settings
cfg = Config()
if not cfg.USERNAME:
logger.error("Username in settings must be set. Exiting...")
sys.exit()
# setup DB session
session = create_db_session(cfg.SQLALCHEMY_DATABASE_URI)
# setup PRAW handler
handler = None
if cfg.MULTIPROCESS:
handler = praw.handlers.MultiprocessHandler()
# setup and open connection to Reddit
user_agent = "Reddit analytics scraper by /u/{}".format(cfg.USERNAME)
reddit = praw.Reddit(user_agent=user_agent, handler=handler)
reddit.config.decode_html_entities = True
# Attributes of interest for comment objects
# note: including `author` slows comment requests considerably
COMMENT_ATTRS = [
'id',
'created_utc',
# 'author',
'body',
'score',
'ups',
'downs',
'subreddit',
'subreddit_id',
'controversiality',
'is_root',
'parent_id',
'gilded',
'permalink',
]
| # -*- coding: utf-8 -*-
import logging
import praw
from settings import Config
from .database import create_db_session
logging.basicConfig(level="INFO")
logger = logging.getLogger(__name__)
# Project configuration settings
cfg = Config()
if not cfg.USERNAME:
logger.error("Username in settings must be set. Exiting...")
sys.exit()
# setup DB session
session = create_db_session(cfg.SQLALCHEMY_DATABASE_URI)
# setup PRAW handler
handler = None
if cfg.MULTIPROCESS:
handler = praw.handlers.MultiprocessHandler()
# setup and open connection to Reddit
user_agent = "Reddit analytics scraper by /u/{}".format(cfg.USERNAME)
reddit = praw.Reddit(user_agent=user_agent, handler=handler)
reddit.config.decode_html_entities = True
# Attributes of interest for comment objects
# note: including `author` slows comment requests considerably
COMMENT_ATTRS = [
'id',
'created_utc',
# 'author',
'body',
'score',
'ups',
'downs',
'subreddit',
'subreddit_id',
'controversiality',
'is_root',
'parent_id',
'gilded',
'permalink',
]
|
Print progress of data migration | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-06 17:33
from __future__ import unicode_literals
from django.db import migrations
from temba.utils import chunk_list
def do_populate_send_all(Broadcast):
broadcast_ids = Broadcast.objects.all().values_list('id', flat=True)
broadcast_count = len(broadcast_ids)
print('Starting to update %d broadcasts send all field...' % broadcast_count)
updated = 0
for chunk in chunk_list(broadcast_ids, 1000):
Broadcast.objects.filter(pk__in=chunk).update(send_all=False)
print("Updated %d of %d broadcasts" % (updated + len(chunk), broadcast_count))
def apply_as_migration(apps, schema_editor):
Broadcast = apps.get_model('msgs', 'Broadcast')
do_populate_send_all(Broadcast)
def apply_manual():
from temba.msgs.models import Broadcast
do_populate_send_all(Broadcast)
class Migration(migrations.Migration):
dependencies = [
('msgs', '0086_broadcast_send_all'),
]
operations = [
migrations.RunPython(apply_as_migration)
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-06 17:33
from __future__ import unicode_literals
from django.db import migrations
from temba.utils import chunk_list
def do_populate_send_all(Broadcast):
broadcast_ids = Broadcast.objects.all().values_list('id', flat=True)
for chunk in chunk_list(broadcast_ids, 1000):
Broadcast.objects.filter(pk__in=chunk).update(send_all=False)
def apply_as_migration(apps, schema_editor):
Broadcast = apps.get_model('msgs', 'Broadcast')
do_populate_send_all(Broadcast)
def apply_manual():
from temba.msgs.models import Broadcast
do_populate_send_all(Broadcast)
class Migration(migrations.Migration):
dependencies = [
('msgs', '0086_broadcast_send_all'),
]
operations = [
migrations.RunPython(apply_as_migration)
]
|
Remove old roles relationship function | <?php
namespace App\Models;
use App\Models\Traits\HasRole;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword, HasRole;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
protected $primaryKey = 'user_id';
public $incrementing = false;
}
| <?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
protected $primaryKey = 'user_id';
public $incrementing = false;
public function roles()
{
return $this->belongsToMany(Role::class, 'user_role');
}
}
|
Change behavior of removing an external account to persist the object | import httplib as http
from flask import redirect
from framework.auth.decorators import must_be_logged_in
from framework.exceptions import HTTPError
from website.oauth.models import ExternalAccount
from website.oauth.utils import get_service
@must_be_logged_in
def oauth_disconnect(external_account_id, auth):
account = ExternalAccount.load(external_account_id)
user = auth.user
if account is None:
HTTPError(http.NOT_FOUND)
if account not in user.external_accounts:
HTTPError(http.FORBIDDEN)
# iterate AddonUserSettings for addons
for user_settings in user.get_addons():
user_settings.revoke_oauth_access(account)
user_settings.save()
# ExternalAccount.remove_one(account)
# # only after all addons have been dealt with can we remove it from the user
user.external_accounts.remove(account)
user.save()
@must_be_logged_in
def oauth_connect(service_name, auth):
service = get_service(service_name)
return redirect(service.auth_url)
@must_be_logged_in
def oauth_callback(service_name, auth):
user = auth.user
provider = get_service(service_name)
# Retrieve permanent credentials from provider
provider.auth_callback(user=user)
if provider.account not in user.external_accounts:
user.external_accounts.append(provider.account)
user.save()
return {}
| import httplib as http
from flask import redirect
from framework.auth.decorators import must_be_logged_in
from framework.exceptions import HTTPError
from website.oauth.models import ExternalAccount
from website.oauth.utils import get_service
@must_be_logged_in
def oauth_disconnect(external_account_id, auth):
account = ExternalAccount.load(external_account_id)
user = auth.user
if account is None:
HTTPError(http.NOT_FOUND)
if account not in user.external_accounts:
HTTPError(http.FORBIDDEN)
# iterate AddonUserSettings for addons
for user_settings in user.get_addons():
user_settings.revoke_oauth_access(account)
user_settings.save()
ExternalAccount.remove_one(account)
# # only after all addons have been dealt with can we remove it from the user
# user.external_accounts.remove(account)
user.save()
@must_be_logged_in
def oauth_connect(service_name, auth):
service = get_service(service_name)
return redirect(service.auth_url)
@must_be_logged_in
def oauth_callback(service_name, auth):
user = auth.user
provider = get_service(service_name)
# Retrieve permanent credentials from provider
provider.auth_callback(user=user)
if provider.account not in user.external_accounts:
user.external_accounts.append(provider.account)
user.save()
return {}
|
Add TODO for handling getOwnPropertyDescriptor support | 'use strict';
/**
* FUNCTION: moveProperty( source, prop, target )
* Moves a property from one object to another object.
*
* @param {Object} source - source object
* @param {String} prop - property to move
* @param {Object} target - target object
* @returns {Boolean} boolean indicating whether operation was successful
*/
function moveProperty( source, prop, target ) {
var desc;
if ( typeof source !== 'object' || source === null ) {
throw new TypeError( 'invalid input argument. Source argument must be an object. Value: `' + source + '`.' );
}
if ( typeof target !== 'object' || target === null ) {
throw new TypeError( 'invalid input argument. Target argument must be an object. Value: `' + target + '`.' );
}
// TODO: handle case where gOPD is not supported
desc = Object.getOwnPropertyDescriptor( source, prop );
if ( desc === void 0 ) {
return false;
}
delete source[ prop ];
Object.defineProperty( target, prop, desc );
return true;
} // end FUNCTION moveProperty()
// EXPORTS //
module.exports = moveProperty;
| 'use strict';
/**
* FUNCTION: moveProperty( source, prop, target )
* Moves a property from one object to another object.
*
* @param {Object} source - source object
* @param {String} prop - property to move
* @param {Object} target - target object
* @returns {Boolean} boolean indicating whether operation was successful
*/
function moveProperty( source, prop, target ) {
var desc;
if ( typeof source !== 'object' || source === null ) {
throw new TypeError( 'invalid input argument. Source argument must be an object. Value: `' + source + '`.' );
}
if ( typeof target !== 'object' || target === null ) {
throw new TypeError( 'invalid input argument. Target argument must be an object. Value: `' + target + '`.' );
}
desc = Object.getOwnPropertyDescriptor( source, prop );
if ( desc === void 0 ) {
return false;
}
delete source[ prop ];
Object.defineProperty( target, prop, desc );
return true;
} // end FUNCTION moveProperty()
// EXPORTS //
module.exports = moveProperty;
|
Use a class filter to allow expansion | import django_filters.rest_framework as filters
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import JSONRenderer
from rest_framework.throttling import UserRateThrottle, AnonRateThrottle
from rest_flex_fields import FlexFieldsModelViewSet
from readthedocs.projects.models import Project
from readthedocs.restapi.permissions import IsOwner
from .filters import ProjectFilter
from .serializers import ProjectSerializer
class APIv3Settings:
authentication_classes = (SessionAuthentication, TokenAuthentication)
permission_classes = (IsAuthenticated, IsOwner)
renderer_classes = (JSONRenderer,)
throttle_classes = (UserRateThrottle, AnonRateThrottle)
filter_backends = (filters.DjangoFilterBackend,)
class ProjectsViewSet(APIv3Settings, FlexFieldsModelViewSet):
model = Project
lookup_field = 'slug'
lookup_url_kwarg = 'project_slug'
serializer_class = ProjectSerializer
filterset_class = ProjectFilter
permit_list_expands = [
'users',
'active_versions',
'active_versions.last_build',
'active_versions.last_build.config',
]
def get_queryset(self):
user = self.request.user
return user.projects.all()
| import django_filters.rest_framework
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import JSONRenderer
from rest_framework.throttling import UserRateThrottle, AnonRateThrottle
from rest_flex_fields import FlexFieldsModelViewSet
from readthedocs.projects.models import Project
from readthedocs.restapi.permissions import IsOwner
from .serializers import ProjectSerializer
class APIv3Settings:
authentication_classes = (SessionAuthentication, TokenAuthentication)
permission_classes = (IsAuthenticated, IsOwner)
renderer_classes = (JSONRenderer,)
throttle_classes = (UserRateThrottle, AnonRateThrottle)
filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
class ProjectsViewSet(APIv3Settings, FlexFieldsModelViewSet):
model = Project
lookup_field = 'slug'
lookup_url_kwarg = 'project_slug'
serializer_class = ProjectSerializer
filterset_fields = (
'slug',
'privacy_level',
)
permit_list_expands = [
'users',
'active_versions',
'active_versions.last_build',
'active_versions.last_build.config',
]
def get_queryset(self):
user = self.request.user
return user.projects.all()
|
Fix lint error, unused param | package image
import (
"io"
"os"
"github.com/dnephin/dobi/tasks/context"
docker "github.com/fsouza/go-dockerclient"
)
// RunPush pushes an image to the registry
func RunPush(ctx *context.ExecuteContext, t *Task, _ bool) (bool, error) {
pushTag := func(tag string) error {
return pushImage(ctx, tag)
}
if err := t.ForEachTag(ctx, pushTag); err != nil {
return false, err
}
t.logger().Info("Pushed")
return true, nil
}
func pushImage(ctx *context.ExecuteContext, tag string) error {
repo, err := parseAuthRepo(tag)
if err != nil {
return err
}
return Stream(os.Stdout, func(out io.Writer) error {
return ctx.Client.PushImage(docker.PushImageOptions{
Name: tag,
OutputStream: out,
RawJSONStream: true,
// TODO: timeout
}, ctx.GetAuthConfig(repo))
})
}
| package image
import (
"io"
"os"
"github.com/dnephin/dobi/tasks/context"
docker "github.com/fsouza/go-dockerclient"
)
// RunPush pushes an image to the registry
func RunPush(ctx *context.ExecuteContext, t *Task, _ bool) (bool, error) {
pushTag := func(tag string) error {
return pushImage(ctx, t, tag)
}
if err := t.ForEachTag(ctx, pushTag); err != nil {
return false, err
}
t.logger().Info("Pushed")
return true, nil
}
func pushImage(ctx *context.ExecuteContext, t *Task, tag string) error {
repo, err := parseAuthRepo(tag)
if err != nil {
return err
}
return Stream(os.Stdout, func(out io.Writer) error {
return ctx.Client.PushImage(docker.PushImageOptions{
Name: tag,
OutputStream: out,
RawJSONStream: true,
// TODO: timeout
}, ctx.GetAuthConfig(repo))
})
}
|
Call super in SunburstWidgetIT setUp method.
Otherwise they fail with NullPointerExceptions.
[rev: ivo.miller] | /*
* Copyright 2017 Hewlett Packard Enterprise Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.autonomy.abc.dashboards;
import com.hp.autonomy.frontend.selenium.config.TestConfig;
import org.junit.Before;
public class SunburstWidgetITCase extends ClickableDashboardITCase {
public SunburstWidgetITCase(final TestConfig config) {
super(config, 1, "Sunburst Dashboard", "Sunburst", "SunburstSearch");
}
@Override
@Before
public void setUp() {
super.setUp();
page.waitForSunburstWidgetToRender();
}
//TODO once config is set up, test:
// * sunburst renders segments
// * sunburst resizes
// * legend is populated (colours, order by counts)
// * segment colours and ordering are correct (give segments data-id for testing?)
// * the 'too many entries' legend item is displayed when necessary
// * legend changes position with resizing
}
| /*
* Copyright 2017 Hewlett Packard Enterprise Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.autonomy.abc.dashboards;
import com.hp.autonomy.frontend.selenium.config.TestConfig;
import org.junit.Before;
public class SunburstWidgetITCase extends ClickableDashboardITCase {
public SunburstWidgetITCase(final TestConfig config) {
super(config, 1, "Sunburst Dashboard", "Sunburst", "SunburstSearch");
}
@Override
@Before
public void setUp() {
page.waitForSunburstWidgetToRender();
}
//TODO once config is set up, test:
// * sunburst renders segments
// * sunburst resizes
// * legend is populated (colours, order by counts)
// * segment colours and ordering are correct (give segments data-id for testing?)
// * the 'too many entries' legend item is displayed when necessary
// * legend changes position with resizing
}
|
Fix missing paren, imports, spelling. | """Retrieves the friendly model name for machines that don't have one yet."""
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
import server.utils as utils
from server.models import Machine
class Command(BaseCommand):
help = 'Retrieves friendly model names for machines without one'
def handle(self, *args, **options):
# Get all the machines without a friendly model name and have a model
no_friendly = Machine.objects.filter(
Q(machine_model_friendly__isnull=True) |
Q(machine_model_friendly='')
).exclude(machine_model__isnull=True).exclude(machine_model='').filter(os_family='Darwin')
for machine in no_friendly[:100]:
print(f'Processing {machine}')
machine.machine_model_friendly = utils.friendly_machine_model(machine)
machine.save()
| '''
Retrieves the firendly model name for machines that don't have one yet.
'''
from django.core.management.base import BaseCommand, CommandError
from server.models import Machine
from django.db.models import Q
import server.utils as utils
class Command(BaseCommand):
help = 'Retrieves friendly model names for machines without one'
def handle(self, *args, **options):
# Get all the machines without a friendly model name and have a model
no_friendly = Machine.objects.filter(
Q(machine_model_friendly__isnull=True) |
Q(machine_model_friendly='')
).exclude(machine_model__isnull=True).exclude(machine_model='').filter(os_family='Darwin')
for machine in no_friendly[:100]:
print(f'Processing {machine}'
machine.machine_model_friendly = utils.friendly_machine_model(machine)
machine.save()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.