text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix ErrorEvent logging + add Ember error listener | /* global DEBUG */
/* eslint-disable no-console */
import Ember from "ember";
import { argv } from "nwjs/argv";
import Logger from "utils/Logger";
const { logDebug, logError } = new Logger( "Application" );
const onError = async ( type, err, debug ) => {
if ( DEBUG ) {
console.error( type, err, debug );
}
try {
await logError( type ? `${type}: ${err}` : err, debug );
} catch ( e ) {}
};
process.on( "uncaughtException", e => onError( "uncaughtException", e ) );
window.addEventListener( "unhandledrejection", e => onError( e.type, e.reason, e.promise ) );
window.addEventListener( "error", e => onError( "error", e.error ) );
Ember.onerror = e => e && e.name !== "Adapter Error" ? onError( "Ember error", e ) : null;
// don't log parameters when running a dev build via grunt
if ( DEBUG ) {
console.debug( argv );
} else {
logDebug( "Parameters", argv );
}
| /* global DEBUG */
/* eslint-disable no-console */
import { argv } from "nwjs/argv";
import Logger from "utils/Logger";
const { logDebug, logError } = new Logger( "Application" );
const onError = async ( type, err, debug ) => {
if ( DEBUG ) {
console.error( type, err, debug );
}
try {
await logError( type ? `${type}: ${err}` : err, debug );
} catch ( e ) {}
};
process.on( "uncaughtException", e => onError( "uncaughtException", e ) );
window.addEventListener( "unhandledrejection", e => onError( e.type, e.reason, e.promise ) );
window.addEventListener( "error", e => onError( "error", e ) );
// don't log parameters when running a dev build via grunt
if ( DEBUG ) {
console.debug( argv );
} else {
logDebug( "Parameters", argv );
}
|
Fix guava test breakage due to GWT internal changes.
For some reason Guava tests call into GWT internal implementations.
I ported guava to use Arrays.copyRange instead of GWT's internal arrays methods. These
methods should never be called from any code outside of GWT's core module.
-------------
Created by MOE: http://code.google.com/p/moe-java
MOE_MIGRATED_REVID=98113442 | /*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.gwt.core.client.GwtScriptOnly;
import java.util.Arrays;
/**
* Version of {@link GwtPlatform} used in web-mode. It includes methods in
* {@link Platform} that requires different implementions in web mode and
* hosted mode. It is factored out from {@link Platform} because <code>
* {@literal @}GwtScriptOnly</code> only supports public classes and methods.
*
* @author Hayward Chan
*/
@GwtScriptOnly
public final class GwtPlatform {
private GwtPlatform() {}
public static <T> T[] clone(T[] array) {
return (T[]) Arrays.copyOfRange(array, 0, array.length);
}
}
| /*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.gwt.core.client.GwtScriptOnly;
import com.google.gwt.lang.Array;
/**
* Version of {@link GwtPlatform} used in web-mode. It includes methods in
* {@link Platform} that requires different implementions in web mode and
* hosted mode. It is factored out from {@link Platform} because <code>
* {@literal @}GwtScriptOnly</code> only supports public classes and methods.
*
* @author Hayward Chan
*/
@GwtScriptOnly
public final class GwtPlatform {
private GwtPlatform() {}
public static <T> T[] clone(T[] array) {
return (T[]) Array.clone(array);
}
}
|
Fix incorrect display of variable id in tooltip | package org.cyclops.integrateddynamics.core.item;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.cyclops.cyclopscore.helper.L10NHelpers;
import org.cyclops.integrateddynamics.IntegratedDynamics;
import java.util.List;
/**
* Base implementation of {@link IVariableFacade}
* @author rubensworks
*/
public abstract class VariableFacadeBase implements IVariableFacade {
private final int id;
public VariableFacadeBase(boolean generateId) {
this.id = generateId ? IntegratedDynamics.globalCounters.getNext("variable") : -1;
}
public VariableFacadeBase(int id) {
this.id = id;
}
@Override
public final int getId() {
return this.id;
}
@SideOnly(Side.CLIENT)
@Override
public void addInformation(List<String> list, EntityPlayer entityPlayer) {
list.add(L10NHelpers.localize("item.items.integrateddynamics.variable.id", getId() == -1 ? "..." : getId()));
}
}
| package org.cyclops.integrateddynamics.core.item;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.cyclops.cyclopscore.helper.L10NHelpers;
import org.cyclops.integrateddynamics.IntegratedDynamics;
import java.util.List;
/**
* Base implementation of {@link IVariableFacade}
* @author rubensworks
*/
public abstract class VariableFacadeBase implements IVariableFacade {
private final int id;
public VariableFacadeBase(boolean generateId) {
this.id = generateId ? IntegratedDynamics.globalCounters.getNext("variable") : -1;
}
public VariableFacadeBase(int id) {
this.id = id;
}
@Override
public final int getId() {
return this.id;
}
@SideOnly(Side.CLIENT)
@Override
public void addInformation(List<String> list, EntityPlayer entityPlayer) {
list.add(L10NHelpers.localize("item.items.integrateddynamics.variable.id", getId() > -1 ? "..." : getId()));
}
}
|
Fix call to old flowlet API in example | package DependencyRandomNumber;
import java.util.Random;
import com.continuuity.api.flow.flowlet.FlowletSpecifier;
import com.continuuity.api.flow.flowlet.SourceFlowlet;
import com.continuuity.api.flow.flowlet.OutputCollector;
import com.continuuity.api.flow.flowlet.Tuple;
import com.continuuity.api.flow.flowlet.TupleSchema;
import com.continuuity.api.flow.flowlet.builders.TupleBuilder;
import com.continuuity.api.flow.flowlet.builders.TupleSchemaBuilder;
public class RandomNumberSource extends SourceFlowlet {
private Random random;
@Override
public void configure(FlowletSpecifier specifier) {
TupleSchema out = new TupleSchemaBuilder().
add("randomNumber", Long.class).
create();
specifier.getDefaultFlowletOutput().setSchema(out);
}
@Override
public void initialize() {
super.initialize();
this.random = new Random();
}
@Override
public void generate(OutputCollector outputCollector) {
long randomNumber = Math.abs(this.random.nextLong());
Tuple randomNumberTuple = new TupleBuilder()
.set("randomNumber", randomNumber)
.create();
outputCollector.add(randomNumberTuple);
}
}
| package DependencyRandomNumber;
import java.util.Random;
import com.continuuity.api.flow.flowlet.SourceFlowlet;
import com.continuuity.api.flow.flowlet.OutputCollector;
import com.continuuity.api.flow.flowlet.StreamsConfigurator;
import com.continuuity.api.flow.flowlet.Tuple;
import com.continuuity.api.flow.flowlet.TupleSchema;
import com.continuuity.api.flow.flowlet.builders.TupleBuilder;
import com.continuuity.api.flow.flowlet.builders.TupleSchemaBuilder;
public class RandomNumberSource extends SourceFlowlet {
private Random random;
@Override
public void configure(StreamsConfigurator configurator) {
TupleSchema out = new TupleSchemaBuilder().
add("randomNumber", Long.class).
create();
configurator.getDefaultTupleOutputStream().setSchema(out);
}
@Override
public void initialize() {
super.initialize();
this.random = new Random();
}
@Override
public void generate(OutputCollector outputCollector) {
long randomNumber = Math.abs(this.random.nextLong());
Tuple randomNumberTuple = new TupleBuilder()
.set("randomNumber", randomNumber)
.create();
outputCollector.add(randomNumberTuple);
}
}
|
Add type for Condorcet autoloader | <?php
/*
Condorcet PHP - Election manager and results calculator.
Designed for the Condorcet method. Integrating a large number of algorithms extending Condorcet. Expandable for all types of voting systems.
By Julien Boudry and contributors - MIT LICENSE (Please read LICENSE.txt)
https://github.com/julien-boudry/Condorcet
*/
declare(strict_types=1);
// Self Autoload function coming after and as a fallback of composer or other framework PSR autoload implementation. Composer or framework autoload will alway be will be preferred to that custom function.
spl_autoload_register(function (string $class) : void {
// project-specific namespace prefix
$prefix = 'CondorcetPHP\\Condorcet\\';
// does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) :
// no, move to the next registered autoloader
return;
endif;
// get the relative class name
$relative_class = substr($class, $len);
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = __DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $relative_class) . '.php';
// if the file exists, require it
if (file_exists($file)) :
require $file;
endif;
});
| <?php
/*
Condorcet PHP - Election manager and results calculator.
Designed for the Condorcet method. Integrating a large number of algorithms extending Condorcet. Expandable for all types of voting systems.
By Julien Boudry and contributors - MIT LICENSE (Please read LICENSE.txt)
https://github.com/julien-boudry/Condorcet
*/
// Self Autoload function coming after and as a fallback of composer or other framework PSR autoload implementation. Composer or framework autoload will alway be will be preferred to that custom function.
spl_autoload_register(function ($class) {
// project-specific namespace prefix
$prefix = 'CondorcetPHP\\Condorcet\\';
// does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) :
// no, move to the next registered autoloader
return false;
endif;
// get the relative class name
$relative_class = substr($class, $len);
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = __DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $relative_class) . '.php';
// if the file exists, require it
if (file_exists($file)) :
require $file;
else :
return false;
endif;
});
|
Revert changes, doesn't seem to work.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Config;
use Orchestra\Story\Model\Content;
class OrchestraStoryMakeContentsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$format = Config::get('orchestra/story::config.default_format', 'markdown');
Schema::create('story_contents', function ($table) use ($format)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('slug');
$table->string('title');
$table->text('content');
$table->string('format')->default($format);
$table->string('type')->default(Content::POST);
$table->string('status')->default(Content::STATUS_DRAFT);
$table->timestamps();
$table->datetime('published_at');
$table->softDeletes();
$table->index('user_id');
$table->index('slug');
$table->index('format');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('story_contents');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Config;
use Orchestra\Story\Model\Content;
class OrchestraStoryMakeContentsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$format = Config::get('orchestra/story::default_format', 'markdown');
Schema::create('story_contents', function ($table) use ($format)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('slug');
$table->string('title');
$table->text('content');
$table->string('format')->default($format);
$table->string('type')->default(Content::POST);
$table->string('status')->default(Content::STATUS_DRAFT);
$table->timestamps();
$table->datetime('published_at');
$table->softDeletes();
$table->index('user_id');
$table->index('slug');
$table->index('format');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('story_contents');
}
}
|
Fix typo in route template security | <?php
namespace Listabierta\Bundle\MunicipalesBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;
class SecurityController extends Controller
{
public function loginAction(Request $request)
{
$session = $request->getSession();
// get the login error if there is one
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR))
{
$error = $request->attributes->get(
SecurityContext::AUTHENTICATION_ERROR
);
} else
{
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
return $this->render(
'MunicipalesBundle:Security:login.html.twig',
array(
// last username entered by the user
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
)
);
}
} | <?php
namespace Listabierta\Bundle\MunicipalesBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;
class SecurityController extends Controller
{
public function loginAction(Request $request)
{
$session = $request->getSession();
// get the login error if there is one
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR))
{
$error = $request->attributes->get(
SecurityContext::AUTHENTICATION_ERROR
);
} else
{
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
return $this->render(
'MunicipalesBundle::Security:login.html.twig',
array(
// last username entered by the user
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
)
);
}
} |
[automerger] Merge "Use api from 26" into oc-mr1-support-27.0-dev am: f5c970b5df am: 0e91a7eccb
Change-Id: Ie2bf4613e238a264bcbcff78f4e28d0e33bb2b82 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.arch.lifecycle;
import android.app.PictureInPictureParams;
import android.os.Build;
import android.support.test.filters.SdkSuppress;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
@SdkSuppress(maxSdkVersion = Build.VERSION_CODES.N_MR1)
@SmallTest
public class MissingClassTest {
public static class ObserverWithMissingClasses {
@SuppressWarnings("unused")
public void newApiMethod(PictureInPictureParams params) {}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {}
}
@Test(expected = IllegalArgumentException.class)
public void testMissingApi() {
new ReflectiveGenericLifecycleObserver(new ObserverWithMissingClasses());
}
}
| /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.arch.lifecycle;
import android.media.PlaybackParams;
import android.os.Build;
import android.support.test.filters.SdkSuppress;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
@SdkSuppress(maxSdkVersion = Build.VERSION_CODES.N_MR1)
@SmallTest
public class MissingClassTest {
public static class ObserverWithMissingClasses {
@SuppressWarnings("unused")
public void newApiMethod(PlaybackParams params) {}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {}
}
@Test(expected = IllegalArgumentException.class)
public void testMissingApi() {
new ReflectiveGenericLifecycleObserver(new ObserverWithMissingClasses());
}
}
|
Add a missing trailing comma | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const kCID = Components.ID('{B1223178-FCE2-4185-8E74-BE1DC67E1831}');
const kID = '@clear-code.com/tb-bug766495/startup;1';
const kNAME = 'tbBug766495StartupService';
const Cc = Components.classes;
const Ci = Components.interfaces;
Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');
XPCOMUtils.defineLazyModuleGetter(this,
"AutoCompactionController",
"resource://tb-bug766495-modules/auto-compaction-controller.jsm");
function tbBug766495StartupService() {}
tbBug766495StartupService.prototype = {
classID : kCID,
contractID : kID,
classDescription : kNAME,
observe : function(aSubject, aTopic, aData) {
AutoCompactionController.activateAutoCompaction();
},
QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver]),
};
var NSGetFactory = XPCOMUtils.generateNSGetFactory([tbBug766495StartupService]);
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const kCID = Components.ID('{B1223178-FCE2-4185-8E74-BE1DC67E1831}');
const kID = '@clear-code.com/tb-bug766495/startup;1';
const kNAME = 'tbBug766495StartupService';
const Cc = Components.classes;
const Ci = Components.interfaces;
Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');
XPCOMUtils.defineLazyModuleGetter(this,
"AutoCompactionController",
"resource://tb-bug766495-modules/auto-compaction-controller.jsm");
function tbBug766495StartupService() {}
tbBug766495StartupService.prototype = {
classID : kCID,
contractID : kID,
classDescription : kNAME,
observe : function(aSubject, aTopic, aData) {
AutoCompactionController.activateAutoCompaction();
},
QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver]),
}
var NSGetFactory = XPCOMUtils.generateNSGetFactory([tbBug766495StartupService]);
|
Split the Python specific version exludes between 2.7/3.4 specific syntax. | from compileall import compile_dir
from distutils.sysconfig import get_python_lib
import os
import os.path
import sys
EXCLUDES_27 = [
'pymysql/_socketio.py',
]
EXCLUDES_34 = [
'gunicorn/workers/_gaiohttp.py',
]
def compile_files(path):
return compile_dir(path, maxlevels=50, quiet=True)
def remove_python3_files(path):
excludes = []
if sys.version_info < (2, 7):
excludes.extend(EXCLUDES_27)
if sys.version_info < (3, 4):
excludes.extend(EXCLUDES_34)
for e in excludes:
fp = os.path.join(path, e)
for extension in ('', 'c', 'o'):
name = fp + extension
if os.path.exists(name):
print('Removing file %s containing Python 3 syntax.' % name)
os.remove(name)
def main():
sp = get_python_lib()
remove_python3_files(sp)
status = compile_files(sp)
sys.exit(not status)
if __name__ == '__main__':
main()
| from compileall import compile_dir
from distutils.sysconfig import get_python_lib
import os
import os.path
import sys
EXCLUDES = [
'gunicorn/workers/_gaiohttp.py',
'pymysql/_socketio.py',
]
def compile_files(path):
return compile_dir(path, maxlevels=50, quiet=True)
def remove_python3_files(path):
for e in EXCLUDES:
fp = os.path.join(path, e)
for extension in ('', 'c', 'o'):
name = fp + extension
if os.path.exists(name):
print('Removing file %s containing Python 3 syntax.' % name)
os.remove(name)
def main():
sp = get_python_lib()
remove_python3_files(sp)
status = compile_files(sp)
sys.exit(not status)
if __name__ == '__main__':
main()
|
Resolve browser field even in server runtime
Otherwise node shims aren't included (see
https://github.com/substack/node-browserify/issues/1654). | #!/usr/bin/env node
'use strict'
const browserify = require('browserify')
const str = require('string-to-stream')
const babel = require('babel-core')
const babelify = require('babelify')
const envify = require('envify')
const pkg = require('../package.json')
browserify(str(js(pkg)), { basedir: process.cwd() })
.transform(babelify.configure({
presets: [require('babel-preset-react')],
plugins: [require('babel-plugin-transform-es2015-modules-commonjs')]
}))
.transform(envify)
.transform(require('brfs'))
.bundle((err, content) => {
if (err) throw err
const opts = { presets: [require('babel-preset-babili')], comments: false }
const res = babel.transform(content, opts)
if (err) throw err
console.log(res.code)
})
function js ({ name }) {
return (
`import createServerRenderer from '${name}/server_renderer.js'
import dataToState from '${name}/lib/data_to_state'
import components from './components'
const { html, data } = __params
const renderer = createServerRenderer({
components,
state: dataToState(data)
})
const $ = renderer(html)
$('body').attr('data-penguin-built', 'true')
__params.output = $.html()
`
)
}
| #!/usr/bin/env node
'use strict'
const browserify = require('browserify')
const str = require('string-to-stream')
const babel = require('babel-core')
const babelify = require('babelify')
const envify = require('envify')
const pkg = require('../package.json')
browserify(str(js(pkg)), { basedir: process.cwd(), detectGlobals: false, browserField: false })
.transform(babelify.configure({
presets: [require('babel-preset-react')],
plugins: [require('babel-plugin-transform-es2015-modules-commonjs')]
}))
.transform(envify)
.transform(require('brfs'))
.bundle((err, content) => {
if (err) throw err
const opts = { presets: [require('babel-preset-babili')], comments: false }
const res = babel.transform(content, opts)
if (err) throw err
console.log(res.code)
})
function js ({ name }) {
return (
`import createServerRenderer from '${name}/server_renderer.js'
import dataToState from '${name}/lib/data_to_state'
import components from './components'
const { html, data } = __params
const renderer = createServerRenderer({
components,
state: dataToState(data)
})
const $ = renderer(html)
$('body').attr('data-penguin-built', 'true')
__params.output = $.html()
`
)
}
|
Change template extension from .tpl to .ng.html | /**
* Created by netanel on 01/01/15.
*/
var minify = Npm.require('html-minifier').minify;
Plugin.registerSourceHandler('ng.html', {
isTemplate: true,
archMatching: "web"
}, function(compileStep) {
var contents = compileStep.read().toString('utf8');
var results = 'angular.module(\'angular-meteor\').run([\'$templateCache\', function($templateCache) {' +
// Since compileStep.inputPath uses backslashes on Windows, we need replace them
// with forward slashes to be able to consistently include templates across platforms.
// Ticket here: https://github.com/Urigo/angular-meteor/issues/169
// A standardized solution to this problem might be on its way, see this ticket:
// https://github.com/meteor/windows-preview/issues/47
'$templateCache.put(\'' + compileStep.inputPath.replace(/\\/g, "/") + '\', \'' +
minify(contents.replace(/'/g, "\\'"), {
collapseWhitespace : true,
removeComments : true,
minifyJS : true,
minifyCSS: true,
processScripts : ['text/ng-template']
}) + '\');' +
'}]);';
compileStep.addJavaScript({
path : compileStep.inputPath,
data : results,
sourcePath : compileStep.inputPath
});
});
| /**
* Created by netanel on 01/01/15.
*/
var minify = Npm.require('html-minifier').minify;
Plugin.registerSourceHandler('tpl', {
isTemplate: true,
archMatching: "web"
}, function(compileStep) {
var contents = compileStep.read().toString('utf8');
var results = 'angular.module(\'angular-meteor\').run([\'$templateCache\', function($templateCache) {' +
// Since compileStep.inputPath uses backslashes on Windows, we need replace them
// with forward slashes to be able to consistently include templates across platforms.
// Ticket here: https://github.com/Urigo/angular-meteor/issues/169
// A standardized solution to this problem might be on its way, see this ticket:
// https://github.com/meteor/windows-preview/issues/47
'$templateCache.put(\'' + compileStep.inputPath.replace(/\\/g, "/") + '\', \'' +
minify(contents.replace(/'/g, "\\'"), {
collapseWhitespace : true,
removeComments : true,
minifyJS : true,
minifyCSS: true,
processScripts : ['text/ng-template']
}) + '\');' +
'}]);';
compileStep.addJavaScript({
path : compileStep.inputPath,
data : results,
sourcePath : compileStep.inputPath
});
});
|
Watch bower.json and run wiredep | 'use strict';
module.exports = function (grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Configure tasks
grunt.initConfig({
// Project settings
project: {
app: 'app'
},
// Watch files and execute tasks when they change
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= project.app %>/*.html'
]
}
},
// Grunt servers
connect: {
options: {
port: 9000,
hostname: 'localhost',
livereload: true
},
livereload: {
options: {
open: true,
base: '<%= project.app %>'
}
}
},
wiredep: {
app: {
src: ['<%= project.app %>/index.html']
}
}
});
grunt.registerTask('serve', ['wiredep', 'connect:livereload', 'watch']);
}; | 'use strict';
module.exports = function (grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Configure tasks
grunt.initConfig({
// Project settings
project: {
app: 'app'
},
// Watch files and execute tasks when they change
watch: {
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= project.app %>/*.html'
]
}
},
// Grunt servers
connect: {
options: {
port: 9000,
hostname: 'localhost',
livereload: true
},
livereload: {
options: {
open: true,
base: '<%= project.app %>'
}
}
},
wiredep: {
app: {
src: ['<%= project.app %>/index.html']
}
}
});
grunt.registerTask('serve', ['wiredep', 'connect:livereload', 'watch']);
}; |
Remove output when restarting apache after module enable | import os
import yaml
def load_modules(data):
result = yaml.load(data)
if result:
apache = result.get('apache', {})
if apache:
return apache.get('modules', [])
return []
def install_modules(modules):
installed = 0
for module in modules:
print " Installing Apache module %s" % module
os.system("a2enmod "+module+" >/dev/null 2>&1")
installed = installed + 1
if installed > 0:
os.system('/etc/init.d/apache2 restart >/dev/null 2>&1')
print " Done enabling Apache modules."
else:
print " No Apache modules to enabled."
def load_file(working_dir="/home/application/current"):
files_name = ["app.yaml", "app.yml"]
for file_name in files_name:
try:
with open(os.path.join(working_dir, file_name)) as f:
return f.read()
except IOError:
pass
return ""
def main():
print ""
print ""
print ""
print "========================================"
print " Parsing Apache modules to enable"
print "========================================"
print ""
data = load_file()
modules = load_modules(data)
install_modules(modules)
main()
| import os
import yaml
def load_modules(data):
result = yaml.load(data)
if result:
apache = result.get('apache', {})
if apache:
return apache.get('modules', [])
return []
def install_modules(modules):
installed = 0
for module in modules:
print " Installing Apache module %s" % module
os.system("a2enmod "+module+" >/dev/null 2>&1")
installed = installed + 1
if installed > 0:
os.system('/etc/init.d/apache2 restart')
print " Done enabling Apache modules."
else:
print " No Apache modules to enabled."
def load_file(working_dir="/home/application/current"):
files_name = ["app.yaml", "app.yml"]
for file_name in files_name:
try:
with open(os.path.join(working_dir, file_name)) as f:
return f.read()
except IOError:
pass
return ""
def main():
print ""
print ""
print ""
print "========================================"
print " Parsing Apache modules to enable"
print "========================================"
print ""
data = load_file()
modules = load_modules(data)
install_modules(modules)
main()
|
Add test showing issue with rna_type | from django.test import TestCase
from portal.models import Rna
class GenericRnaTypeTest(TestCase):
def rna_type_of(self, upi, taxid=None):
return Rna.objects.\
get(upi=upi).\
get_rna_type(taxid=taxid, recompute=True)
def assertRnaTypeIs(self, description, upi, taxid=None):
self.assertEquals(description, self.description_of(upi, taxid=taxid))
class WormTests(GenericRnaTypeTest):
def test_gets_mirna_over_pirna(self):
self.assertRnaTypeIs(
'miRNA',
'URS0000016972',
taxid=6239)
class HumanTests(GenericRnaTypeTest):
def test_if_has_both_anti_and_lnc_likes_lnc(self):
self.assertRnaTypeIs(
'lncRNA',
'URS0000732D5D',
taxid=9606)
| from django.test import TestCase
from portal.models import Rna
class GenericRnaTypeTest(TestCase):
def rna_type_of(self, upi, taxid=None):
return Rna.objects.\
get(upi=upi).\
get_rna_type(taxid=taxid, recompute=True)
def assertRnaTypeIs(self, description, upi, taxid=None):
self.assertEquals(description, self.description_of(upi, taxid=taxid))
class WormTests(GenericRnaTypeTest):
def test_gets_mirna_over_pirna(self):
self.assertRnaTypeIs(
'miRNA',
'URS0000016972',
taxid=6239)
|
Update help text to match default style | package main
import (
"os"
"github.com/taylorskalyo/stno/action"
"gopkg.in/urfave/cli.v1"
)
func main() {
app := cli.NewApp()
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "journal, j",
Usage: "load the journal titled `JOURNAL`",
},
cli.StringFlag{
Name: "config, c",
Usage: "load configuration from `FILE`",
},
}
app.Commands = []cli.Command{
{
Name: "add",
Usage: "Adds a journal entry",
Action: action.Add,
},
{
Name: "query",
Usage: "Queries journal entries",
Action: action.Query,
},
}
app.Run(os.Args)
}
| package main
import (
"os"
"github.com/taylorskalyo/stno/action"
"gopkg.in/urfave/cli.v1"
)
func main() {
app := cli.NewApp()
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "journal, j",
Usage: "Load the journal titled `JOURNAL`",
},
cli.StringFlag{
Name: "config, c",
Usage: "Load configuration from `FILE`",
},
}
app.Commands = []cli.Command{
{
Name: "add",
Usage: "add a journal entry",
Action: action.Add,
},
{
Name: "query",
Usage: "filter and display journal entries",
Action: action.Query,
},
}
app.Run(os.Args)
}
|
Set component div to 100% height | 'use strict'
var document = require('global/document')
var Loop = require('main-loop')
var virtualDom = require('virtual-dom')
var assert = require('assert')
var partial = require('ap').partial
var Delegator = require('dom-delegator')
// Instantiate a DOM delegator once, since it caches itself
Delegator()
exports.createComponent = createComponent
function createComponent (Component, data, callback) {
assert(Component, 'Component is required')
if (arguments.length < 2) return partial(createComponent, Component)
if (typeof data === 'function') {
callback = data
data = undefined
}
// Call the component constructor to get a new state
var state = Component(data)
// Add an element for later use
var div = document.createElement('div')
div.style.height = '100%'
document.body.appendChild(div)
// create a raf rendering loop and add the target element to the dom
var loop = Loop(state(), Component.render, virtualDom)
div.appendChild(loop.target)
// update the loop whenever the state changes
state(loop.update)
return callback(state, loop.target, destroy)
function destroy () {
// remove the element from the DOM
document.body.removeChild(div)
}
}
| 'use strict'
var document = require('global/document')
var Loop = require('main-loop')
var virtualDom = require('virtual-dom')
var assert = require('assert')
var partial = require('ap').partial
var Delegator = require('dom-delegator')
// Instantiate a DOM delegator once, since it caches itself
Delegator()
exports.createComponent = createComponent
function createComponent (Component, data, callback) {
assert(Component, 'Component is required')
if (arguments.length < 2) return partial(createComponent, Component)
if (typeof data === 'function') {
callback = data
data = undefined
}
// Call the component constructor to get a new state
var state = Component(data)
// Add an element for later use
var div = document.createElement('div')
document.body.appendChild(div)
// create a raf rendering loop and add the target element to the dom
var loop = Loop(state(), Component.render, virtualDom)
div.appendChild(loop.target)
// update the loop whenever the state changes
state(loop.update)
return callback(state, loop.target, destroy)
function destroy () {
// remove the element from the DOM
document.body.removeChild(div)
}
}
|
Fix to take into account history in API queries. | from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__historical_seed_set__seedset_id")
seed = ListFilter(name="harvest__historical_seeds__seed_id", distinct=True)
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
| from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__seed_set__seedset_id")
seed = ListFilter(name="harvest__seed_set__seeds__seed_id", distinct=True)
# TODO: This will need to be changed to use historical seeds once #54 is completed.
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
|
Update the default server for the nats dumper and subscribe to the ingest | package main
import (
"encoding/json"
"flag"
"fmt"
nats "github.com/nats-io/go-nats"
"github.com/regner/albiondata-client/lib"
)
var natsURL string
func init() {
flag.StringVar(
&natsURL,
"i",
"nats://ingest.albion-data.com:4222",
"NATS URL to subscribe to.",
)
}
func dumpMarketOrders(m *nats.Msg) {
morders := &lib.MarketUpload{}
if err := json.Unmarshal(m.Data, morders); err != nil {
fmt.Printf("%v\n", err)
}
for _, order := range morders.Orders {
jb, _ := json.Marshal(order)
fmt.Printf("%d %s\n", order.LocationID, string(jb))
}
}
func main() {
flag.Parse()
nc, _ := nats.Connect(natsURL)
defer nc.Close()
marketCh := make(chan *nats.Msg, 64)
marketSub, err := nc.ChanSubscribe("marketorders.ingest", marketCh)
if err != nil {
fmt.Printf("%v\n", err)
return
}
defer marketSub.Unsubscribe()
for {
select {
case msg := <-marketCh:
dumpMarketOrders(msg)
}
}
}
| package main
import (
"encoding/json"
"flag"
"fmt"
nats "github.com/nats-io/go-nats"
"github.com/regner/albiondata-client/lib"
)
var natsURL string
func init() {
flag.StringVar(
&natsURL,
"i",
"nats://localhost:2222",
"NATS URL to subscribe to.",
)
}
func dumpMarketOrders(m *nats.Msg) {
morders := &lib.MarketUpload{}
if err := json.Unmarshal(m.Data, morders); err != nil {
fmt.Printf("%v\n", err)
}
for _, order := range morders.Orders {
jb, _ := json.Marshal(order)
fmt.Printf("%d %s\n", order.LocationID, string(jb))
}
}
func main() {
flag.Parse()
nc, _ := nats.Connect(natsURL)
defer nc.Close()
marketCh := make(chan *nats.Msg, 64)
marketSub, err := nc.ChanSubscribe("marketorders", marketCh)
if err != nil {
fmt.Printf("%v\n", err)
return
}
defer marketSub.Unsubscribe()
for {
select {
case msg := <-marketCh:
dumpMarketOrders(msg)
}
}
}
|
Rename method for getting PersonalData instance | package clientAPI;
import clientAPI.impl.BonusCreditStoreConnector;
import clientAPI.impl.CryptoStoreConnector;
import clientAPI.impl.PersonalDataConnector;
import clientAPI.impl.TicketManagerConnector;
import clientAPI.impl.WalletConnector;
import javax.smartcardio.Card;
public class ClientFactory {
/**
*
* @return
*/
public static TicketManager getTicketManager(Card card) {
return new TicketManagerConnector(card);
}
/**
*
* @return
*/
public static Wallet getWallet(Card card) {
return new WalletConnector(card);
}
/**
*
* @return
*/
public static BonusCreditStore getBonusCreditStore(Card card) {
return new BonusCreditStoreConnector(card);
}
/**
*
* @return
*/
public static PersonalData getPersonalData(Card card) {
return new PersonalDataConnector(card);
}
/**
*
* @return
*/
public static CryptoStore getCryptoStore(Card card) {
return new CryptoStoreConnector(card);
}
}
| package clientAPI;
import clientAPI.impl.BonusCreditStoreConnector;
import clientAPI.impl.CryptoStoreConnector;
import clientAPI.impl.PersonalDataConnector;
import clientAPI.impl.TicketManagerConnector;
import clientAPI.impl.WalletConnector;
import javax.smartcardio.Card;
public class ClientFactory {
/**
*
* @return
*/
public static TicketManager getTicketManager(Card card) {
return new TicketManagerConnector(card);
}
/**
*
* @return
*/
public static Wallet getWallet(Card card) {
return new WalletConnector(card);
}
/**
*
* @return
*/
public static BonusCreditStore getBonusCreditStore(Card card) {
return new BonusCreditStoreConnector(card);
}
/**
*
* @return
*/
public static PersonalData getCustomerData(Card card) {
return new PersonalDataConnector(card);
}
/**
*
* @return
*/
public static CryptoStore getCryptoStore(Card card) {
return new CryptoStoreConnector(card);
}
}
|
Remove unused imports in mesos cluster | from sparkperf.cluster import Cluster
import json
import os
import urllib2
class MesosCluster(Cluster):
"""
Functionality for interacting with a already running Mesos Spark cluster.
All the behavior for starting and stopping the cluster is not supported.
"""
def __init__(self, spark_home, mesos_master, spark_conf_dir = None, commit_sha="unknown"):
self.spark_home = spark_home
self.mesos_master = mesos_master
self.spark_conf_dir = spark_conf_dir
self.commit_sha = commit_sha
state_url = "http://" + os.path.join(mesos_master.strip("mesos://"), "state.json")
resp = urllib2.urlopen(state_url)
if resp.getcode() != 200:
raise "Bad status code returned fetching state.json from mesos master"
state = json.loads(resp.read())
self.slaves = list(map((lambda slave: slave["hostname"]), state["slaves"]))
def sync_spark(self):
None
def stop(self):
None
def start(self):
None
def ensure_spark_stopped_on_slaves(self):
None
| from sparkperf.cluster import Cluster
import json
import re
import os
import sys
import time
import urllib2
class MesosCluster(Cluster):
"""
Functionality for interacting with a already running Mesos Spark cluster.
All the behavior for starting and stopping the cluster is not supported.
"""
def __init__(self, spark_home, mesos_master, spark_conf_dir = None, commit_sha="unknown"):
self.spark_home = spark_home
self.mesos_master = mesos_master
self.spark_conf_dir = spark_conf_dir
self.commit_sha = commit_sha
state_url = "http://" + os.path.join(mesos_master.strip("mesos://"), "state.json")
resp = urllib2.urlopen(state_url)
if resp.getcode() != 200:
raise "Bad status code returned fetching state.json from mesos master"
state = json.loads(resp.read())
self.slaves = list(map((lambda slave: slave["hostname"]), state["slaves"]))
def sync_spark(self):
None
def stop(self):
None
def start(self):
None
def ensure_spark_stopped_on_slaves(self):
None
|
Add a reset task to drop and recreate the db tables with one command. | # -*- coding: utf-8 -*-
from flask import current_app, g
from flask.ext.script import Manager, Server, prompt_bool
from massa import create_app
manager = Manager(create_app)
manager.add_option('-c', '--config', dest='config', required=False)
manager.add_command('runserver', Server(
use_debugger = True,
use_reloader = True,
host = '0.0.0.0',
port = 8080,
))
@manager.command
def db_create_tables():
"""Create all the db tables."""
current_app.preprocess_request()
db = g.sl('db')
db.create_tables()
@manager.command
def db_drop_tables():
"""Drop all the db tables."""
if prompt_bool('Are you sure you want to drop all the db tables?'):
current_app.preprocess_request()
db = g.sl('db')
db.drop_tables()
@manager.command
def db_reset_tables():
"""Drop and (re)create all the db tables."""
if prompt_bool('Are you sure you want to reset all the db tables?'):
current_app.preprocess_request()
db = g.sl('db')
db.drop_tables()
db.create_tables()
if __name__ == '__main__':
manager.run()
| # -*- coding: utf-8 -*-
from flask import current_app, g
from flask.ext.script import Manager, Server, prompt_bool
from massa import create_app
manager = Manager(create_app)
manager.add_option('-c', '--config', dest='config', required=False)
manager.add_command('runserver', Server(
use_debugger = True,
use_reloader = True,
host = '0.0.0.0',
port = 8080,
))
@manager.command
def db_create_tables():
"""Create all the db tables."""
current_app.preprocess_request()
db = g.sl('db')
db.create_tables()
@manager.command
def db_drop_tables():
"""Drop all the db tables."""
if prompt_bool('Are you sure you want to drop all the db tables?'):
current_app.preprocess_request()
db = g.sl('db')
db.drop_tables()
if __name__ == '__main__':
manager.run()
|
Allow serving from root paths | #!/usr/bin/env node
'use strict'
const path = require('path')
const flags = require('commander')
const markserv = require(path.join(__dirname, 'server'))
const pkg = require(path.join('..', 'package.json'))
const cwd = process.cwd()
flags.dir = cwd
flags.version(pkg.version)
.usage('<file/dir>')
.option('-p, --port [type]', 'HTTP port [port]', 8642)
.option('-l, --livereloadport [type]', 'LiveReload port [livereloadport]', 35729)
.option('-i, --silent [type]', 'Silent (no logs to CLI)', false)
.option('-a, --address [type]', 'Serve on ip/address [address]', 'localhost')
.option('-v, --verbose', 'verbose output')
.action(serverPath => {
flags.$pathProvided = true
if (flags.dir[0] !== '/') {
flags.dir = path.normalize(path.join(cwd, serverPath))
}
}).parse(process.argv)
markserv.init(flags)
| #!/usr/bin/env node
'use strict'
const path = require('path')
const flags = require('commander')
const markserv = require(path.join(__dirname, 'server'))
const pkg = require(path.join('..', 'package.json'))
const cwd = process.cwd()
flags.dir = cwd
flags.version(pkg.version)
.usage('<file/dir>')
.option('-p, --port [type]', 'HTTP port [port]', 8642)
.option('-l, --livereloadport [type]', 'LiveReload port [livereloadport]', 35729)
.option('-i, --silent [type]', 'Silent (no logs to CLI)', false)
.option('-a, --address [type]', 'Serve on ip/address [address]', 'localhost')
.option('-v, --verbose', 'verbose output')
.action(serverPath => {
flags.$pathProvided = true
flags.dir = path.normalize(path.join(cwd, serverPath))
}).parse(process.argv)
markserv.init(flags)
|
Use Whoosh in prod for now. | from django_website.settings.www import *
PREPEND_WWW = False
APPEND_SLASH = True
TEMPLATE_CONTEXT_PROCESSORS += ["django.core.context_processors.request"]
ROOT_URLCONF = 'django_website.urls.docs'
CACHE_MIDDLEWARE_KEY_PREFIX = 'djangodocs'
_has_ddt = 'debug_toolbar' in INSTALLED_APPS
INSTALLED_APPS = [
'django_website.docs',
'haystack',
]
if _has_ddt:
INSTALLED_APPS.append('debug_toolbar')
# Where to store the build Sphinx docs.
if PRODUCTION:
DOCS_BUILD_ROOT = BASE.ancestor(2).child('docbuilds')
else:
DOCS_BUILD_ROOT = '/tmp/djangodocs'
# Haystack settings
HAYSTACK_SITECONF = 'django_website.docs.search_sites'
HAYSTACK_SEARCH_ENGINE = 'whoosh'
HAYSTACK_WHOOSH_PATH = '/tmp/djangodocs.index'
| from django_website.settings.www import *
PREPEND_WWW = False
APPEND_SLASH = True
TEMPLATE_CONTEXT_PROCESSORS += ["django.core.context_processors.request"]
ROOT_URLCONF = 'django_website.urls.docs'
CACHE_MIDDLEWARE_KEY_PREFIX = 'djangodocs'
_has_ddt = 'debug_toolbar' in INSTALLED_APPS
INSTALLED_APPS = [
'django_website.docs',
'haystack',
]
if _has_ddt:
INSTALLED_APPS.append('debug_toolbar')
# Where to store the build Sphinx docs.
if PRODUCTION:
DOCS_BUILD_ROOT = BASE.ancestor(2).child('docbuilds')
else:
DOCS_BUILD_ROOT = '/tmp/djangodocs'
# Haystack settings
HAYSTACK_SITECONF = 'django_website.docs.search_sites'
if PRODUCTION:
HAYSTACK_SEARCH_ENGINE = 'solr'
HAYSTACK_SOLR_URL = 'http://127.0.0.1:8983/solr'
else:
HAYSTACK_SEARCH_ENGINE = 'whoosh'
HAYSTACK_WHOOSH_PATH = '/tmp/djangodocs.index'
|
[ENH] jcapture: Implement token authorisation and reconfigure file data to upload into filegallery
git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@42026 b456876b-0849-0410-b77d-98878d47e9d5 | // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
// JS glue for jCapture feature
function openJCaptureDialog() {
var $appletDiv = $("#jCaptureAppletDiv");
if ($appletDiv.length) {
$appletDiv.remove();
}
$appletDiv = $("<div id='jCaptureAppletDiv' style='width:1px;height:1px;visibility:hidden;'> </div>");
$(document.body).append($appletDiv);
$.get($.service('jcapture', 'capture'), {
area: "none",
page: "test"
}, function(data){
$appletDiv.html(data);
});
// } else { TODO later
// $appletDiv[0].showCaptureFrame();
// }
}
function insertAtCarret( areaId, dokuTag ) {
var tag = dokuTag.substring(3, dokuTag.length - 3);
alert("file : " + tag);
if (areaId) {
insertAt( areaId, tag);
}
}
| // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
// JS glue for jCapture feature
function openJCaptureDialog() {
var $appletDiv = $("#jCaptureAppletDiv");
if ($appletDiv.length) {
$appletDiv.remove();
}
$appletDiv = $("<div id='jCaptureAppletDiv'> </div>");
$(document.body).append($appletDiv);
$.get($.service('jcapture', 'capture'), {
area: "none",
page: "test"
}, function(data){
$appletDiv.html(data);
});
// } else { TODO later
// $appletDiv[0].showCaptureFrame();
// }
}
function insertAtCarret( areaId, dokuTag ) {
var tag = dokuTag.subString(3, dokuTag.length - 3);
alert("file : " + tag);
if (areaId) {
insertAt( areaId, tag);
}
}
|
Increase test timeout when run in TravisCI
- potential fix for
https://travis-ci.org/lidel/ipfs-firefox-addon/jobs/109478424#L271 | 'use strict'
require('../lib/peer-watch.js')
const { env } = require('sdk/system/environment')
const { setTimeout } = require('sdk/timers')
const { prefs } = require('sdk/simple-prefs')
const tabs = require('sdk/tabs')
const gw = require('../lib/gateways.js')
exports['test automatic mode disabling redirect when IPFS API is offline'] = function (assert, done) {
const ipfsPath = 'ipfs/QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D/Makefile'
const checkDelay = ('TRAVIS' in env && 'CI' in env) ? 5000 : 500
prefs.apiPollInterval = 100 // faster test
prefs.customApiPort = 59999 // change to something that will always fail
prefs.useCustomGateway = true
prefs.automatic = true
setTimeout(function () {
assert.equal(prefs.automatic, true, 'automatic mode should be enabled')
assert.equal(prefs.useCustomGateway, false, 'redirect should be automatically disabled')
assert.equal(gw.redirectEnabled, false, 'redirect should be automatically disabled')
tabs.open({
url: 'https://ipfs.io/' + ipfsPath,
onReady: function onReady (tab) {
assert.equal(tab.url, 'https://ipfs.io/' + ipfsPath, 'expected no redirect')
tab.close(done)
}
})
}, prefs.apiPollInterval + checkDelay)
}
require('./prefs-util.js').isolateTestCases(exports)
require('sdk/test').run(exports)
| 'use strict'
require('../lib/peer-watch.js')
const { setTimeout } = require('sdk/timers')
const { prefs } = require('sdk/simple-prefs')
const tabs = require('sdk/tabs')
const gw = require('../lib/gateways.js')
exports['test automatic mode disabling redirect when IPFS API is offline'] = function (assert, done) {
const ipfsPath = 'ipfs/QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D/Makefile'
prefs.apiPollInterval = 100 // faster test
prefs.customApiPort = 59999 // change to something that will always fail
prefs.useCustomGateway = true
prefs.automatic = true
setTimeout(function () {
assert.equal(prefs.automatic, true, 'automatic mode should be enabled')
assert.equal(prefs.useCustomGateway, false, 'redirect should be automatically disabled')
assert.equal(gw.redirectEnabled, false, 'redirect should be automatically disabled')
tabs.open({
url: 'https://ipfs.io/' + ipfsPath,
onReady: function onReady (tab) {
assert.equal(tab.url, 'https://ipfs.io/' + ipfsPath, 'expected no redirect')
tab.close(done)
}
})
}, prefs.apiPollInterval + 500)
}
require('./prefs-util.js').isolateTestCases(exports)
require('sdk/test').run(exports)
|
Revert D6139620: [redex] Fix line_map tests
Summary:
This reverts commit 120d0731995f10ef4969d06cd9109c0585107ac2
bypass-lint
Differential Revision: D6139620
fbshipit-source-id: 59ed38a5e980f7684ad413d8d77bf89a0f180070 | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.redexlinemap;
import static org.fest.assertions.api.Assertions.*;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class DisabledLineMapTest {
@NoInline
private void wrapsThrow() throws Exception {
throw new Exception("foo");
}
private void inlinedThrower() throws Exception {
wrapsThrow();
}
@Test
public void testStackTraceWithoutLineMap() {
try {
inlinedThrower();
} catch (Exception e) {
List<StackTraceElement> trace = Arrays.asList(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 3)).isEqualTo(Arrays.asList(
"com.facebook.redexlinemap.DisabledLineMapTest.wrapsThrow(DisabledLineMapTest.java:22)",
"com.facebook.redexlinemap.DisabledLineMapTest.testStackTraceWithoutLineMap(DisabledLineMapTest.java:26)",
"java.lang.reflect.Method.invokeNative(Native Method)"));
}
}
}
| /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.redexlinemap;
import static org.fest.assertions.api.Assertions.*;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class DisabledLineMapTest {
@NoInline
private void wrapsThrow() throws Exception {
throw new Exception("foo");
}
private void inlinedThrower() throws Exception {
wrapsThrow();
}
@Test
public void testStackTraceWithoutLineMap() {
try {
inlinedThrower();
} catch (Exception e) {
List<StackTraceElement> trace = Arrays.asList(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 2)).isEqualTo(Arrays.asList(
"com.facebook.redexlinemap.DisabledLineMapTest.wrapsThrow(DisabledLineMapTest.java:22)",
"com.facebook.redexlinemap.DisabledLineMapTest.testStackTraceWithoutLineMap(DisabledLineMapTest.java:26)"));
}
}
}
|
Define all functions the same way | function getLogin(){
return window.location.hash.slice(1)
}
var foundTemplate = $('#template').html();
Mustache.parse(foundTemplate);
function loadData(login, cb){
if(login){
var searchURL = 'https://api.github.com/search/issues?q=type:pr+author:'+login+'&sort=created&order=asc&per_page=1'
$.getJSON(searchURL, function(data){
if(data.items.length > 0){
$.getJSON(data.items[0].pull_request.url, function(data){
cb(data)
})
} else {
cb(null)
}
}).error(function() { renderError(getLogin()+" isn't a valid GitHub login") })
}
}
function renderData(pullRequestData){
if(pullRequestData){
$('#main').html(Mustache.render(foundTemplate, pullRequestData))
} else {
renderError('It doesn\'t look like '+getLogin()+' has sent a pull request yet.')
}
}
function renderError(message){
$('#main').html("<p>"+message+"</p>")
}
$(window).on('hashchange',function(){
loadData(getLogin(), renderData)
});
$('#user-form').submit(function(){
window.location.hash = $('#login')[0].value
$('#login')[0].value = ""
return false
})
loadData(getLogin(), renderData)
| function getLogin(){
return window.location.hash.slice(1)
}
var foundTemplate = $('#template').html();
Mustache.parse(foundTemplate);
var loadData = function(login, cb){
if(login){
var searchURL = 'https://api.github.com/search/issues?q=type:pr+author:'+login+'&sort=created&order=asc&per_page=1'
$.getJSON(searchURL, function(data){
if(data.items.length > 0){
$.getJSON(data.items[0].pull_request.url, function(data){
cb(data)
})
} else {
cb(null)
}
}).error(function() { renderError(getLogin()+" isn't a valid GitHub login") })
}
}
var renderData = function(pullRequestData){
if(pullRequestData){
$('#main').html(Mustache.render(foundTemplate, pullRequestData))
} else {
renderError('It doesn\'t look like '+getLogin()+' has sent a pull request yet.')
}
}
var renderError = function (message) {
$('#main').html("<p>"+message+"</p>")
}
$(window).on('hashchange',function(){
loadData(getLogin(), renderData)
});
$('#user-form').submit(function(){
window.location.hash = $('#login')[0].value
$('#login')[0].value = ""
return false
})
loadData(getLogin(), renderData)
|
Fix entities showing up in German reset button / confirm dialog | var messages = {
warningReset: {
'en': 'Are you sure you want to reset the game?\n\nYour saved progress will be lost and you\'ll be sent to the start of the game.',
'de': 'Bist su sicher, dass du das Spiel zurücksetzen möchtest?\n\nDein gespeicherter Fortschritt geht dabei verloren und du musst das Spiel von neuem starten.',
'fr': 'Êtes-vous certain de vouloir réinitialiser la partie?\n\nVotre progrès sauvegardé sera perdu et vous recommencerez au début du jeu.',
'pt-br': 'Você tem certeza que quer reinicializar o jogo?\n\nSeu progresso salvo será perdido e você voltará ao começo do jogo.'
},
labelReset: {
'en': 'Reset',
'de': 'Zurücksetzen',
'fr': 'Réinitialiser',
'pt-br': 'Reinicializar'
}
};
| var messages = {
warningReset: {
'en': 'Are you sure you want to reset the game?\n\nYour saved progress will be lost and you\'ll be sent to the start of the game.',
'de': 'Bist su sicher, dass du das Spiel zurücksetzen möchtest?\n\nDein gespeicherter Fortschritt geht dabei verloren und du musst das Spiel von neuem starten.',
'fr': 'Êtes-vous certain de vouloir réinitialiser la partie?\n\nVotre progrès sauvegardé sera perdu et vous recommencerez au début du jeu.',
'pt-br': 'Você tem certeza que quer reinicializar o jogo?\n\nSeu progresso salvo será perdido e você voltará ao começo do jogo.'
},
labelReset: {
'en': 'Reset',
'de': 'Zurücksetzen',
'fr': 'Réinitialiser',
'pt-br': 'Reinicializar'
}
};
|
Add support for newer thread layout | // ==UserScript==
// @name Modify URL @2ch
// @namespace curipha
// @description Modify texts starting with "ttp://" to anchor and redirect URIs to direct link
// @include http://*.2ch.net/*
// @include http://*.bbspink.com/*
// @version 0.1.2
// @grant none
// @noframes
// ==/UserScript==
(function(){
'use strict';
var anchor = document.getElementsByTagName('a');
for (var a of anchor) {
if (a.href.indexOf('http://jump.2ch.net/?') === 0) {
a.href = decodeURIComponent(a.href.slice(21)); // 'http://jump.2ch.net/?'.length -> 21
}
else if (a.href.indexOf('http://pinktower.com/?') === 0) {
a.href = decodeURIComponent('http://' + a.href.slice(22)); // 'http://pinktower.com/?'.length -> 22
}
}
var res = document.getElementsByTagName('dd');
if (res.length < 1) res = document.getElementsByClassName('message');
var ttp = /([^h])(ttps?:\/\/[\x21\x23-\x3b\x3d\x3f-\x7E]+)/ig;
for (var d of res) {
d.innerHTML = d.innerHTML.replace(ttp, '$1<a href="h$2">$2</a>');
}
})();
| // ==UserScript==
// @name Modify URL @2ch
// @namespace curipha
// @description Modify texts starting with "ttp://" to anchor and redirect URIs to direct link
// @include http://*.2ch.net/*
// @include http://*.bbspink.com/*
// @version 0.1.2
// @grant none
// @noframes
// ==/UserScript==
(function(){
'use strict';
var anchor = document.getElementsByTagName('a');
for (var a of anchor) {
if (a.href.indexOf('http://jump.2ch.net/?') === 0) {
a.href = decodeURIComponent(a.href.slice(21)); // 'http://jump.2ch.net/?'.length -> 21
}
else if (a.href.indexOf('http://pinktower.com/?') === 0) {
a.href = decodeURIComponent('http://' + a.href.slice(22)); // 'http://pinktower.com/?'.length -> 22
}
}
var dd = document.getElementsByTagName('dd');
var ttp = /([^h])(ttps?:\/\/[\x21\x23-\x3b\x3d\x3f-\x7E]+)/ig;
for (var d of dd) {
d.innerHTML = d.innerHTML.replace(ttp, '$1<a href="h$2">$2</a>');
}
})();
|
Bz1178758: Fix JBDS import errors in ejb-throws-exception quickstart | /*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.quickstarts.ear.client;
/**
* @author bmaxwell
*
*/
public class GreeterException extends Exception {
/** Default value included to remove warning. **/
private static final long serialVersionUID = 1L;
/**
*
*/
public GreeterException() {
}
/**
* @param message
*/
public GreeterException(String message) {
super(message);
}
/**
* @param cause
*/
public GreeterException(Throwable cause) {
super(cause);
}
/**
* @param message
* @param cause
*/
public GreeterException(String message, Throwable cause) {
super(message, cause);
}
}
| /*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.quickstarts.ear.client;
/**
* @author bmaxwell
*
*/
public class GreeterException extends Exception {
/**
*
*/
public GreeterException() {
}
/**
* @param message
*/
public GreeterException(String message) {
super(message);
}
/**
* @param cause
*/
public GreeterException(Throwable cause) {
super(cause);
}
/**
* @param message
* @param cause
*/
public GreeterException(String message, Throwable cause) {
super(message, cause);
}
}
|
Adjust search to make use of Disease Ontology terms | package org.pdxfinder.repositories;
import org.pdxfinder.dao.OntologyTerm;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.Collection;
/**
* Created by csaba on 07/06/2017.
*/
@Repository
public interface OntologyTermRepository extends PagingAndSortingRepository<OntologyTerm, Long>
{
OntologyTerm findById();
@Query("MATCH (o:OntologyTerm) WHERE toLower(o.label) = toLower({label}) return o")
OntologyTerm findByLabel(@Param("label") String label);
OntologyTerm findByUrl(String url);
@Query("match(o:OntologyTerm) return o limit 40")
Collection<OntologyTerm> findByOntologyTermLabel(@Param("label") String label);
@Query("MATCH (oTerm:OntologyTerm)<-[SUBCLASS_OF]-(subNodes) where oTerm.label CONTAINS trim(toLower({searchParam})) WITH COLLECT(subNodes) AS subNodes " +
"UNWIND subNodes AS subN " +
"MATCH (oTerm:OntologyTerm)<-[SUBCLASS_OF]-(subNodes2) where oTerm.label=subN.label return subN,subNodes2 limit 15")
Collection<OntologyTerm> findByDiseaseOntologyTerm(@Param("searchParam") String searchParam);
}
| package org.pdxfinder.repositories;
import org.pdxfinder.dao.OntologyTerm;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.Collection;
/**
* Created by csaba on 07/06/2017.
*/
@Repository
public interface OntologyTermRepository extends PagingAndSortingRepository<OntologyTerm, Long>
{
OntologyTerm findById();
@Query("MATCH (o:OntologyTerm) WHERE toLower(o.label) = toLower({label}) return o")
OntologyTerm findByLabel(@Param("label") String label);
OntologyTerm findByUrl(String url);
@Query("match(o:OntologyTerm) return o limit 40")
Collection<OntologyTerm> findByOntologyTermLabel(@Param("label") String label);
@Query("MATCH (oTerm:OntologyTerm)<-[SUBCLASS_OF]-(subNodes) where oTerm.label CONTAINS trim(toLower({searchParam})) WITH COLLECT(subNodes) AS subNodes " +
"UNWIND subNodes AS subN " +
"MATCH (oTerm:OntologyTerm)<-[SUBCLASS_OF]-(subNodes2) where oTerm.label=subN.label return subN,subNodes2 limit 8")
Collection<OntologyTerm> findByDiseaseOntologyTerm(@Param("searchParam") String searchParam);
}
|
Fix incorrectly captured value in closure in KeyAssignedListView example. | from clubsandwich.director import DirectorLoop
from clubsandwich.ui import UIScene, WindowView, KeyAssignedListView, ButtonView
class BasicScene(UIScene):
def __init__(self):
button_generator = (ButtonView(
text="Item {}".format(i),
callback=lambda x=i: print("Called Item {}".format(x)))
for i in range(0, 100)
)
self.key_assign = KeyAssignedListView(
value_controls=button_generator
)
super().__init__(WindowView(
"Scrolling Text", subviews=[self.key_assign]))
class DemoLoop(DirectorLoop):
def get_initial_scene(self):
return BasicScene()
if __name__ == '__main__':
DemoLoop().run()
| from clubsandwich.director import DirectorLoop
from clubsandwich.ui import UIScene, WindowView, KeyAssignedListView, ButtonView
class BasicScene(UIScene):
def __init__(self):
button_generator = (ButtonView(
text="Item {}".format(i),
callback=lambda: print("Called Item {}".format(i)))
for i in range(0, 100)
)
self.key_assign = KeyAssignedListView(
value_controls=button_generator
)
super().__init__(WindowView(
"Scrolling Text", subviews=[self.key_assign]))
class DemoLoop(DirectorLoop):
def get_initial_scene(self):
return BasicScene()
if __name__ == '__main__':
DemoLoop().run()
|
Add linting of unused arguments | // Variables http://eslint.org/docs/rules/#variables
module.exports = {
"rules": {
"init-declarations": [ "error", "always" ], // enforce or disallow variable initializations at definition
"no-catch-shadow": "error", // disallow the catch clause parameter name being the same as a variable in the outer scope
"no-delete-var": "error", // disallow deletion of variables
"no-label-var": "error", // disallow labels that share a name with a variable
"no-restricted-globals": "off", // disallow specified global variables
"no-shadow-restricted-names": "error", // disallow shadowing of names such as arguments
"no-shadow": "error", // JSHINT disallow declaration of variables already declared in the outer scope
"no-undef-init": "error", // disallow use of undefined when initializing variables
"no-undef": "error", // JSHINT disallow use of undeclared variables unless mentioned in a /*global */ block
"no-undefined": "off", // disallow use of undefined variable
"no-unused-vars": [ "error", { "vars": "all", "args": "after-used", "ignoreRestSiblings": false, "argsIgnorePattern": "^_" } ], // JSHINT disallow declaration of variables that are not used in the code
"no-use-before-define": [ "error", "nofunc" ] // JSHINT disallow use of variables before they are defined
}
};
| // Variables http://eslint.org/docs/rules/#variables
module.exports = {
"rules": {
"init-declarations": [ "error", "always" ], // enforce or disallow variable initializations at definition
"no-catch-shadow": "error", // disallow the catch clause parameter name being the same as a variable in the outer scope
"no-delete-var": "error", // disallow deletion of variables
"no-label-var": "error", // disallow labels that share a name with a variable
"no-restricted-globals": "off", // disallow specified global variables
"no-shadow-restricted-names": "error", // disallow shadowing of names such as arguments
"no-shadow": "error", // JSHINT disallow declaration of variables already declared in the outer scope
"no-undef-init": "error", // disallow use of undefined when initializing variables
"no-undef": "error", // JSHINT disallow use of undeclared variables unless mentioned in a /*global */ block
"no-undefined": "off", // disallow use of undefined variable
"no-unused-vars": [ "error", { "vars": "all", "args": "none" } ], // JSHINT disallow declaration of variables that are not used in the code
"no-use-before-define": [ "error", "nofunc" ] // JSHINT disallow use of variables before they are defined
}
};
|
Use `process.nextTick` to yield instead of `setTimeout`
Fixes an issue with min-webdriver where it async_script calls respond
with a timeout error if no timeout has been configured explicitly. | /*global Mocha, window*/
/*
* mocaccino.js
*
* Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
*
* @license MIT
*/
'use strict';
require('brout');
require('mocha/mocha');
Mocha.reporters.Base.window.width = JSON.parse('{{WINDOW_WIDTH}}');
Mocha.reporters.Base.symbols.dot = '.';
var mocha = new Mocha();
mocha.reporter('{{REPORTER}}');
mocha.suite.emit('pre-require', window, '', mocha);
var t = new Date().getTime();
var y = Number('{{YIELDS}}');
mocha.suite.afterEach(function (done) {
var now = new Date().getTime();
if (now - t > y) {
t = now;
process.nextTick(done);
} else {
done();
}
});
setTimeout(function () {
Mocha.process.stdout = process.stdout;
mocha.run(function (errs) {
process.exit(errs ? 1 : 0);
});
}, 1);
| /*global Mocha, window*/
/*
* mocaccino.js
*
* Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
*
* @license MIT
*/
'use strict';
require('brout');
require('mocha/mocha');
Mocha.reporters.Base.window.width = JSON.parse('{{WINDOW_WIDTH}}');
Mocha.reporters.Base.symbols.dot = '.';
var mocha = new Mocha();
mocha.reporter('{{REPORTER}}');
mocha.suite.emit('pre-require', window, '', mocha);
var t = new Date().getTime();
var y = Number('{{YIELDS}}');
mocha.suite.afterEach(function (done) {
var now = new Date().getTime();
if (now - t > y) {
t = now;
setTimeout(done, 1);
} else {
done();
}
});
setTimeout(function () {
Mocha.process.stdout = process.stdout;
mocha.run(function (errs) {
process.exit(errs ? 1 : 0);
});
}, 1);
|
Fix typo and move missing import into edit view | from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
#from google.appengine.ext import db
from july.people.models import Commit
from gae_django.auth.models import User
from django.http import Http404
def user_profile(request, username):
user = User.all().filter("username", username).get()
if user == None:
raise Http404("User not found")
commits = Commit.all().ancestor(request.user.key())
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request))
@login_required
def edit_profile(request, username, template_name='people/edit.html'):
from forms import EditUserForm
user = request.user
#CONSIDER FILES with no POST? Can that happen?
form = EditUserForm(request.POST or None, request.FILES or None)
if form.is_valid():
for key in form.cleaned_data:
setattr(user,key,form.cleaned_data.get(key))
user.put()
if user == None:
raise Http404("User not found")
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response(template_name, {'form':form, }, RequestContext(request))
| from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
#from google.appengine.ext import db
from july.people.models import Commit
from gae_django.auth.models import User
from django.http import Http404
from forms import EditUserForm
def user_profile(request, username):
user = User.all().filter("username", username).get()
if user == None:
raise Http404("User not found")
commits = Commit.all().ancestor(request.user.key())
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request))
@login_required
def edit_profile(request, username, template_name='people/edit.html'):
user = request.user
#CONSIDER FILES with no POST? Can that happen?
form = EditUserForm(request.POST or None, request.FILES or None)
if form.is_valid():
for key in form.cleaned_data:
setattr(user,key,form.cleaned_data.get(key))
user.put()
if user == None:
raise Http404("User not found")
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response(template_name, {'form':form, }, RequestContext(request))
|
FIX (router): use proper import instead of depricated | import { createStore, applyMiddleware, compose } from 'redux';
import { createHashHistory } from 'history';
import { routerMiddleware } from 'connected-react-router';
import createRootReducer from 'reducers/root';
import gitHubAPIMiddleware from 'middlewares/gitHubAPI';
export const history = createHashHistory();
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const middlewares = [routerMiddleware(history), gitHubAPIMiddleware];
if (process.env.NODE_ENV === 'development') {
const freeze = require('redux-freeze');
// const { createLogger } = require('redux-logger');
// const logger = createLogger({ collapsed: true });
const middlewaresToAdd = [
freeze
// logger
];
middlewares.push(...middlewaresToAdd);
}
const store = createStore(
createRootReducer(history),
composeEnhancers(applyMiddleware(...middlewares))
);
export default store;
| import { createStore, applyMiddleware, compose } from 'redux';
import createHistory from 'history/createHashHistory';
import { routerMiddleware } from 'connected-react-router';
import createRootReducer from 'reducers/root';
import gitHubAPIMiddleware from 'middlewares/gitHubAPI';
export const history = createHistory();
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const middlewares = [routerMiddleware(history), gitHubAPIMiddleware];
if (process.env.NODE_ENV === 'development') {
const freeze = require('redux-freeze');
// const { createLogger } = require('redux-logger');
// const logger = createLogger({ collapsed: true });
const middlewaresToAdd = [
freeze
// logger
];
middlewares.push(...middlewaresToAdd);
}
const store = createStore(
createRootReducer(history),
composeEnhancers(applyMiddleware(...middlewares))
);
export default store;
|
[Backoffice] Use safer checks to prevent unknown methods. | <?php
/**
* This file is part of the Clastic package.
*
* (c) Dries De Peuter <dries@nousefreak.be>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Clastic\BackofficeBundle\Tests;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @author Dries De Peuter <dries@nousefreak.be>
*/
class SecurityTest extends WebTestCase
{
public function testLoginRedirect()
{
$client = static::createClient();
$client->request('GET', '/admin/');
$this->assertTrue($client->getResponse()->isRedirect());
$this->assertRegExp('|/admin/login$|', $client->getResponse()->headers->get('location'));
}
public function testLoginForm()
{
$client = static::createClient();
$crawler = $client->request('GET', '/admin/login');
$this->assertEquals(1, $crawler->filter('form')->count());
$this->assertEquals(1, $crawler->filter('form input[name="_username"]')->count());
$this->assertEquals(1, $crawler->filter('form input[name="_password"]')->count());
$this->assertEquals(1, $crawler->filter('form input[name="_remember_me"]')->count());
$this->assertEquals(1, $crawler->filter('form button[name="_submit"]')->count());
}
}
| <?php
/**
* This file is part of the Clastic package.
*
* (c) Dries De Peuter <dries@nousefreak.be>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Clastic\BackofficeBundle\Tests;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @author Dries De Peuter <dries@nousefreak.be>
*/
class SecurityTest extends WebTestCase
{
public function testLoginRedirect()
{
$client = static::createClient();
$client->request('GET', '/admin/');
$this->assertTrue($client->getResponse()->isRedirect());
$this->assertRegExp('|/admin/login$|', $client->getResponse()->headers->get('location'));
}
// public function testLoginForm()
// {
// $client = static::createClient();
// $crawler = $client->request('GET', '/admin/login');
//
// $this->assertEquals(1, $crawler->filter('form')->count());
// $this->assertEquals(1, $crawler->filter('form input[name="_username"]')->count());
// $this->assertEquals(1, $crawler->filter('form input[name="_password"]')->count());
// $this->assertEquals(1, $crawler->filter('form input[name="_remember_me"]')->count());
// $this->assertEquals(1, $crawler->filter('form button[name="_submit"]')->count());
// }
}
|
pw_cli: Add quotes around user-provided values
Change-Id: Ifc5fafeefef0dea65cb3aba90b985e6be31fa0bd
Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/81980
Reviewed-by: Joe Ethier <f5eb8cb2f5310c7fa9df6f16eabccb4436f47999@google.com>
Commit-Queue: RJ Ascani <4734195edb8e393f72741de86b813743e1460cb1@google.com> | # Copyright 2021 The Pigweed Authors
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
"""Defines argument types for use with argparse."""
import argparse
import logging
from pathlib import Path
def directory(arg: str) -> Path:
path = Path(arg)
if path.is_dir():
return path.resolve()
raise argparse.ArgumentTypeError(f'"{path}" is not a directory')
def log_level(arg: str) -> int:
try:
return getattr(logging, arg.upper())
except AttributeError:
raise argparse.ArgumentTypeError(
f'"{arg.upper()}" is not a valid log level')
| # Copyright 2021 The Pigweed Authors
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
"""Defines argument types for use with argparse."""
import argparse
import logging
from pathlib import Path
def directory(arg: str) -> Path:
path = Path(arg)
if path.is_dir():
return path.resolve()
raise argparse.ArgumentTypeError(f'{path} is not a directory')
def log_level(arg: str) -> int:
try:
return getattr(logging, arg.upper())
except AttributeError:
raise argparse.ArgumentTypeError(
f'{arg.upper()} is not a valid log level')
|
Move configuration details to docs | """
homeassistant.components.device_tracker.mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MQTT platform for the device tracker.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.mqtt.html
"""
import logging
from homeassistant import util
import homeassistant.components.mqtt as mqtt
DEPENDENCIES = ['mqtt']
CONF_QOS = 'qos'
CONF_DEVICES = 'devices'
DEFAULT_QOS = 0
_LOGGER = logging.getLogger(__name__)
def setup_scanner(hass, config, see):
""" Set up a MQTT tracker. """
devices = config.get(CONF_DEVICES)
qos = util.convert(config.get(CONF_QOS), int, DEFAULT_QOS)
if not isinstance(devices, dict):
_LOGGER.error('Expected %s to be a dict, found %s', CONF_DEVICES,
devices)
return False
dev_id_lookup = {}
def device_tracker_message_received(topic, payload, qos):
""" MQTT message received. """
see(dev_id=dev_id_lookup[topic], location_name=payload)
for dev_id, topic in devices.items():
dev_id_lookup[topic] = dev_id
mqtt.subscribe(hass, topic, device_tracker_message_received, qos)
return True
| """
homeassistant.components.device_tracker.mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MQTT platform for the device tracker.
device_tracker:
platform: mqtt
qos: 1
devices:
paulus_oneplus: /location/paulus
annetherese_n4: /location/annetherese
"""
import logging
from homeassistant import util
import homeassistant.components.mqtt as mqtt
DEPENDENCIES = ['mqtt']
CONF_QOS = 'qos'
CONF_DEVICES = 'devices'
DEFAULT_QOS = 0
_LOGGER = logging.getLogger(__name__)
def setup_scanner(hass, config, see):
""" Set up a MQTT tracker. """
devices = config.get(CONF_DEVICES)
qos = util.convert(config.get(CONF_QOS), int, DEFAULT_QOS)
if not isinstance(devices, dict):
_LOGGER.error('Expected %s to be a dict, found %s', CONF_DEVICES,
devices)
return False
dev_id_lookup = {}
def device_tracker_message_received(topic, payload, qos):
""" MQTT message received. """
see(dev_id=dev_id_lookup[topic], location_name=payload)
for dev_id, topic in devices.items():
dev_id_lookup[topic] = dev_id
mqtt.subscribe(hass, topic, device_tracker_message_received, qos)
return True
|
Use String instead of ordinal for AuthorizationType | package org.ligoj.bootstrap.model.system;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.springframework.http.HttpMethod;
import org.ligoj.bootstrap.core.model.AbstractAudited;
import lombok.Getter;
import lombok.Setter;
/**
* A dynamic authorization for a role on a specified module.
*/
@Entity
@Table(name = "S_AUTHORIZATION")
@Getter
@Setter
public class SystemAuthorization extends AbstractAudited<Integer> {
/**
* Authorization type.
*/
public enum AuthorizationType {
/**
* Business authorization.
*/
BUSINESS,
/**
* UI authorization.
*/
UI
}
/**
* SID
*/
private static final long serialVersionUID = 1L;
@Enumerated(EnumType.STRING)
@NotNull
private AuthorizationType type;
/**
* Associated role.
*/
@ManyToOne
@NotNull
private SystemRole role;
/**
* Authorized URL as pattern.
*/
@NotNull
private String pattern;
/**
* Authorized URL method. Can be <tt>null</tt> for all methods.
*/
@Enumerated(EnumType.STRING)
private HttpMethod method;
}
| package org.ligoj.bootstrap.model.system;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.springframework.http.HttpMethod;
import org.ligoj.bootstrap.core.model.AbstractAudited;
import lombok.Getter;
import lombok.Setter;
/**
* A dynamic authorization for a role on a specified module.
*/
@Entity
@Table(name = "S_AUTHORIZATION")
@Getter
@Setter
public class SystemAuthorization extends AbstractAudited<Integer> {
/**
* Authorization type.
*/
public enum AuthorizationType {
/**
* Business authorization.
*/
BUSINESS,
/**
* UI authorization.
*/
UI
}
/**
* SID
*/
private static final long serialVersionUID = 1L;
@Enumerated(EnumType.ORDINAL)
@NotNull
private AuthorizationType type;
/**
* Associated role.
*/
@ManyToOne
@NotNull
private SystemRole role;
/**
* Authorized URL as pattern.
*/
@NotNull
private String pattern;
/**
* Authorized URL method. Can be <tt>null</tt> for all methods.
*/
private HttpMethod method;
}
|
Add remove() utility function for Arrays | export function compose() {
var fns = Array.from(arguments);
return function(source) {
return fns.reduce(function(result, fn) {
return fn(result);
}, source) ;
};
}
export function rearg(fn) {
return function(options) {
return function(arg) {
return fn(arg, options);
};
};
}
export function rearg3f(fn) {
return function(x, y, z) {
return function(arg) {
return fn(arg, x, y, z);
};
};
}
function numericSort(a, b) {
return a - b;
}
export function removeIndices(array, indices) {
indices.sort(numericSort);
var i = indices.length;
while (i--) {
array.splice(indices[i], 1);
}
}
export function remove(array, element) {
var index = array.indexOf(element);
if (index >= 0) {
array.splice(index, 1);
}
}
| export function compose() {
var fns = Array.from(arguments);
return function(source) {
return fns.reduce(function(result, fn) {
return fn(result);
}, source) ;
};
}
export function rearg(fn) {
return function(options) {
return function(arg) {
return fn(arg, options);
};
};
}
export function rearg3f(fn) {
return function(x, y, z) {
return function(arg) {
return fn(arg, x, y, z);
};
};
}
function numericSort(a, b) {
return a - b;
}
export function removeIndices(array, indices) {
indices.sort(numericSort);
var i = indices.length;
while (i--) {
array.splice(indices[i], 1);
}
}
|
Add management file to packages so django can find it | from setuptools import setup
setup(
name='django-simpleimages',
version='1.0.0',
author='Saul Shanabrook',
author_email='s.shanabrook@gmail.com',
packages=['simpleimages', 'simpleimages.management.commands'],
url='https://www.github.com/saulshanabrook/django-simpleimages',
license=open('LICENSE.txt').read(),
description='Opinionated Django image transforms on models',
long_description=open('README.rst').read(),
install_requires=[
"Django>=1.5,<=1.6",
"six"
],
zip_safe=False, # so that django finds management commands,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Operating System :: Unix',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries',
],
)
| from setuptools import setup
setup(
name='django-simpleimages',
version='1.0.0',
author='Saul Shanabrook',
author_email='s.shanabrook@gmail.com',
packages=['simpleimages', ],
url='https://www.github.com/saulshanabrook/django-simpleimages',
license=open('LICENSE.txt').read(),
description='Opinionated Django image transforms on models',
long_description=open('README.rst').read(),
install_requires=[
"Django>=1.5,<=1.6",
"six"
],
zip_safe=False, # so that django finds management commands,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Operating System :: Unix',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries',
],
)
|
Clean up gbm progress page | package water.api;
import hex.gbm.GBM.GBMModel;
import water.*;
import com.google.gson.JsonObject;
public class GBMProgressPage extends Progress2 {
/** Return {@link Response} for finished job. */
@Override protected Response jobDone(final Job job, final String dst) {
JsonObject args = new JsonObject();
args.addProperty("model_key", job.dest().toString());
return GBMModelView.redirect(this, job.dest());
}
public static Response redirect(Request req, Key jobkey, Key dest) {
return new Response(Response.Status.redirect, req, -1, -1, "GBMProgressPage", "job", jobkey, "dst_key", dest);
}
@Override public boolean toHTML(StringBuilder sb) {
Job jjob = Job.findJob(Key.make(job.value()));
Value value = DKV.get(jjob.dest());
if( value == null ) DocGen.HTML.paragraph(sb, "Pending...");
else ((GBMModel)value.get()).generateHTML("GBM Model", sb);
return true;
}
}
| package water.api;
import hex.gbm.GBM.GBMModel;
import water.*;
import com.google.gson.JsonObject;
public class GBMProgressPage extends Progress2 {
/** Return {@link Response} for finished job. */
@Override protected Response jobDone(final Job job, final String dst) {
JsonObject args = new JsonObject();
args.addProperty("model_key", job.dest().toString());
return GBMModelView.redirect(this, job.dest());
}
public static Response redirect(Request req, Key jobkey, Key dest) {
return new Response(Response.Status.redirect, req, -1, -1, "GBMProgressPage", "job", jobkey, "dst_key", dest);
}
@Override public boolean toHTML(StringBuilder sb) {
Job jjob = Job.findJob(Key.make(job.value()));
Value value = DKV.get(jjob.dest());
GBMModel m = value != null ? (GBMModel) value.get() : null;
if( m != null )
m.generateHTML("GBM Model", sb);
else
DocGen.HTML.paragraph(sb, "Pending...");
return true;
}
}
|
Bump version of python library to 0.14.0 | """
CartoDB Services Python Library
See:
https://github.com/CartoDB/geocoder-api
"""
from setuptools import setup, find_packages
setup(
name='cartodb_services',
version='0.14.0',
description='CartoDB Services API Python Library',
url='https://github.com/CartoDB/dataservices-api',
author='Data Services Team - CartoDB',
author_email='dataservices@cartodb.com',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Mapping comunity',
'Topic :: Maps :: Mapping Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='maps api mapping tools geocoder routing',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'dev': ['unittest'],
'test': ['unittest', 'nose', 'mockredispy', 'mock'],
}
)
| """
CartoDB Services Python Library
See:
https://github.com/CartoDB/geocoder-api
"""
from setuptools import setup, find_packages
setup(
name='cartodb_services',
version='0.13.0',
description='CartoDB Services API Python Library',
url='https://github.com/CartoDB/dataservices-api',
author='Data Services Team - CartoDB',
author_email='dataservices@cartodb.com',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Mapping comunity',
'Topic :: Maps :: Mapping Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='maps api mapping tools geocoder routing',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'dev': ['unittest'],
'test': ['unittest', 'nose', 'mockredispy', 'mock'],
}
)
|
Create a speaker profile for each user that is registered. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import post_save
from django.dispatch.dispatcher import receiver
class Speaker(models.Model):
"""
The speaker model acts as user-abstraction for various session and proposal
related objects.
"""
user = models.OneToOneField(User, related_name='speaker_profile')
def __unicode__(self):
if self.user.first_name and self.user.last_name:
return u"{0} {1}".format(self.user.first_name, self.user.last_name)
return self.user.username
def get_absolute_url(self):
return reverse('account_profile', kwargs={'uid': self.user.id})
@receiver(post_save, sender=User)
def create_speaker_profile(sender, instance, created, raw, **kwargs):
"""
Every user also is a potential speaker in the current implemention so we
also have to create a new speaker object for every newly created user
instance.
"""
if created:
Speaker(user=instance).save()
| from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class Speaker(models.Model):
"""
The speaker model acts as user-abstraction for various session and proposal
related objects.
"""
user = models.OneToOneField(User, related_name='speaker_profile')
def __unicode__(self):
if self.user.first_name and self.user.last_name:
return u"{0} {1}".format(self.user.first_name, self.user.last_name)
return self.user.username
def get_absolute_url(self):
return reverse('account_profile', kwargs={'uid': self.user.id})
def create_speaker_profile(sender, instance, created, raw, **kwargs):
"""
Every user also is a potential speaker in the current implemention so we
also have to create a new speaker object for every newly created user
instance.
"""
if created:
Speaker(user=instance).save()
|
Revert "remove the special toString() in order to sync with ESH" | /**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.core.types;
/**
* There are situations when item states do not have any defined value.
* This might be because they have not been initialized yet (never
* received an state update so far) or because their state is ambiguous
* (e.g. a dimmed light that is treated as a switch (ON/OFF) will have
* an undefined state if it is dimmed to 50%).
*
* @author Kai Kreuzer
* @since 0.1.0
*
*/
public enum UnDefType implements PrimitiveType, State {
UNDEF, NULL;
public String toString() {
switch(this) {
case UNDEF: return "Undefined";
case NULL: return "Uninitialized";
}
return "";
}
public String format(String pattern) {
return String.format(pattern, this.toString());
}
}
| /**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.core.types;
/**
* There are situations when item states do not have any defined value.
* This might be because they have not been initialized yet (never
* received an state update so far) or because their state is ambiguous
* (e.g. a dimmed light that is treated as a switch (ON/OFF) will have
* an undefined state if it is dimmed to 50%).
*
* @author Kai Kreuzer
* @since 0.1.0
*
*/
public enum UnDefType implements PrimitiveType, State {
UNDEF, NULL;
public String format(String pattern) {
return String.format(pattern, this.toString());
}
}
|
Fix cached graph out-of-sync when checking. | #!/usr/bin/env python
import sys
from pprint import pprint as pp
from cc.payment import flow
def verify():
for ignore_balances in (True, False):
graph = flow.build_graph(ignore_balances)
cached = flow.get_cached_graph(ignore_balances)
if not cached:
flow.set_cached_graph(graph, ignore_balances)
continue
diff = compare(cached, graph)
if diff:
# Fix problem.
flow.set_cached_graph(graph, ignore_balances)
print "Ignore balances: %s" % ignore_balances
pp(diff)
return False
return True
def compare(g1, g2):
e1 = set(normalize(g1.edges(data=True)))
e2 = set(normalize(g2.edges(data=True)))
return e1.symmetric_difference(e2)
def normalize(edge_list):
return ((src, dest, data['capacity'], data['weight'], data['creditline_id'])
for src, dest, data in edge_list)
if __name__ == '__main__':
if verify():
print 'OK.'
sys.exit(0)
else:
print 'Mismatch.'
sys.exit(1)
| #!/usr/bin/env python
import sys
from pprint import pprint as pp
from cc.payment import flow
def verify():
for ignore_balances in (True, False):
graph = flow.build_graph(ignore_balances)
cached = flow.get_cached_graph(ignore_balances)
if not cached:
flow.set_cached_graph(graph, ignore_balances)
continue
diff = compare(cached, graph)
if diff:
print "Ignore balances: %s" % ignore_balances
pp(diff)
return False
return True
def compare(g1, g2):
e1 = set(normalize(g1.edges(data=True)))
e2 = set(normalize(g2.edges(data=True)))
return e1.symmetric_difference(e2)
def normalize(edge_list):
return ((src, dest, data['capacity'], data['weight'], data['creditline_id'])
for src, dest, data in edge_list)
if __name__ == '__main__':
if verify():
print 'OK.'
sys.exit(0)
else:
print 'Mismatch.'
sys.exit(1)
|
Reduce complexity, hinted by eslint. | function verifyData(data, onError, onSuccess) {
try {
const parsed = JSON.parse(data);
if (!('groups' in parsed)) {
onError(new Error('No groups found in the data'));
return;
}
onSuccess(parsed.groups);
} catch (jsonParseError) {
onError(jsonParseError);
}
}
export default class RawKataData{
constructor(loadRemoteFile, katasUrl){
this.katasUrl = katasUrl;
this.loadRemoteFile = loadRemoteFile;
}
load(onError, onSuccess) {
const onLoaded = (error, data) => {
if (error) {
onError(error);
return;
}
verifyData(data, onError, onSuccess);
};
this.loadRemoteFile(this.katasUrl, onLoaded);
}
}
| export default class RawKataData{
constructor(loadRemoteFile, katasUrl){
this.katasUrl = katasUrl;
this.loadRemoteFile = loadRemoteFile;
}
load(onError, onSuccess) {
const onLoaded = (err, data) => {
var parsed;
try {
parsed = JSON.parse(data);
} catch (jsonParseError) {
onError(jsonParseError);
return;
}
if (err) {
onError(err);
} else if (!('groups' in parsed)) {
onError(new Error('No groups found in the data'));
} else {
onSuccess(parsed.groups);
}
};
this.loadRemoteFile(this.katasUrl, onLoaded);
}
}
|
Add a test for grabbing the standard selector | from nose.tools import assert_true
def test_find_sampling_selector():
from zope.interface import implementedBy
import cc.license
sampling_selector = cc.license.get_selector('recombo')()
return sampling_selector
def test_find_standard_selector():
from zope.interface import implementedBy
import cc.license
standard_selector = cc.license.get_selector('standard')()
return standard_selector
def test_find_sampling_licenses():
selector = test_find_sampling_selector()
lic = selector.by_code('sampling')
assert_true(not lic.libre)
assert_true(lic.deprecated)
lic = selector.by_code('sampling+')
assert_true(not lic.deprecated)
def test_find_pd():
from zope.interface import implementedBy
import cc.license
pd_selector = cc.license.get_selector('publicdomain')()
pd = pd_selector.by_code('publicdomain')
return pd
def test_pd():
pd = test_find_pd()
assert_true(pd.libre)
assert_true(pd.jurisdiction == 'Your mom')
assert_true(not pd.deprecated)
assert_true(pd.jurisdiction == 'Your mom')
assert_true(pd.license_code == 'publicdomain')
assert_true(pd.name() == 'Public Domain' == pd.name('en'))
assert_true(pd.name('hr') == u'Javna domena')
| from nose.tools import assert_true
def test_find_sampling_selector():
from zope.interface import implementedBy
import cc.license
sampling_selector = cc.license.get_selector('recombo')()
return sampling_selector
def test_find_sampling_licenses():
selector = test_find_sampling_selector()
lic = selector.by_code('sampling')
assert_true(not lic.libre)
assert_true(lic.deprecated)
lic = selector.by_code('sampling+')
assert_true(not lic.deprecated)
def test_find_pd():
from zope.interface import implementedBy
import cc.license
pd_selector = cc.license.get_selector('publicdomain')()
pd = pd_selector.by_code('publicdomain')
return pd
def test_pd():
pd = test_find_pd()
assert_true(pd.libre)
assert_true(pd.jurisdiction == 'Your mom')
assert_true(not pd.deprecated)
assert_true(pd.jurisdiction == 'Your mom')
assert_true(pd.license_code == 'publicdomain')
assert_true(pd.name() == 'Public Domain' == pd.name('en'))
assert_true(pd.name('hr') == u'Javna domena')
|
Add variables and function call for longtouch | import React, { Component } from 'react';
import { TouchableOpacity, Image, View } from 'react-native';
// import styles from './styles/ClickableImageStyle';
import PropTypes from 'prop-types';
import { StackNagivator } from 'react-navigation';
import FadeInView from '../animations/FadeInView';
export default class ClickableImage extends Component {
static propTypes = {
onPress: PropTypes.func,
onLongPress: PropTypes.func,
text: PropTypes.object,
children: PropTypes.object,
navigation: PropTypes.object,
imageStyle: Image.propTypes.style,
touchStyle: View.propTypes.style
}
_onLongPress() {
}
render() {
return (
<View>
<FadeInView>
<TouchableOpacity style={this.props.touchStyle} activeOpacity={.85} onPress={this.props.onPress} onLongPress={this.props.onLongPress}>
<Image style={this.props.imageStyle} source={this.props.text} />
</TouchableOpacity>
</FadeInView>
</View>
)
}
}
| import React, { Component } from 'react';
import { TouchableOpacity, Image, View } from 'react-native';
// import styles from './styles/ClickableImageStyle';
import PropTypes from 'prop-types';
import { StackNagivator } from 'react-navigation';
import FadeInView from '../animations/FadeInView';
export default class ClickableImage extends Component {
static propTypes = {
onPress: PropTypes.func,
text: PropTypes.object,
children: PropTypes.object,
navigation: PropTypes.object,
imageStyle: Image.propTypes.style,
touchStyle: View.propTypes.style
}
render() {
return (
<View>
<FadeInView>
<TouchableOpacity style={this.props.touchStyle} activeOpacity={.85} onPress={this.props.onPress}>
<Image style={this.props.imageStyle} source={this.props.text} />
</TouchableOpacity>
</FadeInView>
</View>
)
}
}
|
Fix unit test as this is overwritten by user's local config | package org.sagebionetworks.dashboard.config;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
public class DwConfigTest {
@Test
public void test() {
DwConfig config = new DwConfig();
assertNotNull(config.getAccessRecordBucket());
assertNotNull(config.getAwsAccessKey());
assertNotNull(config.getAwsSecretKey());
assertNotNull(config.getDwUrl());
assertNotNull(config.getDwUsername());
assertNotNull(config.getDwPassword());
assertNotNull(config.getSynapseUser());
assertNotNull(config.getSynapsePassword());
assertNotNull(config.getBridgeAwsAccessKey());
assertNotNull(config.getBridgeAwsSecretKey());
assertNotNull(config.getBridgeStack());
assertNotNull(config.getBridgeUser());
assertNotNull(config.getBridgeBackupBucket());
assertNotNull(config.getBridgeDynamoTables());
}
}
| package org.sagebionetworks.dashboard.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.sagebionetworks.dashboard.config.DwConfig;
public class DwConfigTest {
@Test
public void test() {
DwConfig config = new DwConfig();
assertNotNull(config.getAccessRecordBucket());
assertNotNull(config.getAwsAccessKey());
assertNotNull(config.getAwsSecretKey());
assertNotNull(config.getDwUrl());
assertNotNull(config.getDwUsername());
assertNotNull(config.getDwPassword());
assertNotNull(config.getSynapseUser());
assertNotNull(config.getSynapsePassword());
assertNotNull(config.getBridgeAwsAccessKey());
assertNotNull(config.getBridgeAwsSecretKey());
assertNotNull(config.getBridgeStack());
assertNotNull(config.getBridgeUser());
assertNotNull(config.getBridgeBackupBucket());
assertNotNull(config.getBridgeDynamoTables());
assertEquals(2, config.getBridgeDynamoTables().size());
assertEquals("TestTable1", config.getBridgeDynamoTables().get(0));
assertEquals("TestTable2", config.getBridgeDynamoTables().get(0));
}
}
|
Improve specs for error event | define(function(require) {
var test = require('../../../test')
var n = 0
// 404
var a = require('./a')
test.assert(a === null, '404 a')
// exec error
setTimeout(function() {
var b = require('./b')
}, 0)
require.async('./c', function(c) {
test.assert(c === null, '404 c')
done()
})
require.async('./e', function(e) {
test.assert(e === null, 'exec error e')
done()
})
seajs.use('./d', function(d) {
test.assert(d === null, '404 d')
done()
})
// 404 css
//require('./f.css')
function done() {
if (++n === 3) {
test.assert(w_errors.length > 0, w_errors.length)
test.assert(s_errors.length === 4, s_errors.length)
test.next()
}
}
})
| define(function(require) {
var test = require('../../../test')
var n = 0
// 404
var a = require('./a')
test.assert(a === null, '404 a')
// exec error
setTimeout(function() {
var b = require('./b')
}, 0)
require.async('./c', function(c) {
test.assert(c === null, '404 c')
done()
})
require.async('./e', function(e) {
test.assert(e === null, 'exec error e')
done()
})
seajs.use('./d', function(d) {
test.assert(d === null, '404 d')
done()
})
// 404 css
//require('./f.css')
function done() {
if (++n === 3) {
test.assert(w_errors.length === 2, w_errors.length)
test.assert(s_errors.length === 4, s_errors.length)
test.next()
}
}
})
|
Call init_notebook_mode only if inside IPython | import plotly.offline as py_offline
### Offline Mode
def run_from_ipython():
try:
__IPYTHON__
return True
except NameError:
return False
def go_offline(connected=False):
if run_from_ipython():
try:
py_offline.init_notebook_mode(connected)
except TypeError:
#For older versions of plotly
py_offline.init_notebook_mode()
py_offline.__PLOTLY_OFFLINE_INITIALIZED=True
def go_online():
py_offline.__PLOTLY_OFFLINE_INITIALIZED=False
def is_offline():
return py_offline.__PLOTLY_OFFLINE_INITIALIZED
def upgrade(url=None):
from .auth import get_config_file
if not url:
if 'http' not in get_config_file()['offline_url']:
raise Exception("No default offline URL set \n"
"Please run cf.set_config_file(offline_url=xx) to set \n"
"the default offline URL.")
else:
url=get_config_file()['offline_url']
py_offline.download_plotlyjs(url)
| import plotly.offline as py_offline
### Offline Mode
def go_offline(connected=False):
try:
py_offline.init_notebook_mode(connected)
except TypeError:
#For older versions of plotly
py_offline.init_notebook_mode()
py_offline.__PLOTLY_OFFLINE_INITIALIZED=True
def go_online():
py_offline.__PLOTLY_OFFLINE_INITIALIZED=False
def is_offline():
return py_offline.__PLOTLY_OFFLINE_INITIALIZED
def upgrade(url=None):
from .auth import get_config_file
if not url:
if 'http' not in get_config_file()['offline_url']:
raise Exception("No default offline URL set \n"
"Please run cf.set_config_file(offline_url=xx) to set \n"
"the default offline URL.")
else:
url=get_config_file()['offline_url']
py_offline.download_plotlyjs(url)
|
ADD path getter for the wrong file path.
Signed-off-by: Richard Lea <5e20e57f18b15612bae274c2aef7dc395ee6b2a1@zoho.com> | <?php
namespace Chigi\Sublime\Exception;
use Chigi\Sublime\Settings\Environment;
/**
* Thrown when a file was not found
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class FileNotFoundException extends FileException {
/**
* Constructor.
*
* @param string $path The path to the file that was not found
*/
public function __construct($path) {
$this->path = $path;
parent::__construct(sprintf('The file "%s" does not exist', $path));
}
public function setLine($line) {
$this->line = $line;
}
public function setCode($code) {
$this->code = $code;
}
public function setFile($file) {
$this->file = $file;
}
private $path;
public function getPath() {
return $this->path;
}
}
| <?php
namespace Chigi\Sublime\Exception;
use Chigi\Sublime\Settings\Environment;
/**
* Thrown when a file was not found
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class FileNotFoundException extends FileException {
/**
* Constructor.
*
* @param string $path The path to the file that was not found
*/
public function __construct($path) {
parent::__construct(sprintf('The file "%s" does not exist', $path));
}
public function setLine($line) {
$this->line = $line;
}
public function setCode($code) {
$this->code = $code;
}
public function setFile($file) {
$this->file = $file;
}
}
|
Send ConfirmRegistration mail upon succesful registration | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
// use App\Http\Controllers\Controller;
use App\Mail\ConfirmRegistration;
use App\Currency;
use App\User;
use Hash;
use Mail;
class RegisterController extends Controller {
public function index() {
$currencies = Currency::all();
return view('register', compact('currencies'));
}
public function store(Request $request) {
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|confirmed',
'currency' => 'required|exists:currencies,id'
]);
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->currency_id = $request->currency;
$user->language = 'en';
$user->save();
Mail::to($user->email)->send(new ConfirmRegistration($user));
return redirect('/register');
}
}
| <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
// use App\Http\Controllers\Controller;
use App\Currency;
use App\User;
use Hash;
class RegisterController extends Controller {
public function index() {
$currencies = Currency::all();
return view('register', compact('currencies'));
}
public function store(Request $request) {
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|confirmed',
'currency' => 'required|exists:currencies,id'
]);
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->currency_id = $request->currency;
$user->language = 'en';
$user->save();
return redirect('/register');
}
}
|
Use encode to check geocoder status | var express = require('express');
var geocode = require('./geocode');
var mongoose = require('./mongo');
var otp = require('./otp');
/**
* Expose `router`
*/
var router = module.exports = express.Router();
/**
* Main check
*/
router.all('/', checkGeocoder, checkOTP, function(req, res) {
var checks = {
api: true,
db: mongoose.connection.readyState === 1,
geocoder: !req.geocoder,
logger: 'not implemented',
otp: !req.otp,
worker: 'not implemented'
};
// TODO: implement checks
res.status(200).send(checks);
});
/**
* OTP
*/
router.all('/otp', checkOTP, function(req, res) {
if (!req.otp) {
res.status(204).end();
} else {
res.status(400).send(req.otp);
}
});
/**
* Check Geocoder
*/
function checkGeocoder(req, res, next) {
geocode.encode('1133 15th St NW, Washington, DC', function(err, suggestions) {
req.geocoder = err;
next();
});
}
/**
* Check OTP
*/
function checkOTP(req, res, next) {
otp.get({
url: '/index/routes'
}, function(err, routes) {
req.otp = err;
next();
});
}
| var express = require('express');
var geocode = require('./geocode');
var mongoose = require('./mongo');
var otp = require('./otp');
/**
* Expose `router`
*/
var router = module.exports = express.Router();
/**
* Main check
*/
router.all('/', checkGeocoder, checkOTP, function(req, res) {
var checks = {
api: true,
db: mongoose.connection.readyState === 1,
geocoder: !req.geocoder,
logger: 'not implemented',
otp: !req.otp,
worker: 'not implemented'
};
// TODO: implement checks
res.status(200).send(checks);
});
/**
* OTP
*/
router.all('/otp', checkOTP, function(req, res) {
if (!req.otp) {
res.status(204).end();
} else {
res.status(400).send(req.otp);
}
});
/**
* Check Geocoder
*/
function checkGeocoder(req, res, next) {
geocode.suggest('1133 15th St NW, Washington, DC', function(err, suggestions) {
req.geocoder = err;
next();
});
}
/**
* Check OTP
*/
function checkOTP(req, res, next) {
otp.get({
url: '/index/routes'
}, function(err, routes) {
req.otp = err;
next();
});
}
|
Change requirements to look for abstract (latest) versions. | # coding=utf-8
"""Setup file for distutils / pypi."""
try:
from ez_setup import use_setuptools
use_setuptools()
except ImportError:
pass
from setuptools import setup, find_packages
setup(
name='django-wms-client',
version='0.1.1',
author='Tim Sutton',
author_email='tim@kartoza.com',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
scripts=[],
url='http://pypi.python.org/pypi/django-wms-client/',
license='../LICENSE.txt',
description=(
'An app to let you include browsable OGC WMS '
'maps on your django web site.'),
long_description=open('README.md').read(),
install_requires=[
"Django",
"django-leaflet",
"psycopg2",
"factory-boy",
],
test_suite='wms_client.run_tests.run',
)
| # coding=utf-8
"""Setup file for distutils / pypi."""
try:
from ez_setup import use_setuptools
use_setuptools()
except ImportError:
pass
from setuptools import setup, find_packages
setup(
name='django-wms-client',
version='0.1.1',
author='Tim Sutton',
author_email='tim@kartoza.com',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
scripts=[],
url='http://pypi.python.org/pypi/django-wms-client/',
license='../LICENSE.txt',
description=(
'An app to let you include browsable OGC WMS '
'maps on your django web site.'),
long_description=open('README.md').read(),
install_requires=[
"Django==1.7",
"django-leaflet==0.14.1",
"psycopg2==2.5.4",
"factory-boy==2.4.1",
],
test_suite='wms_client.run_tests.run',
)
|
Change keyword from CAPS to small letter | package seedu.address.logic.parser;
import java.util.regex.Pattern;
import seedu.address.logic.parser.ArgumentTokenizer.Prefix;
/**
* Contains Command Line Interface (CLI) syntax definitions common to multiple commands
*/
public class CliSyntax {
/* Prefix definitions */
public static final Prefix PREFIX_BOOK_DATE = new Prefix("on ");
public static final Prefix PREFIX_BOOK_DATE_DELIMITER = new Prefix(",");
public static final Prefix PREFIX_DEADLINE = new Prefix("by ");
public static final Prefix PREFIX_TIMEINTERVAL_END = new Prefix("to ");
public static final Prefix PREFIX_TIMEINTERVAL_START = new Prefix("from ");
public static final Prefix PREFIX_LABEL = new Prefix("#");
public static final Prefix PREFIX_STATUS_COMPLETED = new Prefix("completed");
public static final Prefix PREFIX_STATUS_INCOMPLETE = new Prefix("incomplete");
/* Patterns definitions */
public static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
}
| package seedu.address.logic.parser;
import java.util.regex.Pattern;
import seedu.address.logic.parser.ArgumentTokenizer.Prefix;
/**
* Contains Command Line Interface (CLI) syntax definitions common to multiple commands
*/
public class CliSyntax {
/* Prefix definitions */
public static final Prefix PREFIX_BOOK_DATE = new Prefix("on ");
public static final Prefix PREFIX_BOOK_DATE_DELIMITER = new Prefix(",");
public static final Prefix PREFIX_DEADLINE = new Prefix("by ");
public static final Prefix PREFIX_TIMEINTERVAL_END = new Prefix("to ");
public static final Prefix PREFIX_TIMEINTERVAL_START = new Prefix("from ");
public static final Prefix PREFIX_LABEL = new Prefix("#");
public static final Prefix PREFIX_STATUS_COMPLETED = new Prefix("COMPLETED");
public static final Prefix PREFIX_STATUS_INCOMPLETE = new Prefix("INCOMPLETE");
/* Patterns definitions */
public static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
}
|
Fix error handling in get_model_field (passthrough). | try:
from django.db.models.constants import LOOKUP_SEP
except ImportError: # Django < 1.5 fallback
from django.db.models.sql.constants import LOOKUP_SEP
from django.db.models.related import RelatedObject
from six import PY3
def python_2_unicode_compatible(klass): # Copied from Django 1.5
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if not PY3:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
def get_model_field(model, f):
parts = f.split(LOOKUP_SEP)
opts = model._meta
for name in parts[:-1]:
rel = opts.get_field_by_name(name)[0]
if isinstance(rel, RelatedObject):
model = rel.model
opts = rel.opts
else:
model = rel.rel.to
opts = model._meta
rel, model, direct, m2m = opts.get_field_by_name(parts[-1])
return rel, m2m
| try:
from django.db.models.constants import LOOKUP_SEP
except ImportError: # Django < 1.5 fallback
from django.db.models.sql.constants import LOOKUP_SEP
from django.db.models.related import RelatedObject
import six
def python_2_unicode_compatible(klass): # Copied from Django 1.5
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if not six.PY3:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
def get_model_field(model, f):
parts = f.split(LOOKUP_SEP)
opts = model._meta
for name in parts[:-1]:
try:
rel = opts.get_field_by_name(name)[0]
except FieldDoesNotExist:
return None
if isinstance(rel, RelatedObject):
model = rel.model
opts = rel.opts
else:
model = rel.rel.to
opts = model._meta
rel, model, direct, m2m = opts.get_field_by_name(parts[-1])
return rel, m2m
|
Mark class with memory intensive static init method as init at runtime | package org.jboss.shamrock.deployment;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.shamrock.runtime.RegisterForReflection;
public class RegisterForReflectionProcessor implements ResourceProcessor {
@Override
public void process(ArchiveContext archiveContext, ProcessorContext processorContext) throws Exception {
for (AnnotationInstance i : archiveContext.getCombinedIndex().getAnnotations(DotName.createSimple(RegisterForReflection.class.getName()))) {
ClassInfo target = i.target().asClass();
boolean methods = i.value("methods") == null || i.value("methods").asBoolean();
boolean fields = i.value("fields") == null || i.value("fields").asBoolean();
processorContext.addReflectiveClass(methods, fields, target.name().toString());
}
//TODO: where should stuff like this go?
//this will hold a heap of memory when it is initialized, and is rarely used (but it generally on the analysis path)
processorContext.addRuntimeInitializedClasses("com.sun.org.apache.xml.internal.serializer.ToHTMLStream");
}
@Override
public int getPriority() {
return 0;
}
}
| package org.jboss.shamrock.deployment;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.shamrock.runtime.RegisterForReflection;
public class RegisterForReflectionProcessor implements ResourceProcessor {
@Override
public void process(ArchiveContext archiveContext, ProcessorContext processorContext) throws Exception {
for (AnnotationInstance i : archiveContext.getCombinedIndex().getAnnotations(DotName.createSimple(RegisterForReflection.class.getName()))) {
ClassInfo target = i.target().asClass();
boolean methods = i.value("methods") == null || i.value("methods").asBoolean();
boolean fields = i.value("fields") == null || i.value("fields").asBoolean();
processorContext.addReflectiveClass(methods, fields, target.name().toString());
}
}
@Override
public int getPriority() {
return 0;
}
}
|
Increase waiting time after two players have joined in the test | /**
* Created by andybb on 18.03.15.
*/
import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;
import com.mygdx.game.controllers.GameNetworkController;
import java.util.concurrent.TimeUnit;
public class NetworkTest {
private GameNetworkController game1;
private GameNetworkController game2;
@Before
public void setup() {
game1 = new GameNetworkController();
game2 = new GameNetworkController();
}
@Test
public void testGameInitialization() throws InterruptedException {
game1.startGame("andybb");
assertEquals("Username for player 1 given and in model should be equal ", "andybb", game1.getPlayerController().getPlayer().getUsername());
TimeUnit.SECONDS.sleep(1);
game2.startGame("mats");
assertEquals("Username for player 2 given and in model should be equal ", "mats", game2.getPlayerController().getPlayer().getUsername());
TimeUnit.SECONDS.sleep(15);
assertEquals("The opponent of player 1 should player 2", "mats", game1.getPlayerController().getOpponent().getUsername());
assertEquals("The opponent of player 2 should player 1", "andybb", game2.getPlayerController().getOpponent().getUsername());
}
@Test
public void testFireOperation() throws InterruptedException{
}
}
| /**
* Created by andybb on 18.03.15.
*/
import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;
import com.mygdx.game.controllers.GameNetworkController;
import java.util.concurrent.TimeUnit;
public class NetworkTest {
private GameNetworkController game1;
private GameNetworkController game2;
@Before
public void setup() {
game1 = new GameNetworkController();
game2 = new GameNetworkController();
}
@Test
public void testGameInitialization() throws InterruptedException {
game1.startGame("andybb");
assertEquals("Username for player 1 given and in model should be equal ", "andybb", game1.getPlayerController().getPlayer().getUsername());
TimeUnit.SECONDS.sleep(1);
game2.startGame("mats");
assertEquals("Username for player 2 given and in model should be equal ", "mats", game2.getPlayerController().getPlayer().getUsername());
TimeUnit.SECONDS.sleep(11);
assertEquals("The opponent of player 1 should player 2", "mats", game1.getPlayerController().getOpponent().getUsername());
assertEquals("The opponent of player 2 should player 1", "andybb", game2.getPlayerController().getOpponent().getUsername());
}
@Test
public void testFireOperation() throws InterruptedException{
}
}
|
Set the account types as choices
Having a domain object that returns all the types
with labels feels weird. I think this is better. | <?php
declare(strict_types=1);
namespace PerFi\PerFiBundle\Form;
use PerFi\Domain\Account\AccountType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
class CreateAccountType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('type', ChoiceType::class, [
'required' => true,
'choices' => [
'Asset' => (string) AccountType::fromString('asset'),
'Expense' => (string) AccountType::fromString('expense'),
'Income' => (string) AccountType::fromString('income'),
],
])
->add('title', TextType::class, [
'required' => true,
]);
}
}
| <?php
declare(strict_types=1);
namespace PerFi\PerFiBundle\Form;
use PerFi\Domain\Account\AccountTypeView;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
class CreateAccountType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('type', ChoiceType::class, [
'required' => true,
'choices' => AccountTypeView::getTypes(),
])
->add('title', TextType::class, [
'required' => true,
]);
}
}
|
Fix leaky requires between zjsunit tests.
Some node tests used to pass as long as prior tests ran,
but then they would fail if you ran them standalone. Now
we are more aggressive about cleaning up node's require
cache after each individual test runs. | var namespace = (function () {
var _ = require('third/underscore/underscore.js');
var exports = {};
var dependencies = [];
var requires = [];
var old_builtins = {};
exports.set_global = function (name, val) {
global[name] = val;
dependencies.push(name);
return val;
};
exports.patch_builtin = function (name, val) {
old_builtins[name] = global[name];
global[name] = val;
return val;
};
exports.add_dependencies = function (dct) {
_.each(dct, function (fn, name) {
var obj = require(fn);
requires.push(fn);
set_global(name, obj);
});
};
exports.restore = function () {
dependencies.forEach(function (name) {
delete global[name];
});
requires.forEach(function (fn) {
delete require.cache[require.resolve(fn)];
});
dependencies = [];
_.extend(global, old_builtins);
old_builtins = {};
};
return exports;
}());
module.exports = namespace;
| var namespace = (function () {
var _ = require('third/underscore/underscore.js');
var exports = {};
var dependencies = [];
var old_builtins = {};
exports.set_global = function (name, val) {
global[name] = val;
dependencies.push(name);
return val;
};
exports.patch_builtin = function (name, val) {
old_builtins[name] = global[name];
global[name] = val;
return val;
};
exports.add_dependencies = function (dct) {
_.each(dct, function (fn, name) {
var obj = require(fn);
set_global(name, obj);
});
};
exports.restore = function () {
dependencies.forEach(function (name) {
delete global[name];
});
dependencies = [];
_.extend(global, old_builtins);
old_builtins = {};
};
return exports;
}());
module.exports = namespace;
|
Prepare for 0.9.5 on pypi | from setuptools import setup
setup(
name='livescrape',
version='0.9.5',
url='https://github.com/ondergetekende/python-livescrape',
description='A toolkit to build pythonic web scraper libraries',
author='Koert van der Veer',
author_email='koert@ondergetekende.nl',
py_modules=["livescrape"],
install_requires=["lxml", "requests", "cssselect", "six"],
classifiers=[
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 2.7',
],
)
| from setuptools import setup
setup(
name='livescrape',
version='0.9.4',
url='https://github.com/ondergetekende/python-livescrape',
description='A toolkit to build pythonic web scraper libraries',
author='Koert van der Veer',
author_email='koert@ondergetekende.nl',
py_modules=["livescrape"],
install_requires=["lxml", "requests", "cssselect", "six"],
classifiers=[
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 2.7',
],
)
|
Initialize parent_pid in the Proc class init. | import logging
import os
import signal
from setproctitle import setproctitle
class Proc(object):
signal_map = {}
def __init__(self):
self.logger = logging.getLogger(self.__module__)
self.pid = None
self.parent_pid = None
@property
def name(self):
return self.__class__.__name__.lower()
def setup(self):
self.pid = os.getpid()
self.parent_pid = os.getppid()
self.setup_signals()
setproctitle("rotterdam: %s" % self.name)
def run(self):
self.setup()
self.logger.info("Starting %s (%d)", self.name, int(self.pid))
def setup_signals(self):
for signal_name, handler_name in self.signal_map.iteritems():
signal.signal(
getattr(signal, "SIG%s" % signal_name.upper()),
getattr(self, handler_name)
)
| import logging
import os
import signal
from setproctitle import setproctitle
class Proc(object):
signal_map = {}
def __init__(self):
self.logger = logging.getLogger(self.__module__)
self.pid = None
@property
def name(self):
return self.__class__.__name__.lower()
def setup(self):
self.pid = os.getpid()
self.parent_pid = os.getppid()
self.setup_signals()
setproctitle("rotterdam: %s" % self.name)
def run(self):
self.setup()
self.logger.info("Starting %s (%d)", self.name, int(self.pid))
def setup_signals(self):
for signal_name, handler_name in self.signal_map.iteritems():
signal.signal(
getattr(signal, "SIG%s" % signal_name.upper()),
getattr(self, handler_name)
)
|
Fix typo in BackdropUser admin model | from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
from stagecraft.apps.datasets.models.data_set import DataSet
class DataSetInline(admin.StackedInline):
model = DataSet
fields = ('name',)
extra = 0
class BackdropUserAdmin(reversion.VersionAdmin):
search_fields = ['email']
list_display = ('email', 'number_of_datasets_user_has_access_to',)
list_per_page = 30
filter_horizontal = ('data_sets',)
def queryset(self, request):
return BackdropUser.objects.annotate(
dataset_count=models.Count('data_sets')
)
def number_of_datasets_user_has_access_to(self, obj):
return obj.dataset_count
number_of_datasets_user_has_access_to.admin_order_field = 'dataset_count'
admin.site.register(BackdropUser, BackdropUserAdmin)
| from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
from stagecraft.apps.datasets.models.data_set import DataSet
class DataSetInline(admin.StackedInline):
model = DataSet
fields = ('name',)
extra = 0
class BackdropUserAdmin(reversion.VersionAdmin):
search_fields = ['email']
list_display = ('email', 'numer_of_datasets_user_has_access_to',)
list_per_page = 30
filter_horizontal = ('data_sets',)
def queryset(self, request):
return BackdropUser.objects.annotate(
dataset_count=models.Count('data_sets')
)
def numer_of_datasets_user_has_access_to(self, obj):
return obj.dataset_count
numer_of_datasets_user_has_access_to.admin_order_field = 'dataset_count'
admin.site.register(BackdropUser, BackdropUserAdmin)
|
Fix a broken constants.js import
The import of `constants` in NewDiskDialog/actions.js was changed
to use the App level constants in error. The disk create option still
works but redux reports an error on the browser console. Fixed the
import, fixed the error. | // @flow
/* eslint-disable flowtype/require-return-type */
import {
CLEAN_NEW_DISK_DIALOG_SUBTREE,
SET_NEW_DISK_DIALOG_PROGRESS_INDICATOR,
SET_NEW_DISK_DIALOG_ERROR_TEXT,
SET_NEW_DISK_DIALOG_DONE,
} from './constants'
export function cleanNewDiskDialogSubtree () {
return {
type: CLEAN_NEW_DISK_DIALOG_SUBTREE,
}
}
export function setNewDiskDialogProgressIndicator (visible: boolean) {
return {
type: SET_NEW_DISK_DIALOG_PROGRESS_INDICATOR,
payload: { visible },
}
}
export function setNewDiskDialogErrorText (errorText: boolean) {
return {
type: SET_NEW_DISK_DIALOG_ERROR_TEXT,
payload: { errorText },
}
}
export function setNewDiskDialogDone () {
return {
type: SET_NEW_DISK_DIALOG_DONE,
}
}
| // @flow
/* eslint-disable flowtype/require-return-type */
import {
CLEAN_NEW_DISK_DIALOG_SUBTREE,
SET_NEW_DISK_DIALOG_PROGRESS_INDICATOR,
SET_NEW_DISK_DIALOG_ERROR_TEXT,
SET_NEW_DISK_DIALOG_DONE,
} from '_/constants'
export function cleanNewDiskDialogSubtree () {
return {
type: CLEAN_NEW_DISK_DIALOG_SUBTREE,
}
}
export function setNewDiskDialogProgressIndicator (visible: boolean) {
return {
type: SET_NEW_DISK_DIALOG_PROGRESS_INDICATOR,
payload: { visible },
}
}
export function setNewDiskDialogErrorText (errorText: boolean) {
return {
type: SET_NEW_DISK_DIALOG_ERROR_TEXT,
payload: { errorText },
}
}
export function setNewDiskDialogDone () {
return {
type: SET_NEW_DISK_DIALOG_DONE,
}
}
|
Fix bug with the collection validation. | <?php declare(strict_types=1);
namespace Thepixeldeveloper\Sitemap;
use Thepixeldeveloper\Sitemap\Interfaces\VisitorInterface;
abstract class Collection implements VisitorInterface
{
/**
* @var VisitorInterface[]
*/
private $items;
public function add(VisitorInterface $value)
{
$type = $this->type();
if ($value instanceof $type) {
$this->items[] = $value;
} else {
throw new \InvalidArgumentException('$value needs to be an instance of ' . $type);
}
}
/**
* @return VisitorInterface[]
*/
public function all(): array
{
return $this->items;
}
abstract public function type(): string;
}
| <?php declare(strict_types=1);
namespace Thepixeldeveloper\Sitemap;
use Thepixeldeveloper\Sitemap\Interfaces\VisitorInterface;
abstract class Collection implements VisitorInterface
{
/**
* @var VisitorInterface[]
*/
private $items;
public function add(VisitorInterface $value)
{
$type = $this->type();
if ($value instanceof $type) {
$this->items[] = $value;
}
throw new \InvalidArgumentException('$value needs to be an instance of ' . $type);
}
/**
* @return VisitorInterface[]
*/
public function all(): array
{
return $this->items;
}
abstract public function type(): string;
}
|
Solve deprecation warning from Traitlets | from unittest.mock import Mock
from jupyterhub import orm
from remoteappmanager.services.reverse_proxy import ReverseProxy
from tornado import gen, testing
class TestReverseProxy(testing.AsyncTestCase):
@testing.gen_test
def test_reverse_proxy_operations(self):
coroutine_out = None
@gen.coroutine
def mock_api_request(self, *args, **kwargs):
nonlocal coroutine_out
yield gen.sleep(0.1)
coroutine_out = dict(args=args, kwargs=kwargs)
reverse_proxy = ReverseProxy(
endpoint_url="http://fake/api",
auth_token="token")
reverse_proxy._reverse_proxy = Mock(spec=orm.Proxy)
reverse_proxy._reverse_proxy.api_request = mock_api_request
yield reverse_proxy.register("/hello/from/me/",
"http://localhost:12312/")
self.assertEqual(coroutine_out["kwargs"]["method"], "POST")
yield reverse_proxy.unregister("/hello/from/me/")
self.assertEqual(coroutine_out["kwargs"]["method"], "DELETE")
| from unittest.mock import Mock
from jupyterhub import orm
from remoteappmanager.services.reverse_proxy import ReverseProxy
from tornado import gen, testing
class TestReverseProxy(testing.AsyncTestCase):
@testing.gen_test
def test_reverse_proxy_operations(self):
coroutine_out = None
@gen.coroutine
def mock_api_request(self, *args, **kwargs):
nonlocal coroutine_out
yield gen.sleep(0.1)
coroutine_out = dict(args=args, kwargs=kwargs)
reverse_proxy = ReverseProxy("http://fake/api", "token")
reverse_proxy._reverse_proxy = Mock(spec=orm.Proxy)
reverse_proxy._reverse_proxy.api_request = mock_api_request
yield reverse_proxy.register("/hello/from/me/",
"http://localhost:12312/")
self.assertEqual(coroutine_out["kwargs"]["method"], "POST")
yield reverse_proxy.unregister("/hello/from/me/")
self.assertEqual(coroutine_out["kwargs"]["method"], "DELETE")
|
Bring back commented lines of code. | var Model;
module("Ember.RecordArray", {
setup: function() {
Model = Ember.Model.extend({
id: Ember.attr(),
name: Ember.attr()
});
Model.adapter = Ember.FixtureAdapter.create();
Model.FIXTURES = [
{id: 1, name: 'Erik'},
{id: 2, name: 'Stefan'},
{id: 3, name: 'Kris'}
];
},
teardown: function() { }
});
// test("must be created with a modelClass property", function() {
// throws(function() {
// Ember.RecordArray.create();
// }, /RecordArrays must be created with a modelClass/);
// });
test("when called with findMany, should contain an array of the IDs contained in the RecordArray", function() {
var records = Ember.run(Model, Model.find, [1,2,3]);
deepEqual(records.get('_ids'), [1,2,3]);
equal(records.get('length'), 0);
ok(!records.get('isLoaded'));
stop();
Ember.run(records, records.then, function() {
start();
equal(records.get('length'), 3);
});
}); | var Model;
module("Ember.RecordArray", {
setup: function() {
Model = Ember.Model.extend({
id: Ember.attr(),
name: Ember.attr()
});
Model.adapter = Ember.FixtureAdapter.create();
Model.FIXTURES = [
{id: 1, name: 'Erik'},
{id: 2, name: 'Stefan'},
{id: 3, name: 'Kris'}
];
},
teardown: function() { }
});
test("when called with findMany, should contain an array of the IDs contained in the RecordArray", function() {
var records = Ember.run(Model, Model.find, [1,2,3]);
// test("must be created with a modelClass property", function() {
// throws(function() {
// Ember.RecordArray.create();
// }, /RecordArrays must be created with a modelClass/);
// });
deepEqual(records.get('_ids'), [1,2,3]);
equal(records.get('length'), 0);
ok(!records.get('isLoaded'));
stop();
Ember.run(records, records.then, function() {
start();
equal(records.get('length'), 3);
});
}); |
Use correct method for retrieving country code
also work around bug in CountryCode related to e.g. turkish locales | package com.youcruit.onfido.api.serialization;
import java.lang.reflect.Type;
import java.util.Locale;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.neovisionaries.i18n.CountryCode;
public class CountryCodeTypeAdapter implements JsonSerializer<CountryCode>, JsonDeserializer<CountryCode> {
@Override
public CountryCode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonNull()) {
return null;
}
return CountryCode.getByCode(json.getAsString().toUpperCase(Locale.US));
}
@Override
public JsonElement serialize(CountryCode src, Type typeOfSrc, JsonSerializationContext context) {
return context.serialize(src.getAlpha3());
}
}
| package com.youcruit.onfido.api.serialization;
import java.lang.reflect.Type;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.neovisionaries.i18n.CountryCode;
public class CountryCodeTypeAdapter implements JsonSerializer<CountryCode>, JsonDeserializer<CountryCode> {
@Override
public CountryCode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return CountryCode.valueOf(json.getAsString());
}
@Override
public JsonElement serialize(CountryCode src, Type typeOfSrc, JsonSerializationContext context) {
return context.serialize(src.getAlpha3());
}
}
|
Fix logic error in loading unix config. | // Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Build constraints copied from go's src/os/dir_unix.go
// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
package settings
import (
"os/user"
"path/filepath"
)
var defaultConfigPaths = []string{
// This will be prepended by $HOME/.config/gobuster.conf
"/etc/gobuster.conf",
}
func init() {
if usr, err := user.Current(); err == nil {
path := filepath.Join(usr.HomeDir, ".config", "gobuster.conf")
defaultConfigPaths = append([]string{path}, defaultConfigPaths...)
}
}
| // Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Build constraints copied from go's src/os/dir_unix.go
// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
package settings
import (
"os/user"
"path/filepath"
)
var defaultConfigPaths = []string{
// This will be prepended by $HOME/.config/gobuster.conf
"/etc/gobuster.conf",
}
func init() {
if usr, err := user.Current(); err != nil {
path := filepath.Join(usr.HomeDir, ".config", "gobuster.conf")
defaultConfigPaths = append([]string{path}, defaultConfigPaths...)
}
}
|
Fix broken test in php 5.5
Signed-off-by: Fery Wardiyanto <bd7846e81d12676baffd10ffe6daf3939680ab52@gmail.com> | <?php
namespace Projek\Slim\Tests;
use Projek\Slim\Monolog;
use PHPUnit_Framework_TestCase;
use DateTimeZone;
abstract class TestCase extends PHPUnit_Framework_TestCase
{
/**
* @var Projek\Slim\Monolog
*/
protected $logger;
/**
* Slim Application settings
*
* @var array
*/
protected $settings = [
'basename' => 'slim-monolog-app',
'logger' => [
'directory' => '',
'filename' => 'app',
'level' => '',
'handlers' => [],
],
];
public function setUp()
{
$this->settings['logger']['directory'] = __DIR__.'/logs';
$this->logger = new Monolog($this->settings['basename'], $this->settings['logger']);
}
}
| <?php
namespace Projek\Slim\Tests;
use Projek\Slim\Monolog;
use PHPUnit_Framework_TestCase;
use DateTimeZone;
abstract class TestCase extends PHPUnit_Framework_TestCase
{
/**
* @var Projek\Slim\Monolog
*/
protected $logger;
/**
* Slim Application settings
*
* @var array
*/
protected $settings = [
'basename' => 'slim-monolog-app',
'logger' => [
'directory' => __DIR__.'/logs',
'filename' => 'app',
'level' => '',
'handlers' => [],
],
];
public function setUp()
{
$this->logger = new Monolog($this->settings['basename'], $this->settings['logger']);
}
}
|
Make angular work correctly when compressed ... again ... :rage: | 'use strict';
angular.module('calendarApp')
.controller('AppointmentmodalCtrl', ['$scope', '$modalInstance', 'event', 'Config', function ($scope, $modalInstance, event, Config) {
'use strict';
var z = 12;
$scope.config = Config;
$scope.event = event;
$scope.$watch('event.type', function(oldVal, newVal) {
if(oldVal !== newVal) {
//Calculate
alert($scope.event.type.label);
}
});
$scope.finish = function() {
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
function folderCallback(object) {
$modalInstance.close();
}
}]);
| 'use strict';
angular.module('calendarApp')
.controller('AppointmentmodalCtrl', function ($scope, $modalInstance, event, Config) {
'use strict';
var z = 12;
$scope.config = Config;
$scope.event = event;
$scope.$watch('event.type', function(oldVal, newVal) {
if(oldVal !== newVal) {
//Calculate
alert($scope.event.type.label);
}
});
$scope.finish = function() {
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
function folderCallback(object) {
$modalInstance.close();
}
});
|
Switch 'drafted' to 'draft' in projection | Space.eventSourcing.Projection.extend(Donations, 'AppealsProjection', {
collections: {
appeals: 'Donations.Appeals'
},
eventSubscriptions() {
return [{
'Donations.AppealDrafted': this._onAppealDrafted,
'Donations.AppealDraftUpdated': this._onAppealDraftUpdated,
'Donations.AppealMade': this._onAppealMade,
'Donations.AppealUpdated': this._onAppealUpdated
}];
},
_onAppealDrafted(event) {
this.appeals.insert(_.extend({}, this._extractAppealDetails(event), {
_id: event.sourceId.toString(),
organizationId: event.organizationId.toString(),
locationId: event.locationId.toString(),
state: 'draft'
}));
},
_onAppealDraftUpdated(event) {
this.appeals.update(event.sourceId.toString(), {
$set: this._extractAppealDetails(event)
});
},
_onAppealMade(event) {
this.appeals.update(event.sourceId.toString(), { $set: { state: 'open' } });
},
_onAppealUpdated(event) {
this.appeals.update(event.sourceId.toString(), {
$set: { title: event.title, description: event.description }
});
},
_extractAppealDetails(event) {
return {
title: event.title,
requiredQuantity: event.requiredQuantity.value,
description: event.description
};
}
});
| Space.eventSourcing.Projection.extend(Donations, 'AppealsProjection', {
collections: {
appeals: 'Donations.Appeals'
},
eventSubscriptions() {
return [{
'Donations.AppealDrafted': this._onAppealDrafted,
'Donations.AppealDraftUpdated': this._onAppealDraftUpdated,
'Donations.AppealMade': this._onAppealMade,
'Donations.AppealUpdated': this._onAppealUpdated
}];
},
_onAppealDrafted(event) {
this.appeals.insert(_.extend({}, this._extractAppealDetails(event), {
_id: event.sourceId.toString(),
organizationId: event.organizationId.toString(),
locationId: event.locationId.toString(),
state: 'drafted'
}));
},
_onAppealDraftUpdated(event) {
this.appeals.update(event.sourceId.toString(), {
$set: this._extractAppealDetails(event)
});
},
_onAppealMade(event) {
this.appeals.update(event.sourceId.toString(), { $set: { state: 'open' } });
},
_onAppealUpdated(event) {
this.appeals.update(event.sourceId.toString(), {
$set: { title: event.title, description: event.description }
});
},
_extractAppealDetails(event) {
return {
title: event.title,
requiredQuantity: event.requiredQuantity.value,
description: event.description
};
}
});
|
Add exception for Logic Errors | # Copyright 2014 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Various exceptions that can be raised by the CI project."""
class ArgusError(Exception):
pass
class ArgusTimeoutError(ArgusError):
pass
class ArgusCLIError(ArgusError):
pass
class ArgusPermissionDenied(ArgusError):
pass
class ArgusHeatTeardown(ArgusError):
pass
class ArgusEnvironmentError(ArgusError):
"""Base class for errors related to the argus environment."""
pass
class ErrorArgusInvalidDecorator(ArgusError):
"""The `skip_on_os` decorator was used improperly."""
pass
| # Copyright 2014 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Various exceptions that can be raised by the CI project."""
class ArgusError(Exception):
pass
class ArgusTimeoutError(ArgusError):
pass
class ArgusCLIError(ArgusError):
pass
class ArgusPermissionDenied(ArgusError):
pass
class ArgusHeatTeardown(ArgusError):
pass
class ArgusEnvironmentError(ArgusError):
"""Base class for errors related to the argus environment."""
pass
|
Add simple context push test | # -*- coding: utf-8 -*-
import unittest
import stencil
from stencil import Token
class ModuleTestCase(unittest.TestCase):
"""Test cases for the stencil module."""
@staticmethod
def test_tokenise():
"""Test stencil.tokenise() function."""
it_token = stencil.tokenise('abc {{ x }} xyz')
token = next(it_token)
assert isinstance(token, Token)
assert token.type == 'text'
assert token.content == 'abc '
token = next(it_token)
assert isinstance(token, Token)
assert token.type == 'var'
assert token.content == 'x'
token = next(it_token)
assert isinstance(token, Token)
assert token.type == 'text'
assert token.content == ' xyz'
class ContextTestCase(unittest.TestCase):
def test_push(self):
ctx = stencil.Context({'a': 1})
self.assertEqual(ctx['a'], 1)
self.assertIsNone(ctx['None'])
with ctx.push(a=2):
self.assertEqual(ctx['a'], 2)
self.assertEqual(ctx['a'], 1)
| # -*- coding: utf-8 -*-
import unittest
import stencil
from stencil import Token
class ModuleTestCase(unittest.TestCase):
"""Test cases for the stencil module."""
@staticmethod
def test_tokenise():
"""Test stencil.tokenise() function."""
it_token = stencil.tokenise('abc {{ x }} xyz')
token = next(it_token)
assert isinstance(token, Token)
assert token.type == 'text'
assert token.content == 'abc '
token = next(it_token)
assert isinstance(token, Token)
assert token.type == 'var'
assert token.content == 'x'
token = next(it_token)
assert isinstance(token, Token)
assert token.type == 'text'
assert token.content == ' xyz'
|
FIX: Remove g and m flags from autolink regex | /**
This addition handles auto linking of text. When included, it will parse out links and create
a hrefs for them.
**/
var urlReplacerArgs = {
matcher: /^((?:https?:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.])(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\([^\s()<>]+\)|[^`!()\[\]{};:'".,<>?«»“”‘’\s]))/,
spaceOrTagBoundary: true,
emitter: function(matches) {
var url = matches[1],
displayUrl = url;
// Don't autolink a markdown link to something
if (url.match(/\]\[\d$/)) { return; }
// If we improperly caught a markdown link abort
if (url.match(/\(http/)) { return; }
if (url.match(/^www/)) { url = "http://" + url; }
return ['a', {href: url}, displayUrl];
}
};
Discourse.Dialect.inlineRegexp(_.merge({start: 'http'}, urlReplacerArgs));
Discourse.Dialect.inlineRegexp(_.merge({start: 'www'}, urlReplacerArgs));
| /**
This addition handles auto linking of text. When included, it will parse out links and create
a hrefs for them.
**/
var urlReplacerArgs = {
matcher: /^((?:https?:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.])(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\([^\s()<>]+\)|[^`!()\[\]{};:'".,<>?«»“”‘’\s]))/gm,
spaceOrTagBoundary: true,
emitter: function(matches) {
var url = matches[1],
displayUrl = url;
// Don't autolink a markdown link to something
if (url.match(/\]\[\d$/)) { return; }
// If we improperly caught a markdown link abort
if (url.match(/\(http/)) { return; }
if (url.match(/^www/)) { url = "http://" + url; }
return ['a', {href: url}, displayUrl];
}
};
Discourse.Dialect.inlineRegexp(_.merge({start: 'http'}, urlReplacerArgs));
Discourse.Dialect.inlineRegexp(_.merge({start: 'www'}, urlReplacerArgs));
|
Update dependency meteor-typescript to v0.9.0 | Package.describe({
name: 'angular-typescript-compiler',
version: '0.3.1_2',
summary: 'Angular TypeScript Compiler Package',
git: 'https://github.com/Urigo/angular-meteor/tree/master/atmosphere-packages/angular-typescript-compiler',
documentation: null
});
Npm.depends({
'meteor-typescript': '0.9.0',
'rollup': '0.41.4',
'rollup-plugin-node-resolve': '3.0.0',
'rollup-plugin-hypothetical': '1.2.1',
'rollup-plugin-commonjs': '8.2.0'
});
Package.onUse(function(api) {
api.versionsFrom('1.6.1');
api.use([
'ecmascript',
'babel-compiler@7.0.0',
'angular-html-compiler@0.3.1_2',
'angular-scss-compiler@0.3.1_2'
], 'server');
api.mainModule('index.js', 'server');
});
| Package.describe({
name: 'angular-typescript-compiler',
version: '0.3.1_2',
summary: 'Angular TypeScript Compiler Package',
git: 'https://github.com/Urigo/angular-meteor/tree/master/atmosphere-packages/angular-typescript-compiler',
documentation: null
});
Npm.depends({
'meteor-typescript': '0.8.10',
'rollup': '0.41.4',
'rollup-plugin-node-resolve': '3.0.0',
'rollup-plugin-hypothetical': '1.2.1',
'rollup-plugin-commonjs': '8.2.0'
});
Package.onUse(function(api) {
api.versionsFrom('1.6.1');
api.use([
'ecmascript',
'babel-compiler@7.0.0',
'angular-html-compiler@0.3.1_2',
'angular-scss-compiler@0.3.1_2'
], 'server');
api.mainModule('index.js', 'server');
});
|
Put protected method after public methods.
svn commit r1579 | <?php
require_once 'Swat/SwatPage.php';
require_once 'XML/RPC2/Server.php';
/**
* Base class for an XML-RPC Server
*
* The XML-RPC server acts as a regular page in an application . This means
* all the regular page security features work for XML-RPC servers.
*
* Swat XML-RPC server pages use the PEAR::XML_RPC2 package to service
* requests.
*
* @package Swat
* @copyright 2005 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
abstract class SwatXMLRPCServer extends SwatPage
{
/**
* Process the request
*
* This method is called by site code to process the page request. It creates
* an XML-RPC server and handles a request. The XML-RPC response from the
* server is output here as well.
*
* @xmlrpc.hidden
*/
public function process()
{
$server = XML_RPC2_Server::create($this);
ob_start();
$server->handleCall();
// TODO: remove workaround when php-5.0.5 is commonplace
$x = ob_get_clean();
$this->layout->response = $x;
}
/*
* @xmlrpc.hidden
*/
public function build()
{
}
protected function createLayout()
{
return new SwatLayout('Swat/layouts/xmlrpcserver.php');
}
}
?>
| <?php
require_once 'Swat/SwatPage.php';
require_once 'XML/RPC2/Server.php';
/**
* Base class for an XML-RPC Server
*
* The XML-RPC server acts as a regular page in an application . This means
* all the regular page security features work for XML-RPC servers.
*
* Swat XML-RPC server pages use the PEAR::XML_RPC2 package to service
* requests.
*
* @package Swat
* @copyright 2005 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
abstract class SwatXMLRPCServer extends SwatPage
{
protected function createLayout()
{
return new SwatLayout('Swat/layouts/xmlrpcserver.php');
}
/**
* Process the request
*
* This method is called by site code to process the page request. It creates
* an XML-RPC server and handles a request. The XML-RPC response from the
* server is output here as well.
*
* @xmlrpc.hidden
*/
public function process()
{
$server = XML_RPC2_Server::create($this);
ob_start();
$server->handleCall();
// TODO: remove workaround when php-5.0.5 is commonplace
$x = ob_get_clean();
$this->layout->response = $x;
}
/*
* @xmlrpc.hidden
*/
public function build()
{
}
}
?>
|
Set explicit polyfill version for tests | /*******************************************************************************
* Copyright 2014, 2020 gwt-ol
*
* 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 ol;
import com.github.desjardins.gwt.junit.client.BaseTestCase;
import java.util.Arrays;
/**
*
* @author Tino Desjardins
*
*/
public abstract class GwtOLBaseTestCase extends BaseTestCase {
public GwtOLBaseTestCase() {
super(Arrays.asList(
"//polyfill.io/v3/polyfill.js?features=Blob,URL,Symbol&flags=always&version=3.46.0",
"//cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.2.0/build/ol.js"),
"ol.GwtOLTest",
10000);
}
}
| /*******************************************************************************
* Copyright 2014, 2020 gwt-ol
*
* 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 ol;
import com.github.desjardins.gwt.junit.client.BaseTestCase;
import java.util.Arrays;
/**
*
* @author Tino Desjardins
*
*/
public abstract class GwtOLBaseTestCase extends BaseTestCase {
public GwtOLBaseTestCase() {
super(Arrays.asList(
"//polyfill.io/v3/polyfill.js?features=Blob,URL,Symbol&flags=always",
"//cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.2.0/build/ol.js"),
"ol.GwtOLTest",
10000);
}
}
|
Append random hex string to campaign tag for uniqueness | /**
* Handles posting one or more new message via POTC.
*/
var async = require('async');
var map = require('lodash.map');
var partial = require('lodash.partial');
var apiHelpers = require('../helpers/api');
var models = require('../../../../models');
var potc = require('../../../services/third-party-apis/potc');
var potcHelpers = require('../helpers/potc');
var resHelpers = require('../helpers/response');
var crypto = require('crypto');
var post = function (req, res) {
var messages = apiHelpers.getModelData(req.body, models.Message);
var potcMessages = map(messages, function(message) {
var tag = req.app.locals.CONFIG.get('CAMPAIGNS.DEFAULT_TAG');
tag += '-' + crypto.randomBytes(16).toString('hex');
return potcHelpers.makePOTCMessage(message, tag);
});
var onComplete = function(err, data) {
if (err)
return res.status(400).json(resHelpers.makeError(err));
var modelData = map(data, function(res) {
return new models.MessageResponse(res);
});
res.json(resHelpers.makeResponse(modelData));
};
async.parallel(map(potcMessages, function(message) {
return function(cb) {
potc.sendMessage(message, req.app.locals.CONFIG, function(err, res) {
res.bioguideId = message['bio_id'];
cb(err, res);
});
};
}), onComplete);
};
module.exports.post = post;
| /**
* Handles posting one or more new message via POTC.
*/
var async = require('async');
var map = require('lodash.map');
var partial = require('lodash.partial');
var apiHelpers = require('../helpers/api');
var models = require('../../../../models');
var potc = require('../../../services/third-party-apis/potc');
var potcHelpers = require('../helpers/potc');
var resHelpers = require('../helpers/response');
var post = function (req, res) {
var messages = apiHelpers.getModelData(req.body, models.Message);
var potcMessages = map(messages, function(message) {
return potcHelpers.makePOTCMessage(message, req.app.locals.CONFIG.get('CAMPAIGNS.DEFAULT_TAG'));
});
var onComplete = function(err, data) {
if (err)
return res.status(400).json(resHelpers.makeError(err));
var modelData = map(data, function(res) {
return new models.MessageResponse(res);
});
res.json(resHelpers.makeResponse(modelData));
};
async.parallel(map(potcMessages, function(message) {
return function(cb) {
potc.sendMessage(message, req.app.locals.CONFIG, function(err, res) {
res.bioguideId = message['bio_id'];
cb(err, res);
});
};
}), onComplete);
};
module.exports.post = post;
|
Test Fenwick Tree: Check error throwing if passed anything but array | /* eslint-env mocha */
const FenwickTree = require('../../src').DataStructures.FenwickTree;
const assert = require('assert');
describe('Fenwick Tree', () => {
it('should be empty when initialized', () => {
const inst = new FenwickTree([]);
assert(inst.isEmpty());
assert.equal(inst.size, 0);
});
it('should build tree with array', () => {
const inst = new FenwickTree(4);
inst.buildTree([1, 2, 3, 4]);
assert(!inst.isEmpty());
assert.equal(inst.size, 4);
});
it('should sum the array till index', () => {
const inst = new FenwickTree(4);
inst.buildTree([1, 2, 3, 4]);
assert.equal(inst.getSum(2), 6);
assert.equal(inst.getSum(0), 1);
assert.equal(inst.getSum(3), 10);
assert.throws(() => inst.getSum(4), Error);
});
it('should throw an error if passed object', () => {
const inst = new FenwickTree(4);
assert.throws(() => inst.buildTree({}), Error);
});
});
| /* eslint-env mocha */
const FenwickTree = require('../../src').DataStructures.FenwickTree;
const assert = require('assert');
describe('Fenwick Tree', () => {
it('should be empty when initialized', () => {
const inst = new FenwickTree([]);
assert(inst.isEmpty());
assert.equal(inst.size, 0);
});
it('should build tree with array', () => {
const inst = new FenwickTree(4);
inst.buildTree([1, 2, 3, 4]);
assert(!inst.isEmpty());
assert.equal(inst.size, 4);
});
it('should sum the array till index', () => {
const inst = new FenwickTree(4);
inst.buildTree([1, 2, 3, 4]);
assert.equal(inst.getSum(2), 6);
assert.equal(inst.getSum(0), 1);
assert.equal(inst.getSum(3), 10);
assert.throws(() => inst.getSum(4), Error);
});
});
|
Remove autoincrement sqlite paramether from model | from tvseries.ext import db
class TVSerie(db.Model):
id = db.Column(db.Integer(),
nullable=False, unique=True,
autoincrement=True, primary_key=True)
name = db.Column(db.String(50), unique=True, nullable=False)
description = db.Column(db.Text, nullable=True)
episodies_number = db.Column(db.Integer, nullable=False, default=1)
author = db.Column(db.String(50), nullable=False)
def __repr__(self):
if self.description:
self.description = "{0}...".format(self.description[0:10])
return ("TVSerie(id={!r}, name={!r}, "
"description={!r}, episodies_number={!r})").format(
self.id, self.name,
self.description,
self.episodies_number)
| from tvseries.ext import db
class TVSerie(db.Model):
__table_args__ = {'sqlite_autoincrement': True}
id = db.Column(db.Integer(),
nullable=False, unique=True,
autoincrement=True, primary_key=True)
name = db.Column(db.String(50), unique=True, nullable=False)
description = db.Column(db.Text, nullable=True)
episodies_number = db.Column(db.Integer, nullable=False, default=1)
author = db.Column(db.String(50), nullable=False)
def __repr__(self):
if self.description:
self.description = "{0}...".format(self.description[0:10])
return ("TVSerie(id={!r}, name={!r}, "
"description={!r}, episodies_number={!r})").format(
self.id, self.name,
self.description,
self.episodies_number)
|
Add tmp directory to deploy exclude list | 'use strict';
var gulp = require('gulp');
var to5 = require('gulp-6to5');
var watch = require('gulp-watch');
var deploy = require('gulp-gh-pages');
var jshint = require('gulp-jshint');
var options = {
cacheDir: './tmp'
};
gulp.task('deploy', ['js:lint', 'js:compile'], function () {
return gulp.src(['./**/*', '!./node_modules/**', '!./tmp/**'])
.pipe(deploy(options));
});
gulp.task('js:compile', function() {
return gulp.src('src/**/*.js')
.pipe(to5())
.pipe(gulp.dest('dist'));
});
gulp.task('js:lint', function() {
return gulp.src('./src/**/*.js')
.pipe(jshint({ esnext: true }))
.pipe(jshint.reporter('default'));
});
gulp.task('default', function () {
watch('./src/**/*.js', function () {
gulp.start('js:lint');
gulp.start('js:compile');
});
});
| 'use strict';
var gulp = require('gulp');
var to5 = require('gulp-6to5');
var watch = require('gulp-watch');
var deploy = require('gulp-gh-pages');
var jshint = require('gulp-jshint');
var options = {
cacheDir: './tmp'
};
gulp.task('deploy', ['js:lint', 'js:compile'], function () {
return gulp.src(['./**/*', '!./node_modules/**'])
.pipe(deploy(options));
});
gulp.task('js:compile', function() {
return gulp.src('src/**/*.js')
.pipe(to5())
.pipe(gulp.dest('dist'));
});
gulp.task('js:lint', function() {
return gulp.src('./src/**/*.js')
.pipe(jshint({ esnext: true }))
.pipe(jshint.reporter('default'));
});
gulp.task('default', function () {
watch('./src/**/*.js', function () {
gulp.start('js:lint');
gulp.start('js:compile');
});
});
|
Add proptype validation to DropDownFilter component | import React from 'react';
import { map } from 'lodash';
import PropTypes from 'prop-types';
class DropdownFilter extends React.Component {
constructor() {
super();
this.change = this.change.bind(this);
}
componentDidMount() {
const type = this.props.options.type;
const defaultValue = this.props.options.default;
this.props.updateFilters({ [type]: defaultValue });
}
change(event) {
const type = this.props.options.type;
this.props.updateFilters({ [type]: event.target.value });
}
render() {
return (
<div className="container__block -third">
<h2 className="heading -delta">{this.props.header}</h2>
<div className="select">
<select onChange={event => this.change(event)}>
{map(this.props.options.values, (option, key) => (
<option value={key} key={key}>{option}</option>
))}
</select>
</div>
</div>
);
}
}
DropdownFilter.propTypes = {
options: PropTypes.shape({
default: PropTypes.string,
type: PropTypes.string,
values: PropTypes.object,
}).isRequired,
updateFilters: PropTypes.func,
header: PropTypes.string.isRequired,
};
DropdownFilter.defaultProps = {
updateFilters: null,
};
export default DropdownFilter;
| import React from 'react';
import { map } from 'lodash';
class DropdownFilter extends React.Component {
constructor() {
super();
this.change = this.change.bind(this);
}
componentDidMount() {
const type = this.props.options.type;
const defaultValue = this.props.options.default;
this.props.updateFilters({ [type]: defaultValue });
}
change(event) {
const type = this.props.options.type;
this.props.updateFilters({ [type]: event.target.value });
}
render() {
return (
<div className="container__block -third">
<h2 className="heading -delta">{this.props.header}</h2>
<div className="select">
<select onChange={(event) => this.change(event)}>
{map(this.props.options.values, (option, key) => (
<option value={key} key={key}>{option}</option>
))}
</select>
</div>
</div>
)
}
}
export default DropdownFilter;
|
Revert "Mardi 4 Juillet, Matin 1: Correction depreciation"
This reverts commit 3f4f94057631c9cbea5f3a0fe4acbe996c1bf409. | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace AppBundle\Service;
/**
* Description of Extrait
*
* @author Human Booster
*/
class ExtraitWithLink {
private $router, $max;
public function __construct(\Symfony\Component\Routing\Router $router, $max) {
$this->router = $router;
$this->max = $max;
}
function get(\AppBundle\Entity\Article $article) {
$texte = strip_tags($article->getContenu());
if (strlen($texte) > $this->max) {
$texte = substr($texte, 0, $this->max);
$texte = substr($texte, 0, strrpos($texte, ' '));
$url = $this->router->generate('blog_detail', ['id' => $article->getId()]);
$texte .= '<a href="' . $url . '">Lire la suite</a>';
}
return $texte;
}
}
| <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace AppBundle\Service;
/**
* Description of Extrait
*
* @author Human Booster
*/
class ExtraitWithLink {
private $router, $max;
public function __construct(\Symfony\Component\Routing\RouterInterface $router, $max) {
$this->router = $router;
$this->max = $max;
}
function get(\AppBundle\Entity\Article $article) {
$texte = strip_tags($article->getContenu());
if (strlen($texte) > $this->max) {
$texte = substr($texte, 0, $this->max);
$texte = substr($texte, 0, strrpos($texte, ' '));
$url = $this->router->generate('blog_detail', ['id' => $article->getId()]);
$texte .= '<a href="' . $url . '">Lire la suite</a>';
}
return $texte;
}
}
|
Format tweaks, complete through present | package com.tinkerpop.etc.github.beans;
/**
* @author Joshua Shinavier (http://fortytwo.net)
*/
public class Payload {
public String action;
public Comment comment;
public Long comment_id;
public String commit;
public String description;
public String head;
public Long issue;
public Long issue_id;
public String master_branch;
public User member;
public Integer number;
public Page[] pages;
public PullRequest pull_request;
public String pusher_type;
public String ref;
public String ref_type;
public Release release;
public Repository repository;
public Object[] shas;
public Integer size;
public Team team;
public String before;
public String after;
public String name;
public String url;
public Long id;
public String desc;
public User target;
public Long membership_id;
}
| package com.tinkerpop.etc.github.beans;
/**
* @author Joshua Shinavier (http://fortytwo.net)
*/
public class Payload {
public String action;
public Comment comment;
public Long comment_id;
public String commit;
public String description;
public String head;
public Long issue;
public Long issue_id;
public String master_branch;
public User member;
public Integer number;
public Page[] pages;
public PullRequest pull_request;
public String pusher_type;
public String ref;
public String ref_type;
public Release release;
public Repository repository;
public Object[] shas;
public Integer size;
public Team team;
public String before;
public String after;
public String name;
public String url;
public Long id;
public String desc;
public User target;
}
|
Make normal WebGL the default renderer |
const os = require('os')
const prefix = 'webjcs:'
class Settings {
constructor (defaults = {}) {
this.defaults = defaults
}
set (key, value) {
window.localStorage.setItem(prefix + key, JSON.stringify(value))
}
setDefault (key) {
const def = this.defaults[key]
this.set(key, def)
return def
}
get (key) {
let item = window.localStorage.getItem(prefix + key)
if (item === null) item = this.defaults[key]
else item = JSON.parse(item)
return item
}
}
module.exports = new Settings({
renderer: 'webgl',
paths: IS_ELECTRON && os.platform() === 'win32' ? ['C:\\Games\\Jazz2\\'] : [],
jj2_exe: IS_ELECTRON && os.platform() === 'win32' ? 'C:\\Games\\Jazz2\\Jazz2+.exe' : '',
jj2_args: IS_ELECTRON ? '-windowed -nolog' + (os.platform() !== 'win32' ? ' -noddrawmemcheck -nocpucheck' : '') : '',
wine_prefix: IS_ELECTRON && os.platform() !== 'win32' && process.env.HOME ? process.env.HOME : ''
})
|
const os = require('os')
const prefix = 'webjcs:'
class Settings {
constructor (defaults = {}) {
this.defaults = defaults
}
set (key, value) {
window.localStorage.setItem(prefix + key, JSON.stringify(value))
}
setDefault (key) {
const def = this.defaults[key]
this.set(key, def)
return def
}
get (key) {
let item = window.localStorage.getItem(prefix + key)
if (item === null) item = this.defaults[key]
else item = JSON.parse(item)
return item
}
}
module.exports = new Settings({
renderer: 'webgl-advanced',
paths: IS_ELECTRON && os.platform() === 'win32' ? ['C:\\Games\\Jazz2\\'] : [],
jj2_exe: IS_ELECTRON && os.platform() === 'win32' ? 'C:\\Games\\Jazz2\\Jazz2+.exe' : '',
jj2_args: IS_ELECTRON ? '-windowed -nolog' + (os.platform() !== 'win32' ? ' -noddrawmemcheck -nocpucheck' : '') : '',
wine_prefix: IS_ELECTRON && os.platform() !== 'win32' && process.env.HOME ? process.env.HOME : ''
})
|
Add response codes to exceptions. | <?php
namespace MeadSteve\Console;
use MeadSteve\Console\Exceptions\ExecutionError;
use MeadSteve\Console\Exceptions\CommandNotFoundError;
class Executor
{
const RESULT_CODE_COMMAND_NOT_FOUND = 127;
/**
* Calls command using exec(). On less than zero response code an
* exception will be thrown.
*
* @param $command
* @return array output of command.
* @throws Exceptions\ExecutionError|Exceptions\CommandNotFoundError
*/
function execute($command) {
$output = array();
$result = null;
// Redirect standard error to stdout so we can do something with
// it.
$command .= " 2>&1";
exec($command, $output, $result);
if ($result !== 0) {
if ($result === self::RESULT_CODE_COMMAND_NOT_FOUND) {
throw new CommandNotFoundError(implode("\t", $output), $result);
}
else {
throw new ExecutionError(implode("\t", $output), $result);
}
}
return $output;
}
} | <?php
namespace MeadSteve\Console;
use MeadSteve\Console\Exceptions\ExecutionError;
use MeadSteve\Console\Exceptions\CommandNotFoundError;
class Executor
{
const RESULT_CODE_COMMAND_NOT_FOUND = 127;
/**
* Calls command using exec(). On less than zero response code an
* exception will be thrown.
*
* @param $command
* @return array output of command.
* @throws Exceptions\ExecutionError|Exceptions\CommandNotFoundError
*/
function execute($command) {
$output = array();
$result = null;
// Redirect standard error to stdout so we can do something with
// it.
$command .= " 2>&1";
exec($command, $output, $result);
if ($result !== 0) {
if ($result === self::RESULT_CODE_COMMAND_NOT_FOUND) {
throw new CommandNotFoundError(implode("\t", $output));
}
else {
throw new ExecutionError(implode("\t", $output));
}
}
return $output;
}
} |
Fix string formatting to work with python 2.6. | from winrm.protocol import Protocol
class Response(object):
"""Response from a remote command execution"""
def __init__(self, args):
self.std_out, self.std_err, self.status_code = args
def __repr__(self):
#TODO put tree dots at the end if out/err was truncated
return '<Response code {0}, out "{1}", err "{2}">'.format(
self.status_code, self.std_out[:20], self.std_err[:20])
class Session(object):
#TODO implement context manager methods
def __init__(self, url, auth):
#TODO convert short urls into well-formed endpoint
username, password = auth
self.protocol = Protocol(url, username=username, password=password)
def run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs
| from winrm.protocol import Protocol
class Response(object):
"""Response from a remote command execution"""
def __init__(self, args):
self.std_out, self.std_err, self.status_code = args
def __repr__(self):
#TODO put tree dots at the end if out/err was truncated
return '<Response code {}, out "{}", err "{}">'.format(
self.status_code, self.std_out[:20], self.std_err[:20])
class Session(object):
#TODO implement context manager methods
def __init__(self, url, auth):
#TODO convert short urls into well-formed endpoint
username, password = auth
self.protocol = Protocol(url, username=username, password=password)
def run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs |
Fix alembic branch due to change in master | """Use proper type and FK for booked_for_id
Revision ID: 3b997c7a4f0c
Revises: 2bb9dc6f5c28
Create Date: 2015-05-06 14:04:14.590496
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3b997c7a4f0c'
down_revision = '2bb9dc6f5c28'
def upgrade():
op.execute('ALTER TABLE roombooking.reservations ALTER COLUMN booked_for_id TYPE int USING booked_for_id::int')
op.create_foreign_key(None,
'reservations', 'users',
['booked_for_id'], ['id'],
source_schema='roombooking', referent_schema='users')
op.create_index(None, 'reservations', ['booked_for_id'], unique=False, schema='roombooking')
def downgrade():
op.drop_index(op.f('ix_reservations_booked_for_id'), table_name='reservations', schema='roombooking')
op.drop_constraint('fk_reservations_booked_for_id_users', 'reservations', schema='roombooking')
op.alter_column('reservations', 'booked_for_id', type_=sa.String, schema='roombooking')
| """Use proper type and FK for booked_for_id
Revision ID: 3b997c7a4f0c
Revises: 2b4b4bce2165
Create Date: 2015-05-06 14:04:14.590496
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3b997c7a4f0c'
down_revision = '2b4b4bce2165'
def upgrade():
op.execute('ALTER TABLE roombooking.reservations ALTER COLUMN booked_for_id TYPE int USING booked_for_id::int')
op.create_foreign_key(None,
'reservations', 'users',
['booked_for_id'], ['id'],
source_schema='roombooking', referent_schema='users')
op.create_index(None, 'reservations', ['booked_for_id'], unique=False, schema='roombooking')
def downgrade():
op.drop_index(op.f('ix_reservations_booked_for_id'), table_name='reservations', schema='roombooking')
op.drop_constraint('fk_reservations_booked_for_id_users', 'reservations', schema='roombooking')
op.alter_column('reservations', 'booked_for_id', type_=sa.String, schema='roombooking')
|
Add index to oai_id column | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddOaiId extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('documents', function (Blueprint $table) {
$table->text('oai_id')->nullable()->unique();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('documents', function (Blueprint $table) {
$table->dropColumn('oai_id');
});
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddOaiId extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('documents', function (Blueprint $table) {
$table->text('oai_id')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('documents', function (Blueprint $table) {
$table->dropColumn('oai_id');
});
}
}
|
Allow plot_mask to take nibabel image | import numpy as np
import nibabel as nib
import matplotlib.pyplot as plt
import seaborn as sns
def plot_mask_distribution(mask_img, hist=False):
"""Plot the distribution of voxel coordinates in a mask image or file.
Parameters
----------
fname : string or nibabel image
path to binary mask file or image object with data and affine
Returns
-------
ax : matplotlib axis object
axis with plot on it
"""
if ax is None:
ax = plt.subplot(111)
if isinstance(mask_img, basestring):
img = nib.load(mask_img)
else:
img = mask_img
mask = img.get_data()
aff = img.get_affine()
vox = np.where(mask)
vox = np.vstack([vox, np.ones(mask.sum())])
coords = np.dot(aff, vox)[:-1]
colors = sns.get_color_list()[:3]
for axis, data, color in zip(["x", "y", "z"], coords, colors):
if hist:
sns.kdeplot(data, hist=True, label=axis, color=color, ax=ax)
else:
sns.kdeplot(data, shade=True, label=axis, color=color, ax=ax)
ax.legend()
return ax
| import os.path as op
import numpy as np
import nibabel as nib
import matplotlib.pyplot as plt
import seaborn as sns
def plot_mask_distribution(fname, ax=None, hist=False):
"""Plot the distribution of voxel coordinates in a mask file.
Parameters
----------
fname : string
path to binary mask file
Returns
-------
ax : matplotlib axis object
axis with plot on it
"""
if ax is None:
ax = plt.subplot(111)
img = nib.load(fname)
mask = img.get_data()
aff = img.get_affine()
vox = np.where(mask)
vox = np.vstack([vox, np.ones(mask.sum())])
coords = np.dot(aff, vox)[:-1]
colors = sns.get_color_list()[:3]
for axis, data, color in zip(["x", "y", "z"], coords, colors):
if hist:
sns.kdeplot(data, hist=True, label=axis, color=color, ax=ax)
else:
sns.kdeplot(data, shade=True, label=axis, color=color, ax=ax)
ax.legend()
ax.set_title(op.basename(fname))
return ax
|
Fix alembic revision after merge master | """text to JSON
Revision ID: 151b2f642877
Revises: ac115763654
Create Date: 2015-06-12 14:40:56.956657
"""
# revision identifiers, used by Alembic.
revision = '151b2f642877'
down_revision = 'ac115763654'
from alembic import op
import sqlalchemy as sa
def upgrade():
query = 'ALTER TABLE project ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
query = 'ALTER TABLE "user" ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
query = 'ALTER TABLE task ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
query = 'ALTER TABLE task_run ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
def downgrade():
query = 'ALTER TABLE project ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
query = 'ALTER TABLE "user" ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
query = 'ALTER TABLE task ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
query = 'ALTER TABLE task_run ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
| """text to JSON
Revision ID: 151b2f642877
Revises: aee7291c81
Create Date: 2015-06-12 14:40:56.956657
"""
# revision identifiers, used by Alembic.
revision = '151b2f642877'
down_revision = 'aee7291c81'
from alembic import op
import sqlalchemy as sa
def upgrade():
query = 'ALTER TABLE project ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
query = 'ALTER TABLE "user" ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
query = 'ALTER TABLE task ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
query = 'ALTER TABLE task_run ALTER COLUMN info TYPE JSON USING info::JSON;'
op.execute(query)
def downgrade():
query = 'ALTER TABLE project ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
query = 'ALTER TABLE "user" ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
query = 'ALTER TABLE task ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
query = 'ALTER TABLE task_run ALTER COLUMN info TYPE TEXT USING info::TEXT;'
op.execute(query)
|
Add united states to the languages | package com.proxerme.library.parameters;
import android.support.annotation.StringDef;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Class containing the the available countries, used for translator groups and industries.
*
* @author Ruben Gees
*/
public class CountryParameter {
public static final String GERMAN = "de";
public static final String ENGLISH = "en";
public static final String UNITED_STATES = "us";
public static final String JAPANESE = "jp";
public static final String MISCELLANEOUS = "misc";
private CountryParameter() {
}
/**
* An annotation representing the available countries.
*/
@StringDef({GERMAN, ENGLISH, UNITED_STATES, JAPANESE, MISCELLANEOUS})
@Retention(value = RetentionPolicy.SOURCE)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface Country {
}
}
| package com.proxerme.library.parameters;
import android.support.annotation.StringDef;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Class containing the the available countries, used for translator groups and industries.
*
* @author Ruben Gees
*/
public class CountryParameter {
public static final String GERMAN = "de";
public static final String ENGLISH = "en";
public static final String JAPANESE = "jp";
public static final String MISCELLANEOUS = "misc";
private CountryParameter() {
}
/**
* An annotation representing the available countries.
*/
@StringDef({GERMAN, ENGLISH, JAPANESE, MISCELLANEOUS})
@Retention(value = RetentionPolicy.SOURCE)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface Country {
}
}
|
Add crud for folder in navigation | <?php
namespace PHPOrchestra\ModelBundle\Document;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\Common\Collections\Collection;
use PHPOrchestra\ModelBundle\Model\MediaFolderInterface;
use PHPOrchestra\ModelBundle\Model\MediaInterface;
/**
* Class MediaFolder
*
* @ODM\Document(
* repositoryClass="PHPOrchestra\ModelBundle\Repository\FolderRepository"
* )
*/
class MediaFolder extends Folder implements MediaFolderInterface
{
/**
* @var Collection
*
* @ODM\ReferenceMany(targetDocument="PHPOrchestra\ModelBundle\Document\Media", mappedBy="folder")
*/
protected $medias;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->medias = new ArrayCollection();
}
/**
* @return Collection
*/
public function getMedias()
{
return $this->medias;
}
/**
* @param MediaInterface $media
*/
public function addMedia(MediaInterface $media)
{
$this->medias->add($media);
$media->setMedialFolder($this);
}
/**
* @param MediaInterface $media
*/
public function removeMedia(MediaInterface $media)
{
$this->medias->removeElement($media);
}
}
| <?php
namespace PHPOrchestra\ModelBundle\Document;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\Common\Collections\Collection;
use PHPOrchestra\ModelBundle\Model\MediaFolderInterface;
use PHPOrchestra\ModelBundle\Model\MediaInterface;
/**
* Class MediaFolder
*
* @ODM\Document(
* repositoryClass="PHPOrchestra\ModelBundle\Repository\FolderRepository"
* )
*/
class MediaFolder extends Folder implements MediaFolderInterface
{
/**
* @var Collection
*
* @ODM\ReferenceMany(targetDocument="PHPOrchestra\ModelBundle\Document\Media", mappedBy="folder")
*/
protected $medias;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->medias = new ArrayCollection();
}
/**
* @return Collection
*/
public function getMedias()
{
return $this->medias;
}
/**
* @param MediaInterface $media
*/
public function addMedia(MediaInterface $media)
{
$this->medias->add($media);
}
/**
* @param MediaInterface $media
*/
public function removeMedia(MediaInterface $media)
{
$this->medias->removeElement($media);
}
}
|
Include a list of files | package gen
type Config struct {
Source string `json:"source"`
Destination string `json:'destination"`
Safe bool `json:"safe"`
Excluede []string `json:"exclude"`
Include []string `json""include"`
KeepFiles string `json:"keep_files"`
TimeZone string `json:"timezone"`
Encoding string `json:"encoding"`
Port int `json:"port"`
Host string `json:"host"`
BaseURL string `json:"base_url"`
}
type System struct {
Boot *Boot `json:"boot"`
Config *Config `json:"config"`
Plan *Plan `json:"plan"`
WorkDir string `json:"work_dir"`
}
type Boot struct {
ConfiFile string `json:"config_file"`
PlanFile string `json:"plan_file"`
ENV map[string]string `json:"env"`
}
type Theme struct {
Name string `json:"name"`
Author []Author `json:"author"`
}
type Author struct {
Name string `json:"name"`
Github string `json:"github"`
Twitter string `json:"twitter"`
Linkedin string `json:"linkedin"`
Email string `json:"email"`
Website string `json:"website"`
}
| package gen
type Config struct {
Source string `json:"source"`
Destination string `json:'destination"`
Safe bool `json:"safe"`
Excluede []string `json:"exclude"`
Include string `json""include"`
KeepFiles string `json:"keep_files"`
TimeZone string `json:"timezone"`
Encoding string `json:"encoding"`
Port int `json:"port"`
Host string `json:"host"`
BaseURL string `json:"base_url"`
}
type System struct {
Boot *Boot `json:"boot"`
Config *Config `json:"config"`
Plan *Plan `json:"plan"`
WorkDir string `json:"work_dir"`
}
type Boot struct {
ConfiFile string `json:"config_file"`
PlanFile string `json:"plan_file"`
ENV map[string]string `json:"env"`
}
type Theme struct {
Name string `json:"name"`
Author []Author `json:"author"`
}
type Author struct {
Name string `json:"name"`
Github string `json:"github"`
Twitter string `json:"twitter"`
Linkedin string `json:"linkedin"`
Email string `json:"email"`
Website string `json:"website"`
}
|
Send proper path to views | var path = require("path"),
Files = require("../modules"),
config = require("../config"),
root_dir = config.root_dir;
// Parse the request path and figure out how to respond
exports.file = function fileRoute (req, res){
var uri = path.normalize(req.path);
if (uri !== req.path)
return res.redirect(uri);
// Figure out what's going on and render accordingly
Files.FileCollector.init(path.normalize(root_dir + req.path))
.on("ready", function (directory) {
return res.render("directory", {
"title": directory.getPath(),
"files": directory.files,
"breadcrumbs": directory.getBreadCrumbs()
});
}).on("single", function (file) {
// Render single file
}).on("notFound", function (directory_or_file) {
var path = directory_or_file.getPath();
return res.status(404).render("404", {
"title": path,
"path": path
});
});
};
| var path = require("path"),
Files = require("../modules"),
config = require("../config"),
root_dir = config.get("root_dir") + '/';
// Parse the request path and figure out how to respond
exports.file = function fileRoute (req, res){
var uri = path.normalize(req.path);
if (uri !== req.path)
return res.redirect(uri);
// Figure out what's going on and render accordingly
Files.FileCollector.init(path.normalize(root_dir + req.path))
.on("ready", function (directory) {
return res.render("directory", {
"title": directory.path,
"files": directory.files,
"breadcrumbs": directory.getBreadCrumbs()
});
}).on("single", function (file) {
// Render single file
}).on("notFound", function (directory_or_file) {
var path = directory_or_file.path;
return res.status(404).render("404", {
"title": path,
"path": path
});
});
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.