text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Replace pseudo-code sketch with accurate comment
|
// Animate: call model update and view render at each animation frame.
//
var tickState = require('./tickState')
var render = require('./view/render')
// To indicate if started.
// Maybe to pause the animation in the future.
var running = false
// number, unix timestamp milliseconds of most recent frame.
var past = null
var animationLoop = function (state) {
var present, dtms
// Time difference from previous frame in milliseconds
present = Date.now()
dtms = (past === null) ? 0 : present - past
past = present
// Update Model
tickState(state, dtms / 1000) // secs
// DEBUG
// console.log('num of particles', state.canvases.reduce(function (acc, c) {
// return c.waves.reduce((ac, w) => {
// return ac + w.particles.length
// }, acc)
// }, 0))
// Draw; View current model
render(state)
// Recursion
// Allow only one viewLoop recursion at a time.
if (running) {
window.requestAnimationFrame(function () {
animationLoop(state)
})
}
}
module.exports = function (state) {
if (!running) {
running = true
animationLoop(state)
}
}
|
// A bit of pseudo-code
//
// tickModel
// var dt
// for each canvas
// canvasParticles = canvasParticles.filterOut(particlesOutsideOrTimeout)
//
// for each particle in canvasParticles
// tick(particle)
//
// for each startOptions
// var newParticles = createParticles(imageUrls, startOptions, dt)
// canvasParticles = [].concat(canvasParticles, newParticles)
//
// tickView
// drawCanvas(canvasId, loadedImages, canvasParticles)
//
var tickState = require('./tickState')
var render = require('./view/render')
// To indicate if started.
// Maybe to pause the animation in the future.
var running = false
// number, unix timestamp milliseconds of most recent frame.
var past = null
var animationLoop = function (state) {
var present, dtms
// Time difference from previous frame in milliseconds
present = Date.now()
dtms = (past === null) ? 0 : present - past
past = present
// Update Model
tickState(state, dtms / 1000) // secs
// DEBUG
// console.log('num of particles', state.canvases.reduce(function (acc, c) {
// return c.waves.reduce((ac, w) => {
// return ac + w.particles.length
// }, acc)
// }, 0))
// Draw; View current model
render(state)
// Recursion
// Allow only one viewLoop recursion at a time.
if (running) {
window.requestAnimationFrame(function () {
animationLoop(state)
})
}
}
module.exports = function (state) {
if (!running) {
running = true
animationLoop(state)
}
}
|
Fix checkstyle issue: File does not end with a newline
|
/*
* Copyright 2015 Benedikt Ritter
*
* 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.github.britter.beanvalidators.strings;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = ISBNConstraintValidator.class)
@Documented
public @interface ISBN {
ISBNType type() default ISBNType.ALL;
String message() default "{com.github.britter.beanvalidators.strings.ISBN.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
|
/*
* Copyright 2015 Benedikt Ritter
*
* 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.github.britter.beanvalidators.strings;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = ISBNConstraintValidator.class)
@Documented
public @interface ISBN {
ISBNType type() default ISBNType.ALL;
String message() default "{com.github.britter.beanvalidators.strings.ISBN.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
|
Make never ending traverser consume less CPU.
Max, please review.
|
// Copyright 2006 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.
package com.google.enterprise.connector.traversal;
/**
* A mock query traverser that runs forever.
*/
public class NeverEndingQueryTraverser implements Traverser {
/* (non-Javadoc)
* @see com.google.enterprise.connector.traversal.Traverser#runBatch(int)
*/
public int runBatch(int batchHint) throws InterruptedException {
boolean breakLoop = true;
// infinite loop
while (breakLoop) {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
// do nothing
}
}
return batchHint;
}
}
|
// Copyright 2006 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.
package com.google.enterprise.connector.traversal;
/**
* A mock query traverser that runs forever.
*/
public class NeverEndingQueryTraverser implements Traverser {
/* (non-Javadoc)
* @see com.google.enterprise.connector.traversal.Traverser#runBatch(int)
*/
public int runBatch(int batchHint) throws InterruptedException {
boolean breakLoop = true;
while (breakLoop) {
// infinite loop
}
return batchHint;
}
}
|
fix(test): Use of StageComponent to ensure aurelia’s framework is loaded as expected.
|
import { Container } from 'aurelia-dependency-injection';
import { StageComponent } from 'aurelia-testing';
import { bootstrap } from 'aurelia-bootstrapper';
import { Config } from '../../src/config';
import { Collection } from '../../src/collection';
import { UseCollection } from '../../src/use-collection';
import { InjectTest } from './resources/inject-test';
describe('UseCollection', () => {
let component;
let container;
let config;
beforeAll(done => {
component = StageComponent.withResources();
component.create(bootstrap)
.then(() => {
container = Container.instance;
config = container.get(Config);
config.registerCollection('fake', 'http://jsonplaceholder.typicode.com');
done();
});
});
afterAll(() => {
component.dispose();
});
describe('static .of()', () => {
it('Should return a new instance of self.', () => {
let resolver = UseCollection.of('foo');
expect(resolver instanceof UseCollection).toBe(true);
expect(resolver._key).toBe('foo');
});
it('Should return a new instance of Collection.', () => {
let injectTest = container.get(InjectTest);
expect(injectTest.myCollection instanceof Collection).toBe(true);
});
});
});
|
import { Config } from '../../src/config';
import { Collection } from '../../src/collection';
import { UseCollection } from '../../src/use-collection';
import { Container } from 'aurelia-dependency-injection';
import { InjectTest } from './resources/inject-test';
let container = new Container();
let config = container.get(Config);
config.registerCollection('fake', 'http://jsonplaceholder.typicode.com');
describe('UseCollection', () => {
describe('static .of()', () => {
it('Should return a new instance of self.', () => {
let resolver = UseCollection.of('foo');
expect(resolver instanceof UseCollection).toBe(true);
expect(resolver._key).toBe('foo');
});
it('Should return a new instance of Collection.', () => {
let injectTest = container.get(InjectTest);
expect(injectTest.myCollection instanceof Collection).toBe(true);
});
});
});
|
Add API number in get_config()
|
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Fri 20 Sep 14:45:01 2013
"""Blitz++ Array bindings for Python"""
import pkg_resources
from ._library import array, as_blitz
from . import version
from .version import module as __version__
from .version import api as __api_version__
def get_include():
"""Returns the directory containing the C/C++ API include directives"""
return pkg_resources.resource_filename(__name__, 'include')
def get_config():
"""Returns a string containing the configuration information.
"""
from .version import externals
packages = pkg_resources.require(__name__)
this = packages[0]
deps = packages[1:]
retval = "%s: %s [api=0x%04x] (%s)\n" % (this.key, this.version,
version.api, this.location)
retval += " - c/c++ dependencies:\n"
for k in sorted(externals): retval += " - %s: %s\n" % (k, externals[k])
retval += " - python dependencies:\n"
for d in deps: retval += " - %s: %s (%s)\n" % (d.key, d.version, d.location)
return retval.strip()
# gets sphinx autodoc done right - don't remove it
__all__ = [_ for _ in dir() if not _.startswith('_')]
|
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Fri 20 Sep 14:45:01 2013
"""Blitz++ Array bindings for Python"""
import pkg_resources
from ._library import array, as_blitz
from . import version
from .version import module as __version__
from .version import api as __api_version__
def get_include():
"""Returns the directory containing the C/C++ API include directives"""
return pkg_resources.resource_filename(__name__, 'include')
def get_config():
"""Returns a string containing the configuration information.
"""
from .version import externals
packages = pkg_resources.require(__name__)
this = packages[0]
deps = packages[1:]
retval = "%s: %s (%s)\n" % (this.key, this.version, this.location)
retval += " - c/c++ dependencies:\n"
for k in sorted(externals): retval += " - %s: %s\n" % (k, externals[k])
retval += " - python dependencies:\n"
for d in deps: retval += " - %s: %s (%s)\n" % (d.key, d.version, d.location)
return retval.strip()
# gets sphinx autodoc done right - don't remove it
__all__ = [_ for _ in dir() if not _.startswith('_')]
|
Upgrade to v0.4.6 of membersuire_api_client
|
#!/usr/bin/env python
from setuptools import setup
import os
# Utility function to read README file
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='iss',
version='2.7.1',
description="Ideally Single Source app for MemberSuite data.",
author='AASHE',
author_email='it@aashe.org',
url='https://github.com/aashe/iss',
long_description=read("README.md"),
packages=[
'iss',
],
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Framework :: Django',
],
install_requires=[
"beatbox==32.1",
"membersuite_api_client==0.4.6",
"pycountry",
"pyYAML==3.12",
]
)
|
#!/usr/bin/env python
from setuptools import setup
import os
# Utility function to read README file
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='iss',
version='2.7.1',
description="Ideally Single Source app for MemberSuite data.",
author='AASHE',
author_email='it@aashe.org',
url='https://github.com/aashe/iss',
long_description=read("README.md"),
packages=[
'iss',
],
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Framework :: Django',
],
install_requires=[
"beatbox==32.1",
"membersuite_api_client==0.4.4",
"pycountry",
"pyYAML==3.12",
]
)
|
Change SubscribeKernelListenerPass position to BEFORE_OPTIMIZATION because original one was moved to BEFORE_REMOVE since Symfony 2.3
|
<?php
/*
* Copyright (c)
* Kirill chEbba Chebunin <iam@chebba.org>
*
* This source file is subject to the MIT license that is bundled
* with this package in the file LICENSE.
*/
namespace EventBand\Bundle;
use EventBand\Bundle\DependencyInjection\Compiler\JmsEventConfigPass;
use EventBand\Bundle\DependencyInjection\Compiler\ReplaceDispatcherPass;
use EventBand\Bundle\DependencyInjection\Compiler\SubscribeKernelListenerPass;
use EventBand\Bundle\DependencyInjection\Compiler\SubscribePass;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* EventBandBundle main bundle class
*
* @author Kirill chEbba Chebunin <iam@chebba.org>
* @license http://opensource.org/licenses/mit-license.php MIT
*/
class EventBandBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
$container->addCompilerPass(new SubscribeKernelListenerPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION); // RegisterKernelListenersPass is registered on "BEFORE_REMOVING" since 2.3
$container->addCompilerPass(new SubscribePass(), PassConfig::TYPE_AFTER_REMOVING);
$container->addCompilerPass(new ReplaceDispatcherPass(), PassConfig::TYPE_BEFORE_REMOVING);
$container->addCompilerPass(new JmsEventConfigPass());
}
}
|
<?php
/*
* Copyright (c)
* Kirill chEbba Chebunin <iam@chebba.org>
*
* This source file is subject to the MIT license that is bundled
* with this package in the file LICENSE.
*/
namespace EventBand\Bundle;
use EventBand\Bundle\DependencyInjection\Compiler\JmsEventConfigPass;
use EventBand\Bundle\DependencyInjection\Compiler\ReplaceDispatcherPass;
use EventBand\Bundle\DependencyInjection\Compiler\SubscribeKernelListenerPass;
use EventBand\Bundle\DependencyInjection\Compiler\SubscribePass;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* EventBandBundle main bundle class
*
* @author Kirill chEbba Chebunin <iam@chebba.org>
* @license http://opensource.org/licenses/mit-license.php MIT
*/
class EventBandBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
$container->addCompilerPass(new SubscribeKernelListenerPass(), PassConfig::TYPE_REMOVE); // RegisterKernelListenersPass is registered on "AFTER_REMOVING"
$container->addCompilerPass(new SubscribePass(), PassConfig::TYPE_AFTER_REMOVING);
$container->addCompilerPass(new ReplaceDispatcherPass(), PassConfig::TYPE_BEFORE_REMOVING);
$container->addCompilerPass(new JmsEventConfigPass());
}
}
|
Add type checking and piping to /dev/null
|
"""A collection of common git actions."""
import os
from subprocess import check_output, PIPE, Popen, STDOUT
def is_valid_reference(reference):
"""Determines if a reference is valid.
:param str reference: name of the reference to validate
:return bool: whether or not the reference is valid
"""
assert isinstance(reference, str), "'reference' must be a str. Given: " + type(reference).__name__
show_ref_proc = Popen(['git', 'show-ref', '--quiet', reference])
show_ref_proc.communicate()
return not show_ref_proc.returncode
def is_commit(object):
"""Determines if an object is a commit.
:param str object: a git object
:return bool: whether or not the object is a commit object
"""
assert isinstance(object, str), "'object' must be a str. Given: " + type(object).__name__
with open(os.devnull, 'w') as dev_null:
cat_file_proc = Popen(['git', 'cat-file', '-t', object], stdout=PIPE, stderr=dev_null)
object_type = cat_file_proc.communicate()[0].strip()
return not cat_file_proc.returncode and object_type == 'commit'
def current_branch():
"""Returns the current branch.
:return str or unicode: the name of the current branch
"""
return check_output(('git', 'rev-parse', '--abbrev-ref', 'HEAD')).strip()
|
"""A collection of common git actions."""
from subprocess import check_output, PIPE, Popen, STDOUT
def is_valid_reference(reference):
"""Determines if a reference is valid.
:param str reference: name of the reference to validate
:return bool: whether or not the reference is valid
"""
show_ref_proc = Popen(['git', 'show-ref', '--quiet', reference])
show_ref_proc.communicate()
return not show_ref_proc.returncode
def is_commit(object):
"""Determines if an object is a commit.
:param object: a git object
:return bool: whether or not the object is a commit object
"""
cat_file_proc = Popen(['git', 'cat-file', '-t', object], stdout=PIPE, stderr=STDOUT)
object_type = cat_file_proc.communicate()[0].strip()
return not cat_file_proc.returncode and object_type == 'commit'
def current_branch():
"""Returns the current branch.
:return str or unicode: the name of the current branch
"""
return check_output(('git', 'rev-parse', '--abbrev-ref', 'HEAD')).strip()
|
Fix bug: api exceptions can occurs with some versions of PHP
|
<?php
namespace Api;
/**
* File API controller
*
* @package api
* @author Frederic Guillot
*/
class File extends Base
{
public function getFile($file_id)
{
return $this->file->getById($file_id);
}
public function getAllFiles($task_id)
{
return $this->file->getAll($task_id);
}
public function downloadFile($file_id)
{
$file = $this->file->getById($file_id);
if (! empty($file)) {
$filename = FILES_DIR.$file['path'];
if (file_exists($filename)) {
return base64_encode(file_get_contents($filename));
}
}
return '';
}
public function createFile($project_id, $task_id, $filename, $is_image, $blob)
{
return $this->file->uploadContent($project_id, $task_id, $filename, $is_image, $blob);
}
public function removeFile($file_id)
{
return $this->file->remove($file_id);
}
}
|
<?php
namespace Api;
/**
* File API controller
*
* @package api
* @author Frederic Guillot
*/
class File extends Base
{
public function getFile($file_id)
{
return $this->file->getById($file_id);
}
public function getAllFiles($task_id)
{
return $this->file->getAll($task_id);
}
public function downloadFile($file_id)
{
$file = $this->file->getById($file_id);
if (! empty($file)) {
$filename = FILES_DIR.$file['path'];
if (file_exists($filename)) {
return base64_encode(file_get_contents($filename));
}
}
return '';
}
public function createFile($project_id, $task_id, $filename, $is_image, &$blob)
{
return $this->file->uploadContent($project_id, $task_id, $filename, $is_image, $blob);
}
public function removeFile($file_id)
{
return $this->file->remove($file_id);
}
}
|
Allow adding workers to the router.
|
<?php
declare(strict_types=1);
namespace Keystone\Queue\Router;
use Keystone\Queue\Envelope;
use Keystone\Queue\Exception\RoutingException;
use Keystone\Queue\Router;
class SimpleRouter implements Router
{
/**
* @var object[]
*/
private $workers;
/**
* @param object[] $workers
*/
public function __construct(array $workers = [])
{
$this->workers = $workers;
}
/**
* @param string $messageName
* @param object $worker
*/
public function add(string $messageName, $worker)
{
$this->workers[$messageName] = $worker;
}
/**
* {@inheritdoc}
*/
public function map(Envelope $envelope)
{
$className = get_class($envelope->getMessage());
if (!array_key_exists($className, $this->workers)) {
throw new RoutingException(sprintf(
'Unable to find worker for message "%s"',
$className
));
}
return $this->workers[$className];
}
}
|
<?php
declare(strict_types=1);
namespace Keystone\Queue\Router;
use Keystone\Queue\Envelope;
use Keystone\Queue\Exception\RoutingException;
use Keystone\Queue\Router;
class SimpleRouter implements Router
{
/**
* @var object[]
*/
private $workers;
/**
* @param object[] $workers
*/
public function __construct(array $workers)
{
$this->workers = $workers;
}
/**
* {@inheritdoc}
*/
public function map(Envelope $envelope)
{
$className = get_class($envelope->getMessage());
if (!array_key_exists($className, $this->workers)) {
throw new RoutingException(sprintf(
'Unable to find worker for message "%s"',
$className
));
}
return $this->workers[$className];
}
}
|
Return same function if length doesn't differ
|
'use strict';
var toUint = require('../number/to-uint')
, test = function (a, b) {}, desc, defineProperty
, generate, mixin;
try {
Object.defineProperty(test, 'length', { configurable: true, writable: false,
enumerable: false, value: 1 });
} catch (ignore) {}
if (test.length === 1) {
// ES6
desc = { configurable: true, writable: false, enumerable: false };
defineProperty = Object.defineProperty;
module.exports = function (fn, length) {
length = toUint(length);
if (fn.length === length) return fn;
desc.value = length;
return defineProperty(fn, 'length', desc);
};
} else {
mixin = require('../object/mixin');
generate = (function () {
var cache = [];
return function (l) {
var args, i = 0;
if (cache[l]) return cache[l];
args = [];
while (l--) args.push('a' + (++i).toString(36));
return new Function('fn', 'return function (' + args.join(', ') +
') { return fn.apply(this, arguments); };');
};
}());
module.exports = function (src, length) {
var target;
length = toUint(length);
if (src.length === length) return src;
target = generate(length)(src);
try { mixin(target, src); } catch (ignore) {}
return target;
};
}
|
'use strict';
var test = function (a, b) {}, desc, defineProperty
, generate, mixin;
try {
Object.defineProperty(test, 'length', { configurable: true, writable: false,
enumerable: false, value: 1 });
} catch (ignore) {}
if (test.length === 1) {
// ES6
desc = { configurable: true, writable: false, enumerable: false };
defineProperty = Object.defineProperty;
module.exports = function (fn, length) {
desc.value = length;
return defineProperty(fn, 'length', desc);
};
} else {
mixin = require('../object/mixin');
generate = (function () {
var cache = [];
return function (l) {
var args, i = 0;
if (cache[l]) return cache[l];
args = [];
while (l--) args.push('a' + (++i).toString(36));
return new Function('fn', 'return function (' + args.join(', ') +
') { return fn.apply(this, arguments); };');
};
}());
module.exports = function (src, length) {
var target = generate(length)(src);
try { mixin(target, src); } catch (ignore) {}
return target;
};
}
|
Set timeout to infinity for init-widgets tag
|
var raptorWidgets = require('../');
module.exports = function render(input, context) {
var widgetsContext = raptorWidgets.getWidgetsContext(context);
if (context.featureLastFlush === false) {
// If the rendering context doesn't support the ability to know when all of the asynchronous fragmnents
// have completed then we won't be able to know which widgets were rendered so we will
// need to scan the DOM to find the widgets
raptorWidgets.writeInitWidgetsCode(widgetsContext, context, {scanDOM: true});
} else {
var asyncContext = context.beginAsync({ last: true, timeout: -1 });
context.on('last', function() {
if (!widgetsContext.hasWidgets()) {
return asyncContext.end();
}
raptorWidgets.writeInitWidgetsCode(widgetsContext, asyncContext);
asyncContext.end();
});
}
};
|
var raptorWidgets = require('../');
module.exports = function render(input, context) {
var widgetsContext = raptorWidgets.getWidgetsContext(context);
if (context.featureLastFlush === false) {
// If the rendering context doesn't support the ability to know when all of the asynchronous fragmnents
// have completed then we won't be able to know which widgets were rendered so we will
// need to scan the DOM to find the widgets
raptorWidgets.writeInitWidgetsCode(widgetsContext, context, {scanDOM: true});
} else {
var asyncContext = context.beginAsync({ last: true });
context.on('last', function() {
if (!widgetsContext.hasWidgets()) {
return asyncContext.end();
}
raptorWidgets.writeInitWidgetsCode(widgetsContext, asyncContext);
asyncContext.end();
});
}
};
|
Fix typo: delayWhileIdle should be delay_while_idle
|
/**
* This module defines all the arguments that may be passed to a message.
*
* Each argument may contain a field `__argName`, if the name of the field
* should be different when sent to the server.
*
* The argument may also contain a field `__argType`, if the given
* argument must be of that type. The types are the strings resulting from
* calling `typeof <arg>` where `<arg>` is the argument.
*
* Other than that, the arguments are expected to follow the indicated
* structure.
*/
module.exports = {
collapseKey: {
__argName: "collapse_key",
__argType: "string"
},
//priority (number),
//content_available (boolean),
delayWhileIdle: {
__argName: "delay_while_idle",
__argType: "boolean"
},
timeToLive: {
__argName: "time_to_live",
__argType: "number"
},
//restricted_package_name (string),
dryRun: {
__argName: "dry_run",
__argType: "boolean"
},
data: {
__argType: "object"
},
notification: {
__argType: "object"
//TODO: There are a lot of very specific arguments that could
// be indicated here.
}
};
|
/**
* This module defines all the arguments that may be passed to a message.
*
* Each argument may contain a field `__argName`, if the name of the field
* should be different when sent to the server.
*
* The argument may also contain a field `__argType`, if the given
* argument must be of that type. The types are the strings resulting from
* calling `typeof <arg>` where `<arg>` is the argument.
*
* Other than that, the arguments are expected to follow the indicated
* structure.
*/
module.exports = {
collapseKey: {
__argName: "collapse_key",
__argType: "string"
},
//priority (number),
//content_available (boolean),
delayWhileIdle: {
__argName: "content_available",
__argType: "boolean"
},
timeToLive: {
__argName: "time_to_live",
__argType: "number"
},
//restricted_package_name (string),
dryRun: {
__argName: "dry_run",
__argType: "boolean"
},
data: {
__argType: "object"
},
notification: {
__argType: "object"
//TODO: There are a lot of very specific arguments that could
// be indicated here.
}
};
|
Add Aspect of the Turtle to Beast Mastery buffs
|
import SPELLS from 'common/SPELLS';
import BLOODLUST_BUFFS from 'game/BLOODLUST_BUFFS';
import CoreBuffs, { BuffDuration } from 'parser/core/modules/Buffs';
class Buffs extends CoreBuffs {
buffs() {
const combatant = this.selectedCombatant;
// Documentation:
return [
{
spell: SPELLS.BESTIAL_WRATH,
duration: BuffDuration.STATIC(15000),
timelineHightlight: true,
},
{
spell: SPELLS.ASPECT_OF_THE_WILD,
duration: BuffDuration.STATIC(20000),
timelineHightlight: true,
},
{
spell: SPELLS.ASPECT_OF_THE_TURTLE,
duration: BuffDuration.STATIC(20000),
timelineHightlight: true, // showing because it's relevant to know when we couldn't attack (this could explain some downtime)
},
{
spell: Object.keys(BLOODLUST_BUFFS).map(spellId => SPELLS[spellId]),
duration: BuffDuration.STATIC(40000),
timelineHightlight: true,
},
];
}
}
export default Buffs;
|
import SPELLS from 'common/SPELLS';
import BLOODLUST_BUFFS from 'game/BLOODLUST_BUFFS';
import CoreBuffs, { BuffDuration } from 'parser/core/modules/Buffs';
class Buffs extends CoreBuffs {
buffs() {
const combatant = this.selectedCombatant;
// Documentation:
return [
{
spell: SPELLS.BESTIAL_WRATH,
duration: BuffDuration.STATIC(15000),
timelineHightlight: true,
},
{
spell: SPELLS.ASPECT_OF_THE_WILD,
duration: BuffDuration.STATIC(20000),
timelineHightlight: true,
},
{
spell: Object.keys(BLOODLUST_BUFFS).map(spellId => SPELLS[spellId]),
duration: BuffDuration.STATIC(40000),
timelineHightlight: true,
},
];
}
}
export default Buffs;
|
Fix bug, need to return server for counting request
|
var pstarter = require('pstarter');
var worker = function() {
var config = require('./config');
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var bootstrap = require('./app/bootstrap.js');
bootstrap.setupApp(app, __dirname);
bootstrap.bootstrap(app);
bootstrap.postrun();
server.listen(config.http.port, config.http.host);
return server;
};
/* run only one single process and worker for debug */
if('worker' in process.env) {
var server = worker();
} else {
pstarter.startMaster(__dirname + '/config', {}, function() {
var config = require('./config');
pstarter.statServer(config.http.statPort, config.http.statHost);
if(process.env['NODE_ENV'] && process.env['NODE_ENV'] === 'development') {
pstarter.startWatch(__dirname, [__dirname + '/node_modules'], ['.js', '.json', '.html', '.css']);
}
}).startWorker(function() {
var server = worker();
/* Counting request */
server.on('request', function(req, res) {
process.send({
cmd : pstarter.cmd.requestCount
});
});
});
}
|
var pstarter = require('pstarter');
var worker = function() {
var config = require('./config');
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var bootstrap = require('./app/bootstrap.js');
bootstrap.setupApp(app, __dirname);
bootstrap.bootstrap(app);
bootstrap.postrun();
server.listen(config.http.port, config.http.host);
};
/* run only one single process and worker for debug */
if('worker' in process.env) {
worker();
} else {
pstarter.startMaster(__dirname + '/config', {}, function() {
var config = require('./config');
pstarter.statServer(config.http.statPort, config.http.statHost);
if(process.env['NODE_ENV'] && process.env['NODE_ENV'] === 'development') {
pstarter.startWatch(__dirname, [__dirname + '/node_modules'], ['.js', '.json', '.html', '.css']);
}
}).startWorker(function() {
worker();
/* Counting request */
server.on('request', function(req, res) {
process.send({
cmd : pstarter.cmd.requestCount
});
});
});
}
|
Fix import Linter from pylam_pylint
|
"""Load extensions."""
import os
import sys
CURDIR = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps'))
LINTERS = {}
try:
from pylama.lint.pylama_mccabe import Linter
LINTERS['mccabe'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pydocstyle import Linter
LINTERS['pep257'] = Linter() # for compatibility
LINTERS['pydocstyle'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pycodestyle import Linter
LINTERS['pycodestyle'] = Linter() # for compability
LINTERS['pep8'] = Linter() # for compability
except ImportError:
pass
try:
from pylama.lint.pylama_pyflakes import Linter
LINTERS['pyflakes'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pylint import Linter
LINTERS['pylint'] = Linter()
except ImportError:
pass
from pkg_resources import iter_entry_points
for entry in iter_entry_points('pylama.linter'):
if entry.name not in LINTERS:
try:
LINTERS[entry.name] = entry.load()()
except ImportError:
pass
# pylama:ignore=E0611
|
"""Load extensions."""
import os
import sys
CURDIR = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps'))
LINTERS = {}
try:
from pylama.lint.pylama_mccabe import Linter
LINTERS['mccabe'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pydocstyle import Linter
LINTERS['pep257'] = Linter() # for compatibility
LINTERS['pydocstyle'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pycodestyle import Linter
LINTERS['pycodestyle'] = Linter() # for compability
LINTERS['pep8'] = Linter() # for compability
except ImportError:
pass
try:
from pylama.lint.pylama_pyflakes import Linter
LINTERS['pyflakes'] = Linter()
except ImportError:
pass
try:
from pylama_pylint import Linter
LINTERS['pylint'] = Linter()
except ImportError:
pass
from pkg_resources import iter_entry_points
for entry in iter_entry_points('pylama.linter'):
if entry.name not in LINTERS:
try:
LINTERS[entry.name] = entry.load()()
except ImportError:
pass
# pylama:ignore=E0611
|
Update the PyPI version to 7.0.11.
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.11',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.10',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Add date to info reported for new links
|
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
LOG = logging.getLogger(__name__)
def update(pinboard_client, items):
for i in items:
if not i.tags:
# Skip anything that isn't tagged.
continue
LOG.info('%s - %s: %s' % (i.time_updated.date(), i.title, i.tags))
LOG.debug('%r', i)
pinboard_client.posts.add(
url=i.url,
description=i.title,
extended=i.excerpt,
tags=u', '.join(i.tags),
date=str(i.time_updated.date()),
)
LOG.debug('')
|
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
LOG = logging.getLogger(__name__)
def update(pinboard_client, items):
for i in items:
if not i.tags:
# Skip anything that isn't tagged.
continue
LOG.info('%s: %s' % (i.title, i.tags))
LOG.debug('%r', i)
pinboard_client.posts.add(
url=i.url,
description=i.title,
extended=i.excerpt,
tags=u', '.join(i.tags),
date=str(i.time_updated.date()),
)
LOG.debug('')
|
Update capture profiler to new spec of providing board instead of string.
|
import cProfile
from pqhelper import capture
def main():
cProfile.run('test_solution(catapult)')
def test_solution(board_string):
board = capture.Board(board_string)
print capture.capture(board)
skeleton = '''
..*..*..
.gm..mg.
.ms..sm.
.rs..sr.
.ggmmgg.
.rsggsr.
.rsrrsr.
ssgssgss'''
giant_rat = '''
...mm...
..mrym..
.mgyrgm.
mygrygym
ryxssxyr
rxgbbgxr
xygssgyx
rybssbyr'''
griffon = '''
.r..s...
.b.sy...
.b.yys..
.r.yxg.g
.g.x*b.r
.g.xxb.r
rybyxygy
ygyxybyr'''
catapult = '''
........
........
..mbgm..
.mxgbrm.
my*gb*gm
yrrxrxxg
ymxyyrmg
ssxssrss'''
easy = '''
........
........
........
........
.......x
....xx.r
....rr.r
..rryyry'''
if __name__ == '__main__':
main()
|
import cProfile
from pqhelper import capture
def main():
cProfile.run('test_solution(catapult)')
def test_solution(board_string):
print capture.capture(board_string)
skeleton = '''
..*..*..
.gm..mg.
.ms..sm.
.rs..sr.
.ggmmgg.
.rsggsr.
.rsrrsr.
ssgssgss'''
giant_rat = '''
...mm...
..mrym..
.mgyrgm.
mygrygym
ryxssxyr
rxgbbgxr
xygssgyx
rybssbyr'''
griffon = '''
.r..s...
.b.sy...
.b.yys..
.r.yxg.g
.g.x*b.r
.g.xxb.r
rybyxygy
ygyxybyr'''
catapult = '''
........
........
..mbgm..
.mxgbrm.
my*gb*gm
yrrxrxxg
ymxyyrmg
ssxssrss'''
easy = '''
........
........
........
........
.......x
....xx.r
....rr.r
..rryyry'''
if __name__ == '__main__':
main()
|
Add exception to method signature, and add additional annotation
|
package uk.ac.ebi.spot.goci.service;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import java.io.IOException;
/**
* Created by emma on 13/04/2016.
*
* @author emma
* <p>
* Create sheet from file, this is then used to read through each row
*/
@Lazy
@Service
public class SheetCreationService {
public XSSFSheet createSheet(String fileName) throws InvalidFormatException, IOException,
InvalidOperationException {
// Open file
OPCPackage pkg = OPCPackage.open(fileName);
XSSFWorkbook current = new XSSFWorkbook(pkg);
pkg.close();
return current.getSheetAt(0);
}
}
|
package uk.ac.ebi.spot.goci.service;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import java.io.IOException;
/**
* Created by emma on 13/04/2016.
*
* @author emma
* <p>
* Create sheet from file, this is then used to read through each row
*/
@Service
public class SheetCreationService {
public XSSFSheet createSheet(String fileName) throws InvalidFormatException, IOException {
// Open file
OPCPackage pkg = OPCPackage.open(fileName);
XSSFWorkbook current = new XSSFWorkbook(pkg);
pkg.close();
return current.getSheetAt(0);
}
}
|
Add failing test for multiple attributes
|
define([ 'janitor' ], function (Janitor) {
describe('janitor', function () {
var janitor;
var config = {
tags: {
p: []
}
};
beforeEach(function () {
janitor = new Janitor(config);
});
it('should clean attributes not in the whitelist', function () {
var p = document.createElement('p');
p.setAttribute('style', 'font-size: 16px;');
p.setAttribute('class', 'example-class');
expect(janitor.clean(p.outerHTML)).toBe('<p></p>');
});
it('should remove elements not in the whitelist', function () {
var div = document.createElement('div');
var p = document.createElement('p');
div.appendChild(p);
expect(janitor.clean(div.outerHTML)).toBe('<p></p>');
});
});
});
|
define([ 'janitor' ], function (Janitor) {
describe('janitor', function () {
var janitor;
var config = {
tags: {
p: []
}
};
beforeEach(function () {
janitor = new Janitor(config);
});
it('should clean attributes not in the whitelist', function () {
var p = document.createElement('p');
p.setAttribute('style', 'font-size: 16px;');
expect(janitor.clean(p.outerHTML)).toBe('<p></p>');
});
it('should remove elements not in the whitelist', function () {
var div = document.createElement('div');
var p = document.createElement('p');
div.appendChild(p);
expect(janitor.clean(div.outerHTML)).toBe('<p></p>');
});
});
});
|
docs: Update site ads on navigation
|
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import useScript from '@charlietango/use-script';
import DocSidebarBase from '@theme-original/DocSidebar';
import styles from './styles.module.css';
const SCRIPT_URL = 'https://media.ethicalads.io/media/client/ethicalads.min.js';
const PUBLISHER_ID = 'react-styleguidist';
function Extra({ path }) {
// Load the EthicalAds script
useScript(SCRIPT_URL);
// Update the ad on navigation
useEffect(() => {
if (window.ethicalads) {
window.ethicalads.load_placements();
}
}, [path]);
return (
<div className={styles.extra}>
<div data-ea-publisher={PUBLISHER_ID} data-ea-type="image" className="bordered"></div>
</div>
);
}
Extra.propTypes = {
path: PropTypes.string.isRequired,
};
function DocSidebar({ showExtra, ...props }) {
return (
<div className={styles.sidebar}>
<DocSidebarBase {...props} />
{showExtra && <Extra path={props.path} />}
</div>
);
}
DocSidebar.propTypes = {
showExtra: PropTypes.bool,
path: PropTypes.string.isRequired,
};
DocSidebar.defaultProps = {
showExtra: true,
};
export default DocSidebar;
|
import React from 'react';
import PropTypes from 'prop-types';
import useScript from '@charlietango/use-script';
import DocSidebarBase from '@theme-original/DocSidebar';
import styles from './styles.module.css';
const SCRIPT_URL = 'https://media.ethicalads.io/media/client/ethicalads.min.js';
const PUBLISHER_ID = 'react-styleguidist';
function Extra() {
useScript(SCRIPT_URL);
return (
<div className={styles.extra}>
<div data-ea-publisher={PUBLISHER_ID} data-ea-type="image" className="bordered"></div>
</div>
);
}
function DocSidebar({ showExtra, ...props }) {
return (
<div className={styles.sidebar}>
<DocSidebarBase {...props} />
{showExtra && <Extra />}
</div>
);
}
DocSidebar.propTypes = {
showExtra: PropTypes.bool,
};
DocSidebar.defaultProps = {
showExtra: true,
};
export default DocSidebar;
|
Change location to reset directory we store output
|
'use strict';
const bodyParser = require('body-parser').json({ limit: '50mb' });
const path = require('path');
const date = require('date-and-time');
const { ensureDirSync, writeJsonSync, emptyDirSync } = require('fs-extra');
let outputDir;
function reportViolations(req, res) {
const REPORT_TIMESTAMP = date.format(new Date(), 'YYYY-MM-DD-HH_mm_ss');
let outputPath = path.resolve(
path.join(outputDir, `${REPORT_TIMESTAMP}.json`)
);
writeJsonSync(outputPath, req.body);
res.send({
outputPath,
});
}
function logError(err, req, res, next) {
console.error(err.stack);
next(err);
}
function setupMiddleware(app, options) {
outputDir = path.join(options.root, 'ember-a11y-report');
ensureDirSync(outputDir);
emptyDirSync(outputDir);
app.post(
'/report-violations',
bodyParser,
(req, res) => {
reportViolations(req, res);
},
logError
);
}
module.exports = setupMiddleware;
|
'use strict';
const bodyParser = require('body-parser').json({ limit: '50mb' });
const path = require('path');
const date = require('date-and-time');
const { ensureDirSync, writeJsonSync, emptyDirSync } = require('fs-extra');
function reportViolations(req, res, options) {
const REPORT_TIMESTAMP = date.format(new Date(), 'YYYY-MM-DD-HH_mm_ss');
let outputDir = path.join(options.root, 'ember-a11y-report');
let outputPath = path.resolve(
path.join(outputDir, `${REPORT_TIMESTAMP}.json`)
);
ensureDirSync(outputDir);
emptyDirSync(outputDir);
writeJsonSync(outputPath, req.body);
res.send({
outputPath,
});
}
function logError(err, req, res, next) {
console.error(err.stack);
next(err);
}
function setupMiddleware(app, options) {
app.post(
'/report-violations',
bodyParser,
(req, res) => {
reportViolations(req, res, options);
},
logError
);
}
module.exports = setupMiddleware;
|
Refactor tests: Extracted the twitter address to a field
|
package org.ale.app;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class TwitterLinkCreatorTest {
private String twitterAddress;
@Before
public void setup(){
twitterAddress = "<a href=\"http://twitter.com/";
}
@Test
public void shouldProcessSingleTwitterName() {
String result = TwitterLinkCreator.process("@foobar");
assertEquals(twitterAddress +"foobar\">@foobar</a>", result);
}
@Test
public void shouldProcessSeveralTwitterNames() {
String result = TwitterLinkCreator.process("@foo, @bar");
assertEquals(twitterAddress +"foo\">@foo</a>, <a href=\"http://twitter.com/"+"bar\">@bar</a>", result);
}
@Test
public void shouldProcessNameWithUnderscore() {
String result = TwitterLinkCreator.process("@foo_bar");
assertEquals(twitterAddress +"foo_bar\">@foo_bar</a>", result);
}
}
|
package org.ale.app;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class TwitterLinkCreatorTest {
@Test
public void shouldProcessSingleTwitterName() {
String result = TwitterLinkCreator.process("@foobar");
assertEquals("<a href=\"http://twitter.com/foobar\">@foobar</a>", result);
}
@Test
public void shouldProcessSeveralTwitterNames() {
String result = TwitterLinkCreator.process("@foo, @bar");
assertEquals("<a href=\"http://twitter.com/foo\">@foo</a>, <a href=\"http://twitter.com/bar\">@bar</a>", result);
}
@Test
public void shouldProcessNameWithUnderscore() {
String result = TwitterLinkCreator.process("@foo_bar");
assertEquals("<a href=\"http://twitter.com/foo_bar\">@foo_bar</a>", result);
}
}
|
Enable prefetching to try it out
|
// This is a second entry point to speed up our query
// to fetch search results.
// We've patched react-scripts to add this as another entry
// point. E.g., the Webpack config by running lives at
// web/node_modules/react-scripts/config/webpack.config.js.
// After modifying files in react-scripts, commit the
// patches with:
// `yarn patch-package react-scripts`
// You can view the patch diff in ./web/patches.
// For this to be meaningful, we have to make sure we inject
// this script first, before all other app code.
// TODO: add tests for env var and other logic
// Return an empty script when building the newtab app.
// The newtab app will still build this entry point because
// we share Webpack configs.
if (process.env.REACT_APP_WHICH_APP === 'search') {
const {
// eslint-disable-next-line no-unused-vars
prefetchSearchResults,
} = require('js/components/Search/fetchBingSearchResults')
const getSearchResults = () => {
var t = performance.now()
// console.log('searchQuery', t)
window.debug.searchQuery = t
// TODO
// If the path is /query, call fetchBingSearchResults.
// Let it handle the logic of determining the search query, etc.
prefetchSearchResults()
}
getSearchResults()
}
|
// This is a second entry point to speed up our query
// to fetch search results.
// We've patched react-scripts to add this as another entry
// point. E.g., the Webpack config by running lives at
// web/node_modules/react-scripts/config/webpack.config.js.
// After modifying files in react-scripts, commit the
// patches with:
// `yarn patch-package react-scripts`
// You can view the patch diff in ./web/patches.
// For this to be meaningful, we have to make sure we inject
// this script first, before all other app code.
// Return an empty script when building the newtab app.
// The newtab app will still build this entry point because
// we share Webpack configs.
if (process.env.REACT_APP_WHICH_APP === 'search') {
const {
// eslint-disable-next-line no-unused-vars
prefetchSearchResults,
} = require('js/components/Search/fetchBingSearchResults')
const getSearchResults = () => {
var t = performance.now()
// console.log('searchQuery', t)
window.debug.searchQuery = t
// TODO
// If the path is /query, call fetchBingSearchResults.
// Let it handle the logic of determining the search query, etc.
// prefetchSearchResults()
}
getSearchResults()
}
|
Make the current request object available in views
|
<?php defined('SYSPATH') OR die('No direct script access.');
/**
*
* @package Boom
* @category Controllers
*/
class Boom_Controller_Page_Html extends Controller_Page
{
/**
*
* @var View
*/
public $template;
public function before()
{
parent::before();
$this->_save_last_url();
$template = $this->page->version()->template;
$this->template = View::factory($template->filename());
// Set some variables which need to be used globally in the views.
View::bind_global('auth', $this->auth);
View::bind_global('editor', $this->editor);
View::bind_global('page', $this->page);
View::bind_global('request', $this->request);
}
public function action_show() {}
public function after()
{
// If we're in the CMS then add the boom editor the the page.
if ($this->auth->logged_in())
{
$content = $this->editor->insert((string) $this->template, $this->page->id);
}
else
{
$content = (string) $this->template;
}
$this->response->body($content);
}
}
|
<?php defined('SYSPATH') OR die('No direct script access.');
/**
*
* @package Boom
* @category Controllers
*/
class Boom_Controller_Page_Html extends Controller_Page
{
/**
*
* @var View
*/
public $template;
public function before()
{
parent::before();
$this->_save_last_url();
$template = $this->page->version()->template;
$this->template = View::factory($template->filename());
// Set some variables which need to be used globally in the views.
View::bind_global('auth', $this->auth);
View::bind_global('editor', $this->editor);
View::bind_global('page', $this->page);
}
public function action_show() {}
public function after()
{
// If we're in the CMS then add the boom editor the the page.
if ($this->auth->logged_in())
{
$content = $this->editor->insert((string) $this->template, $this->page->id);
}
else
{
$content = (string) $this->template;
}
$this->response->body($content);
}
}
|
Set collapsable element's initial state to collapse.
|
angular.module('ui.bootstrapAddOns.collapse',['ui.bootstrap.transition'])
.directive('collapsableelement', function() {
return {
restrict: 'E',
replace: true,
scope: {
name: '='
},
transclude: true,
template: '<div class="collapse" collapse="isCollapse" ng-transclude></div>',
link: function(scope, element, attrs) {
scope.name = {
toggleState: function() {
scope.isCollapse = !scope.isCollapse;
}, showExpanded: function(show) {
scope.isCollapse = !!show;
}
};
scope.name.showExpanded(true);
}
};
});
|
angular.module('ui.bootstrapAddOns.collapse',['ui.bootstrap.transition'])
.directive('collapsableelement', function() {
return {
restrict: 'E',
replace: true,
scope: {
name: '='
},
transclude: true,
template: '<div class="collapse" collapse="isExpand" ng-transclude></div>',
link: function(scope, element, attrs) {
scope.name= {toggleState: function() {
scope.isExpand = !scope.isExpand;
}, showCollapsed: function(show) {
scope.isExpand = !!show;
}
};
}
};
});
|
Update the PyPI version to 7.0.
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.26',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Stop errors if no datasets are defined
|
<?php
require_once("/var/www/secure_settings/class.FlipsideSettings.php");
require_once('Autoload.php');
class DataSetFactory
{
static function get_data_set($set_name)
{
static $instances = array();
if(isset($instances[$set_name]))
{
return $instances[$set_name];
}
if(!isset(FlipsideSettings::$dataset) || !isset(FlipsideSettings::$dataset[$set_name]))
{
throw new Exception('Unknown dataset name '.$set_name);
}
$set_data = FlipsideSettings::$dataset[$set_name];
$class_name = '\\Data\\'.$set_data['type'];
$obj = new $class_name($set_data['params']);
$instances[$set_name] = $obj;
return $obj;
}
}
?>
|
<?php
require_once("/var/www/secure_settings/class.FlipsideSettings.php");
require_once('Autoload.php');
class DataSetFactory
{
static function get_data_set($set_name)
{
static $instances = array();
if(isset($instances[$set_name]))
{
return $instances[$set_name];
}
if(!isset(FlipsideSettings::$dataset[$set_name]))
{
throw new Exception('Unknown dataset name '.$set_name);
}
$set_data = FlipsideSettings::$dataset[$set_name];
$class_name = '\\Data\\'.$set_data['type'];
$obj = new $class_name($set_data['params']);
$instances[$set_name] = $obj;
return $obj;
}
}
?>
|
Fix syntax errors in lambda func
|
var https = require('https');
exports.handler = function(event, context, callback) {
// This token should live as an environmental variable set in the
// build config for Netlify.
var bearerToken = process.env.TWITTER_BEARER_TOKEN;
if (bearerToken == null) {
callback('Could not find required TWITTER_BEARER_TOKEN environmental variable.');
}
var authToken = 'Bearer ' + bearerToken;
var queryString = '?q=chano4mayor%20OR%20chance4mayor%20OR%20chanoformayor%20OR%20chanceformayor';
var options = {
hostname: 'api.twitter.com',
path: '/1.1/search/tweets.json' + queryString,
headers: {
'Authorization': authToken
}
};
https.get(options, function(res) {
res.on('data', function(data) {
callback(null, {
statusCode: 200,
body: data
})
}).on('error', function(err) {
callback(err);
});
});
}
|
var https = require('https');
exports.handler = function(event, context, callback) {
// This token should live as an environmental variable set in the
// build config for Netlify.
var bearerToken = process.env.TWITTER_BEARER_TOKEN;
if (bearerToken == null) {
callback('Could not find required TWITTER_BEARER_TOKEN environmental variable.')
}
var authToken = 'Bearer ' + bearerToken;
var queryString = '?q=chano4mayor%20OR%20chance4mayor%20OR%20chanoformayor%20OR%20chanceformayor';
var options = {
hostname: 'api.twitter.com',
path: '/1.1/search/tweets.json' + queryString,
headers: {
'Authorization': authToken;
}
};
https.get(options, function(res) {
res.on('data', function(data) {
callback(null, {
statusCode: 200,
body: data
})
}).on('error', function(err) {
callback(err);
});
});
}
|
Rename changelog types and headers
|
/*
* Axelor Business Solutions
*
* Copyright (C) 2005-2019 Axelor (<http://axelor.com>).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.axelor.tools.changelog;
public enum EntryType {
FEATURE("Features"),
CHANGE("Changes"),
DEPRECATE("Deprecated"),
REMOVE("Removed"),
FIX("Fixed"),
SECURITY("Security");
private final String value;
private EntryType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
|
/*
* Axelor Business Solutions
*
* Copyright (C) 2005-2019 Axelor (<http://axelor.com>).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.axelor.tools.changelog;
public enum EntryType {
FEATURE("Feature"),
CHANGE("Change"),
DEPRECATED("Deprecated"),
REMOVED("Removed"),
FIXED("Fixed"),
SECURITY("Security");
private final String value;
private EntryType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
|
Add serialization number to agent exception
|
/*
* Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es)
*
* 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 es.bsc.compss.agent;
public class AgentException extends Exception {
/**
* Exceptions Version UID are 2L in all Runtime.
*/
private static final long serialVersionUID = 2L;
public AgentException(String message) {
super(message);
}
public AgentException(Throwable cnfe) {
super(cnfe);
}
public AgentException(String message, Throwable cause) {
super(message, cause);
}
}
|
/*
* Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es)
*
* 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 es.bsc.compss.agent;
public class AgentException extends Exception {
public AgentException(String message) {
super(message);
}
public AgentException(Throwable cnfe) {
super(cnfe);
}
public AgentException(String message, Throwable cause) {
super(message, cause);
}
}
|
Use ID instead of source_blob.version
|
'use strict';
let cli = require('heroku-cli-util');
let columnify = require('columnify');
module.exports = {
topic: 'builds',
needsAuth: true,
needsApp: true,
description: 'list builds',
help: 'List builds for a Heroku app',
run: cli.command(function (context, heroku) {
return heroku.request({
path: `/apps/${context.app}/builds`,
method: 'GET',
headers: {
'Range': 'created_at ..; order=desc;'
},
parseJSON: true
}).then(function (builds) {
var columnData = builds.slice(0, 10).map(function(build) {
return { created_at: build.created_at,
status: build.status,
id: build.id,
user: build.user.email
};
});
// TODO: use `max` directive in query to avoid the slice nonsense
// heroku-client currently breaks if one tries to do this
var columns = columnify(columnData, {
showHeaders: false
});
console.log(columns);
});
})
};
|
'use strict';
let cli = require('heroku-cli-util');
let columnify = require('columnify');
module.exports = {
topic: 'builds',
needsAuth: true,
needsApp: true,
description: 'list builds',
help: 'List builds for a Heroku app',
run: cli.command(function (context, heroku) {
return heroku.request({
path: `/apps/${context.app}/builds`,
method: 'GET',
headers: {
'Range': 'created_at ..; order=desc;'
},
parseJSON: true
}).then(function (builds) {
var columnData = builds.slice(0, 10).map(function(build) {
return { created_at: build.created_at,
status: build.status,
version: build.source_blob.version,
user: build.user.email
};
});
// TODO: use `max` directive in query to avoid the slice nonsense
// heroku-client currently breaks if one tries to do this
var columns = columnify(columnData, {
showHeaders: false
});
console.log(columns);
});
})
};
|
TST: Fix pims warning test under Py3
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import os
import unittest
import warnings
import pims
import trackpy
import trackpy.diag
path, _ = os.path.split(os.path.abspath(__file__))
class DiagTests(unittest.TestCase):
def test_performance_report(self):
trackpy.diag.performance_report()
def test_dependencies(self):
trackpy.diag.dependencies()
class APITests(unittest.TestCase):
def test_pims_deprecation(self):
"""Using a pims class should work, but generate a warning.
The inclusion of these classes (and therefore this test) in
trackpy is deprecated as of v0.3 and will be removed in a future
version."""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always', UserWarning)
imseq = trackpy.ImageSequence(os.path.join(path, 'video/image_sequence/*.png'))
assert isinstance(imseq, pims.ImageSequence)
assert len(w) == 1
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import os
import unittest
import warnings
import trackpy
import trackpy.diag
path, _ = os.path.split(os.path.abspath(__file__))
class DiagTests(unittest.TestCase):
def test_performance_report(self):
trackpy.diag.performance_report()
def test_dependencies(self):
trackpy.diag.dependencies()
class APITests(unittest.TestCase):
def test_pims_deprecation(self):
with warnings.catch_warnings(True) as w:
warnings.simplefilter('always')
_ = trackpy.ImageSequence(os.path.join(path, 'video/image_sequence/*.png'))
assert len(w) == 1
|
Use click event instead of change event for checkbox list so it works in IE
svn commit r13549
|
/**
* JavaScript SwatCheckboxList component
*
* @param id string Id of the matching {@link SwatCheckboxList} object.
*/
function SwatCheckboxList(id)
{
this.check_list = document.getElementsByName(id + '[]');
this.check_all = null; // a reference to a check-all js object
for (i = 0; i < this.check_list.length; i++) {
YAHOO.util.Event.addListener(this.check_list[i], 'click',
SwatCheckboxList.clickHandler, this);
}
}
SwatCheckboxList.clickHandler = function(event, object)
{
object.checkAllInit();
}
SwatCheckboxList.prototype.checkAllInit = function ()
{
if (this.check_all == null)
return;
var count = 0;
for (i = 0; i < this.check_list.length; i++)
if (this.check_list[i].checked)
count++;
else if (count > 0)
break; // can't possibly be all checked or none checked
this.check_all.setState(count == this.check_list.length);
}
SwatCheckboxList.prototype.checkAll = function(checked)
{
for (i = 0; i < this.check_list.length; i++)
this.check_list[i].checked = checked;
}
|
/**
* JavaScript SwatCheckboxList component
*
* @param id string Id of the matching {@link SwatCheckboxList} object.
*/
function SwatCheckboxList(id)
{
this.check_list = document.getElementsByName(id + '[]');
this.check_all = null; // a reference to a check-all js object
for (i = 0; i < this.check_list.length; i++) {
YAHOO.util.Event.addListener(this.check_list[i], 'change',
SwatCheckboxList.clickHandler, this);
}
}
SwatCheckboxList.clickHandler = function(event, object)
{
object.checkAllInit();
}
SwatCheckboxList.prototype.checkAllInit = function ()
{
if (this.check_all == null)
return;
var count = 0;
for (i = 0; i < this.check_list.length; i++)
if (this.check_list[i].checked)
count++;
else if (count > 0)
break; // can't possibly be all checked or none checked
this.check_all.setState(count == this.check_list.length);
}
SwatCheckboxList.prototype.checkAll = function(checked)
{
for (i = 0; i < this.check_list.length; i++)
this.check_list[i].checked = checked;
}
|
Make the first word of the package description capital
|
from setuptools import setup, find_packages
setup(
name = "sanitize",
version = "0.33",
description = "Bringing sanitiy to world of messed-up data",
author = "Aaron Swartz",
author_email = "me@aaronsw.com",
url='http://www.aaronsw.com/2002/sanitize/',
license=open('LICENCE').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.3',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2'
],
license='BSD',
packages=find_packages(),
py_modules=['sanitize'],
include_package_data=True,
zip_safe=False,
)
|
from setuptools import setup, find_packages
setup(
name = "sanitize",
version = "0.33",
description = "bringing sanitiy to world of messed-up data",
author = "Aaron Swartz",
author_email = "me@aaronsw.com",
url='http://www.aaronsw.com/2002/sanitize/',
license=open('LICENCE').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.3',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2'
],
license='BSD',
packages=find_packages(),
py_modules=['sanitize'],
include_package_data=True,
zip_safe=False,
)
|
Add constant name for attribute.value
|
/*
* Copyright 2012 Canoo Engineering AG.
*
* 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.canoo.dolphin.core;
public interface Attribute extends Observable {
String QUALIFIER_PROPERTY = "qualifier";
String DIRTY_PROPERTY = "dirty";
String INITIAL_VALUE = "initialValue";
String VALUE = "value";
Object getValue();
void setValue(Object value);
String getPropertyName();
String getQualifier();
long getId();
void setId(long id);
void syncWith(Attribute source);
boolean isDirty();
Object getInitialValue();
void save();
}
|
/*
* Copyright 2012 Canoo Engineering AG.
*
* 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.canoo.dolphin.core;
public interface Attribute extends Observable {
String QUALIFIER_PROPERTY = "qualifier";
String DIRTY_PROPERTY = "dirty";
String INITIAL_VALUE = "initialValue";
Object getValue();
void setValue(Object value);
String getPropertyName();
String getQualifier();
long getId();
void setId(long id);
void syncWith(Attribute source);
boolean isDirty();
Object getInitialValue();
void save();
}
|
Fix association model with user and email
|
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
if(env !== 'production') {
var config = require(__dirname + '/../config/development.json')[env];
}
else{
config = require(__dirname + '/../config/production.json')[env];
}
var db = {};
if (config.use_env_variable) {
config = {};
config.define = {underscored: true};
var sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
config.define = {underscored: true};
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
|
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
if(env !== 'production') {
var config = require(__dirname + '/../config/development.json')[env];
}
else{
config = require(__dirname + '/../config/production.json')[env];
}
var db = {};
if (config.use_env_variable) {
config = {};
config.define = {underscored: true};
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
config.define = {underscored: true};
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
|
Add basic example of usage
|
<?php namespace mitogh;
function random_image_src( $size = 'full' ){
$sources = random_images_src( $size, 1 );
$src = '';
foreach( $sources as $image_src ){
$src = $image_src;
}
return $src;
}
function random_images_src( $size = 'full', $total = 1 ){
$sources = array();
$ids = random_images_ids( $total );
foreach( $ids as $image_id ){
$src = '';
$data = wp_get_attachment_image_src( $image_id, $size );
if( $data && ! empty( $data ) ){
$src = $data[0];
}
$sources[] = $src;
}
return $sources;
}
function random_images_ids( $total = 1 ){
$query = new Query( array(
'post_mime_type' => 'image',
'posts_per_page' => (int) $total,
));
return $query->run();
}
/* $url = random_image_src(); */
/* printf( '<a href="%s" target="_blank">%s</a>', $url, $url); */
/* printf( '<img src="%s" />', $url ); */
/* die(); */
|
<?php namespace mitogh;
function random_image_src( $size = 'full' ){
$sources = random_images_src( $size, 1 );
$src = '';
foreach( $sources as $image_src ){
$src = $image_src;
}
return $src;
}
function random_images_src( $size = 'full', $total = 1 ){
$sources = array();
$ids = random_images_ids( $total );
foreach( $ids as $image_id ){
$src = '';
$data = wp_get_attachment_image_src( $image_id, $size );
if( $data && ! empty( $data ) ){
$src = $data[0];
}
$sources[] = $src;
}
return $sources;
}
function random_images_ids( $total = 1 ){
$query = new Query( array(
'post_mime_type' => 'image',
'posts_per_page' => (int) $total,
));
return $query->run();
}
|
Fix MODULESTATE_REPLACE bug: checked for a member literally called 'module', rather than for a member named according to the content of module.
|
import { routerReducer as routing } from 'react-router-redux';
import { reducer as form } from 'redux-form';
import crud from 'redux-crud'
import { combineReducers } from 'redux';
// TODO reducer registry in core via store.replaceReducer() and handle
// module state with a reducer instance for each module/key
const moduleStateReducer = (state = {}, action) => {
if (!(action.type.startsWith('MODULESTATE'))) return state;
const newState = Object.assign({}, state);
const module = action.meta.module;
const key = action.meta.key;
switch (action.type) {
case 'MODULESTATE_UPDATE':
if (!(module in newState)) newState[module] = {};
if (!(key in newState[module])) newState[module][key] = {};
newState[module][key] = Object.assign({}, newState[module], action.payload);
break;
case 'MODULESTATE_REPLACE':
if (!(module in newState)) newState[module] = {};
newState[module][key] = Object.assign({}, action.payload);
break;
};
return newState;
};
const rootReducer = combineReducers({
modules: moduleStateReducer,
routing,
form
});
export default rootReducer;
|
import { routerReducer as routing } from 'react-router-redux';
import { reducer as form } from 'redux-form';
import crud from 'redux-crud'
import { combineReducers } from 'redux';
// TODO reducer registry in core via store.replaceReducer() and handle
// module state with a reducer instance for each module/key
const moduleStateReducer = (state = {}, action) => {
if (!(action.type.startsWith('MODULESTATE'))) return state;
const newState = Object.assign({}, state);
const module = action.meta.module;
const key = action.meta.key;
switch (action.type) {
case 'MODULESTATE_UPDATE':
if (!(module in newState)) newState[module] = {};
if (!(key in newState[module])) newState[module][key] = {};
newState[module][key] = Object.assign({}, newState[module], action.payload);
break;
case 'MODULESTATE_REPLACE':
if (!('module' in newState)) newState[module] = {};
newState[module][key] = Object.assign({}, action.payload);
break;
};
return newState;
};
const rootReducer = combineReducers({
modules: moduleStateReducer,
routing,
form
});
export default rootReducer;
|
Send episode_done=True from local human agent
|
# Copyright (c) 2017-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.
"""Agent does gets the local keyboard input in the act() function.
Example: python examples/eval_model.py -m local_human -t babi:Task1k:1 -dt valid
"""
from parlai.core.agents import Agent
from parlai.core.worlds import display_messages
class LocalHumanAgent(Agent):
def __init__(self, opt, shared=None):
super().__init__(opt)
self.id = 'localHuman'
self.done = False
def observe(self, msg):
print(display_messages([msg]))
def act(self):
obs = self.observation
reply = {}
reply['id'] = self.getID()
reply['text'] = input("Enter Your Reply: ")
if reply_text == '[DONE]':
reply['episode_done'] = True
self.done = True
reply['text'] = reply_text
return reply
def epoch_done(self):
return self.done
|
# Copyright (c) 2017-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.
"""Agent does gets the local keyboard input in the act() function.
Example: python examples/eval_model.py -m local_human -t babi:Task1k:1 -dt valid
"""
from parlai.core.agents import Agent
from parlai.core.worlds import display_messages
class LocalHumanAgent(Agent):
def __init__(self, opt, shared=None):
super().__init__(opt)
self.id = 'localHuman'
def observe(self, msg):
print(display_messages([msg]))
def act(self):
obs = self.observation
reply = {}
reply['id'] = self.getID()
reply['text'] = input("Enter Your Reply: ")
return reply
|
Add test for parse;print of church terms
|
'use strict';
var compiler = require('../lib/compiler');
var mocha = require('mocha');
var assert = require('../lib/assert');
var datasets = require('./lib/datasets');
mocha.suite('serialize', function () {
mocha.test('print;parse = id', function () {
var examples = [
'VAR x',
'QUOTE APP LAMBDA CURSOR VAR x VAR x HOLE',
'LETREC VAR i LAMBDA VAR x VAR x APP VAR i VAR i',
];
assert.inverses(compiler.parse, compiler.print, examples);
});
mocha.test('works on datasets.codes', function () {
assert.inverses(compiler.parse, compiler.print, datasets.codes);
});
mocha.test('works on datasets.curryTerms', function () {
assert.inverses(compiler.print, compiler.parse, datasets.curryTerms);
});
mocha.test('works on datasets.churchTerms', function () {
assert.inverses(compiler.print, compiler.parse, datasets.churchTerms);
});
});
|
'use strict';
var compiler = require('../lib/compiler');
var mocha = require('mocha');
var assert = require('../lib/assert');
var datasets = require('./lib/datasets');
mocha.suite('serialize', function () {
mocha.test('print;parse = id', function () {
var examples = [
'VAR x',
'QUOTE APP LAMBDA CURSOR VAR x VAR x HOLE',
'LETREC VAR i LAMBDA VAR x VAR x APP VAR i VAR i',
];
assert.inverses(compiler.parse, compiler.print, examples);
});
mocha.test('works on datasets.codes', function () {
assert.inverses(compiler.parse, compiler.print, datasets.codes);
});
mocha.test('works on datasets.curryTerms', function () {
assert.inverses(compiler.print, compiler.parse, datasets.curryTerms);
});
});
|
Fix the delay for subscription and unsubscription retry
|
from celery.task import task
@task
def subscribe(email, newsletter_list, lang=None, user=None):
from courriers.backends import get_backend
backend = get_backend()()
try:
backend.register(email=email,
newsletter_list=newsletter_list,
lang=lang,
user=user)
except Exception as e:
raise subscribe.retry(args=[email, newsletter_list, lang, user], exc=e, countdown=30)
@task
def unsubscribe(email, newsletter_list=None, lang=None, user=None):
from courriers.backends import get_backend
backend = get_backend()()
try:
backend.unregister(email=email,
newsletter_list=newsletter_list,
lang=lang,
user=user)
except Exception as e:
raise unsubscribe.retry(args=[email, newsletter_list, lang, user], exc=e, countdown=30)
|
from celery.task import task
@task
def subscribe(email, newsletter_list, lang=None, user=None):
from courriers.backends import get_backend
backend = get_backend()()
try:
backend.register(email=email,
newsletter_list=newsletter_list,
lang=lang,
user=user)
except Exception as e:
raise subscribe.retry(args=[email, newsletter_list, lang, user], exc=e, countdown=5)
@task
def unsubscribe(email, newsletter_list=None, lang=None, user=None):
from courriers.backends import get_backend
backend = get_backend()()
try:
backend.unregister(email=email,
newsletter_list=newsletter_list,
lang=lang,
user=user)
except Exception as e:
raise unsubscribe.retry(args=[email, newsletter_list, lang, user], exc=e, countdown=5)
|
Revert "Decrease high timeout in ci"
0e16b3547b7134e032885053ddac97cb85cb7ee2
|
var path = require('path');
var webpack = require('./webpack.config');
process.env.CHROME_BIN = require('puppeteer').executablePath();
module.exports = function (config) {
config.set({
basePath: '.',
frameworks: ['mocha'],
reporters: ['mocha'],
client: {
captureConsole: true,
mocha: {
timeout : 10000, // 10 seconds - upped from 2 seconds
retries: 3 // Allow for slow server on CI.
}
},
files: [
{pattern: path.resolve('./build/injector.js'), watched: false},
{pattern: process.env.KARMA_FILE_PATTERN, watched: false}
],
preprocessors: {
'build/injector.js': ['webpack'],
'src/*.spec.ts': ['webpack', 'sourcemap']
},
mime: {
'text/x-typescript': ['ts','tsx']
},
webpack: webpack,
webpackMiddleware: {
noInfo: true,
stats: 'errors-only'
},
browserNoActivityTimeout: 31000, // 31 seconds - upped from 10 seconds
browserDisconnectTimeout: 31000, // 31 seconds - upped from 2 seconds
browserDisconnectTolerance: 2,
port: 9876,
colors: true,
singleRun: true,
logLevel: config.LOG_INFO
});
};
|
var path = require('path');
var webpack = require('./webpack.config');
process.env.CHROME_BIN = require('puppeteer').executablePath();
module.exports = function (config) {
config.set({
basePath: '.',
frameworks: ['mocha'],
reporters: ['mocha'],
client: {
captureConsole: true,
},
files: [
{pattern: path.resolve('./build/injector.js'), watched: false},
{pattern: process.env.KARMA_FILE_PATTERN, watched: false}
],
preprocessors: {
'build/injector.js': ['webpack'],
'src/*.spec.ts': ['webpack', 'sourcemap']
},
mime: {
'text/x-typescript': ['ts','tsx']
},
webpack: webpack,
webpackMiddleware: {
noInfo: true,
stats: 'errors-only'
},
port: 9876,
colors: true,
singleRun: true,
logLevel: config.LOG_INFO
});
};
|
Set 10.11.0 as minimum macOS version in the .app bundle
|
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'iconfile':'resources/icon.icns',
'includes': {'PySide2.QtCore', 'PySide2.QtUiTools', 'PySide2.QtGui','PySide2.QtWidgets', 'certifi'},
'excludes': {'PySide', 'PySide.QtCore', 'PySide.QtUiTools', 'PySide.QtGui'},
'qt_plugins': ['platforms/libqcocoa.dylib', 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib', 'styles/libqmacstyle.dylib'],
'plist': {
'CFBundleName':'Syncplay',
'CFBundleShortVersionString':syncplay.version,
'CFBundleIdentifier':'pl.syncplay.Syncplay',
'LSMinimumSystemVersion':'10.11.0',
'NSHumanReadableCopyright': '@ 2018 Syncplay All Rights Reserved'
}
}
setup(
app=APP,
name='Syncplay',
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
|
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'iconfile':'resources/icon.icns',
'includes': {'PySide2.QtCore', 'PySide2.QtUiTools', 'PySide2.QtGui','PySide2.QtWidgets', 'certifi'},
'excludes': {'PySide', 'PySide.QtCore', 'PySide.QtUiTools', 'PySide.QtGui'},
'qt_plugins': ['platforms/libqcocoa.dylib', 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib', 'styles/libqmacstyle.dylib'],
'plist': {
'CFBundleName':'Syncplay',
'CFBundleShortVersionString':syncplay.version,
'CFBundleIdentifier':'pl.syncplay.Syncplay',
'NSHumanReadableCopyright': '@ 2017 Syncplay All Rights Reserved'
}
}
setup(
app=APP,
name='Syncplay',
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
|
Set a flag when config is loaded on a browser
|
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the organization nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
window.process = {};
window.process._RJS_baseUrl = function(n)
{
return "..";
};
window.process._RJS_rootDir = function(n)
{
if (n == 1) return ".";
if (n == 0) return "readium-cfi-js";
};
window.process._RJS_isBrowser = true;
require.config({
/* http://requirejs.org/docs/api.html#config-waitSeconds */
waitSeconds: 1
});
|
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the organization nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
window.process = {};
window.process._RJS_baseUrl = function(n)
{
return "..";
};
window.process._RJS_rootDir = function(n)
{
if (n == 1) return ".";
if (n == 0) return "readium-cfi-js";
};
require.config({
/* http://requirejs.org/docs/api.html#config-waitSeconds */
waitSeconds: 1
});
|
Use full path to api in stead of relatieve path
At this moment a relative path is used (../../../), for the cde saikuWidget. But the preview of the dashboard and the 'normal' view are on a different directory level, so one of them needs an extra ../ Fixed by using the full path /pentaho/plugin/saiku/api But this won't work if somebody use a different 'directory' for pentaho. But I guess that is not a big problem...
|
var saikuWidgetComponent = BaseComponent.extend({
update : function() {
var myself=this;
var htmlId = "#" + myself.htmlObject;
if (myself.saikuFilePath.substr(0,1) == "/") {
myself.saikuFilePath = myself.saikuFilePath.substr(1,myself.saikuFilePath.length - 1 );
}
var parameters = {};
if (myself.parameters) {
_.each(myself.parameters, function(parameter) {
var k = parameter[0];
var v = parameter[1];
if (window.hasOwnProperty(v)) {
v = window[v];
}
parameters[k] = v;
});
}
if (myself.width) {
$(htmlId).width(myself.width);
}
if (myself.width) {
$(htmlId).height(myself.height);
}
if ("table" == myself.renderMode) {
$(htmlId).addClass('workspace_results');
var t = $("<div></div>");
$(htmlId).html(t);
htmlId = t;
}
var myClient = new SaikuClient({
server: "/pentaho/plugin/saiku/api",
path: "/cde-component"
});
myClient.execute({
file: myself.saikuFilePath,
htmlObject: htmlId,
render: myself.renderMode,
mode: myself.renderType,
zoom: true,
params: parameters
});
}
});
|
var saikuWidgetComponent = BaseComponent.extend({
update : function() {
var myself=this;
var htmlId = "#" + myself.htmlObject;
if (myself.saikuFilePath.substr(0,1) == "/") {
myself.saikuFilePath = myself.saikuFilePath.substr(1,myself.saikuFilePath.length - 1 );
}
var parameters = {};
if (myself.parameters) {
_.each(myself.parameters, function(parameter) {
var k = parameter[0];
var v = parameter[1];
if (window.hasOwnProperty(v)) {
v = window[v];
}
parameters[k] = v;
});
}
if (myself.width) {
$(htmlId).width(myself.width);
}
if (myself.width) {
$(htmlId).height(myself.height);
}
if ("table" == myself.renderMode) {
$(htmlId).addClass('workspace_results');
var t = $("<div></div>");
$(htmlId).html(t);
htmlId = t;
}
var myClient = new SaikuClient({
server: "../../../plugin/saiku/api",
path: "/cde-component"
});
myClient.execute({
file: myself.saikuFilePath,
htmlObject: htmlId,
render: myself.renderMode,
mode: myself.renderType,
zoom: true,
params: parameters
});
}
});
|
Use the array API types for the array API type annotations
|
"""
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Literal', 'Optional', 'Tuple', 'Union', 'array', 'device',
'dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule']
from typing import Literal, Optional, Tuple, Union, TypeVar
from . import (ndarray, int8, int16, int32, int64, uint8, uint16, uint32,
uint64, float32, float64)
array = ndarray
device = TypeVar('device')
dtype = Literal[int8, int16, int32, int64, uint8, uint16,
uint32, uint64, float32, float64]
SupportsDLPack = TypeVar('SupportsDLPack')
SupportsBufferProtocol = TypeVar('SupportsBufferProtocol')
PyCapsule = TypeVar('PyCapsule')
|
"""
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Literal', 'Optional', 'Tuple', 'Union', 'array', 'device',
'dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule']
from typing import Literal, Optional, Tuple, Union, TypeVar
import numpy as np
array = np.ndarray
device = TypeVar('device')
dtype = Literal[np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16,
np.uint32, np.uint64, np.float32, np.float64]
SupportsDLPack = TypeVar('SupportsDLPack')
SupportsBufferProtocol = TypeVar('SupportsBufferProtocol')
PyCapsule = TypeVar('PyCapsule')
|
Use singular table naming in Many To Many migration
|
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class {{ucfirst($first)}}{{ucfirst($second)}} extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('{{str_singular($first)}}_{{str_singular($second)}}',function (Blueprint $table){
$table->increments('id')->unique()->index()->unsigned();
$table->integer('{{str_singular($first)}}_id')->unsigned()->index();
$table->foreign('{{str_singular($first)}}_id')->references('id')->on('{{$first}}')->onDelete('cascade');
$table->integer('{{str_singular($second)}}_id')->unsigned()->index();
$table->foreign('{{str_singular($second)}}_id')->references('id')->on('{{$second}}')->onDelete('cascade');
/**
* Type your addition here
*
*/
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('{{str_singular($first)}}_{{str_singular($second)}}');
}
}
|
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class {{ucfirst($first)}}{{ucfirst($second)}} extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('{{$first}}_{{$second}}',function (Blueprint $table){
$table->increments('id')->unique()->index()->unsigned();
$table->integer('{{str_singular($first)}}_id')->unsigned()->index();
$table->foreign('{{str_singular($first)}}_id')->references('id')->on('{{$first}}')->onDelete('cascade');
$table->integer('{{str_singular($second)}}_id')->unsigned()->index();
$table->foreign('{{str_singular($second)}}_id')->references('id')->on('{{$second}}')->onDelete('cascade');
/**
* Type your addition here
*
*/
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('{{$first}}_{{$second}}');
}
}
|
Use patchers for overriding data/cache directories
|
# tests.__init__
import os
import os.path
import shutil
import tempfile
import yvs.shared as yvs
from mock import patch
temp_dir = tempfile.gettempdir()
local_data_dir_patcher = patch(
'yvs.shared.LOCAL_DATA_DIR_PATH',
os.path.join(temp_dir, 'yvs-data'))
local_cache_dir_patcher = patch(
'yvs.shared.LOCAL_CACHE_DIR_PATH',
os.path.join(temp_dir, 'yvs-cache'))
def set_up():
local_data_dir_patcher.start()
try:
os.mkdir(yvs.LOCAL_DATA_DIR_PATH)
except OSError:
pass
local_cache_dir_patcher.start()
try:
os.mkdir(yvs.LOCAL_CACHE_DIR_PATH)
except OSError:
pass
def tear_down():
try:
shutil.rmtree(yvs.LOCAL_CACHE_DIR_PATH)
except OSError:
pass
local_cache_dir_patcher.stop()
try:
shutil.rmtree(yvs.LOCAL_DATA_DIR_PATH)
except OSError:
pass
local_data_dir_patcher.stop()
|
# tests.__init__
import os
import os.path
import shutil
import tempfile
import yvs.shared as yvs
temp_dir = tempfile.gettempdir()
yvs.LOCAL_DATA_DIR_PATH = os.path.join(temp_dir, 'yvs-data')
yvs.LOCAL_CACHE_DIR_PATH = os.path.join(temp_dir, 'yvs-cache')
def set_up():
try:
os.mkdir(yvs.LOCAL_DATA_DIR_PATH)
except OSError:
pass
try:
os.mkdir(yvs.LOCAL_CACHE_DIR_PATH)
except OSError:
pass
def tear_down():
try:
shutil.rmtree(yvs.LOCAL_CACHE_DIR_PATH)
except OSError:
pass
try:
shutil.rmtree(yvs.LOCAL_DATA_DIR_PATH)
except OSError:
pass
|
Add more pypi trove classifiers
|
from setuptools import setup
setup(name='glreg',
version='0.9.0',
description='OpenGL XML API registry parser',
url='https://github.com/pyokagan/pyglreg',
author='Paul Tan',
author_email='pyokagan@gmail.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Code Generators',
'Topic :: Software Development :: Libraries :: Python Module',
],
keywords='opengl',
py_modules=['glreg'],
entry_points={
'console_scripts': [
'glreg=glreg:main'
]
})
|
from setuptools import setup
setup(name='glreg',
version='0.9.0',
description='OpenGL XML API registry parser',
url='https://github.com/pyokagan/pyglreg',
author='Paul Tan',
author_email='pyokagan@gmail.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
'Topic :: Software Development :: Code Generators',
'Topic :: Software Development :: Libraries :: Python Module',
],
keywords='opengl',
py_modules=['glreg'],
entry_points={
'console_scripts': [
'glreg=glreg:main'
]
})
|
Correct API helper scripts for getScript and getBuild
|
var
request = require('request'),
config = require('../../config');
exports.get = function () {
var query = arguments.length === 2 ? arguments[0] : null;
var callback = arguments[arguments.length - 1];
var options = {
uri: 'http://localhost:' + config.port + '/components',
timeout: 3000,
json: true
};
if (query) {
options.uri += '/' + query;
}
request.get(options, callback);
};
exports.search = function (query, callback) {
var options = {
uri: 'http://localhost:' + config.port + '/components/?q=' + query,
timeout: 3000,
json: true
};
request.get(options, callback);
};
exports.getScript = function (pkg, callback) {
var options = {
uri: 'http://localhost:' + config.port + '/components/' + pkg + '/script.js',
timeout: 3000
};
request.get(options, callback);
};
exports.getBuild = function (pkg, callback) {
var options = {
uri: 'http://localhost:' + config.port + '/components/' + pkg + '/build.js',
timeout: 3000
};
request.get(options, callback);
};
|
var
request = require('request'),
config = require('../../config');
exports.get = function () {
var query = arguments.length === 2 ? arguments[0] : null;
var callback = arguments[arguments.length - 1];
var options = {
uri: 'http://localhost:' + config.port + '/components',
timeout: 3000,
json: true
};
if (query) {
options.uri += '/' + query;
}
request.get(options, callback);
};
exports.search = function (query, callback) {
var options = {
uri: 'http://localhost:' + config.port + '/components/?q=' + query,
timeout: 3000,
json: true
};
request.get(options, callback);
};
exports.getScript = function (pkg, callback) {
var options = {
uri: 'http://localhost:' + config.port + '/components/' + pkg + '/script.js',
timeout: 3000
};
request.get(options, callback);
};
|
Adjust syntax to match records
|
'use strict'
const tokens = require('../database/tokens')
const KnownError = require('../utils/KnownError')
const response = (entry) => ({
id: entry.id,
created: entry.created,
updated: entry.updated
})
module.exports = {
Mutation: {
createToken: async (parent, { input }) => {
const { username, password, permanent, title } = input
if (process.env.ACKEE_USERNAME == null) throw new KnownError('Ackee username missing in environment')
if (process.env.ACKEE_PASSWORD == null) throw new KnownError('Ackee username missing in environment')
if (username !== process.env.ACKEE_USERNAME) throw new KnownError('Username or password incorrect')
if (password !== process.env.ACKEE_PASSWORD) throw new KnownError('Username or password incorrect')
const entry = await tokens.add({ permanent, title })
return {
success: true,
payload: response(entry)
}
},
deleteToken: async (parent, { id }) => {
await tokens.del(id)
return {
success: true
}
}
}
}
|
'use strict'
const tokens = require('../database/tokens')
const KnownError = require('../utils/KnownError')
const response = (entry) => ({
id: entry.id,
created: entry.created,
updated: entry.updated
})
module.exports = {
Mutation: {
createToken: async (parent, { input }) => {
const { username, password, permanent, title } = input
if (process.env.ACKEE_USERNAME == null) throw new KnownError('Ackee username missing in environment')
if (process.env.ACKEE_PASSWORD == null) throw new KnownError('Ackee username missing in environment')
if (username !== process.env.ACKEE_USERNAME) throw new KnownError('Username or password incorrect')
if (password !== process.env.ACKEE_PASSWORD) throw new KnownError('Username or password incorrect')
const entry = await tokens.add(permanent, title)
return {
success: true,
payload: response(entry)
}
},
deleteToken: async (parent, { id }) => {
await tokens.del(id)
return {
success: true
}
}
}
}
|
Add right and bottom of area to JSON output
|
package technology.tabula.json;
import java.lang.reflect.Type;
import java.util.List;
import technology.tabula.RectangularTextContainer;
import technology.tabula.Table;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public final class TableSerializer implements JsonSerializer<Table> {
public static final TableSerializer INSTANCE = new TableSerializer();
private TableSerializer() {
// singleton
}
@Override
public JsonElement serialize(Table src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject result = new JsonObject();
result.addProperty("extraction_method", src.getExtractionMethod());
result.addProperty("top", src.getTop());
result.addProperty("left", src.getLeft());
result.addProperty("width", src.getWidth());
result.addProperty("height", src.getHeight());
result.addProperty("right", src.getRight());
result.addProperty("bottom", src.getBottom());
JsonArray data;
result.add("data", data = new JsonArray());
for (List<RectangularTextContainer> srcRow : src.getRows()) {
JsonArray row = new JsonArray();
for (RectangularTextContainer textChunk : srcRow) row.add(context.serialize(textChunk));
data.add(row);
}
return result;
}
}
|
package technology.tabula.json;
import java.lang.reflect.Type;
import java.util.List;
import technology.tabula.RectangularTextContainer;
import technology.tabula.Table;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public final class TableSerializer implements JsonSerializer<Table> {
public static final TableSerializer INSTANCE = new TableSerializer();
private TableSerializer() {
// singleton
}
@Override
public JsonElement serialize(Table src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject result = new JsonObject();
result.addProperty("extraction_method", src.getExtractionMethod());
result.addProperty("top", src.getTop());
result.addProperty("left", src.getLeft());
result.addProperty("width", src.getWidth());
result.addProperty("height", src.getHeight());
JsonArray data;
result.add("data", data = new JsonArray());
for (List<RectangularTextContainer> srcRow : src.getRows()) {
JsonArray row = new JsonArray();
for (RectangularTextContainer textChunk : srcRow) row.add(context.serialize(textChunk));
data.add(row);
}
return result;
}
}
|
Remove strict declaration on migration
|
<?php
namespace Sylius\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20180102140039 extends AbstractMigration
{
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('CREATE INDEX IDX_16C8119EE551C011 ON sylius_channel (hostname)');
}
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('DROP INDEX IDX_16C8119EE551C011 ON sylius_channel');
}
}
|
<?php declare(strict_types = 1);
namespace Sylius\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20180102140039 extends AbstractMigration
{
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('CREATE INDEX IDX_16C8119EE551C011 ON sylius_channel (hostname)');
}
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('DROP INDEX IDX_16C8119EE551C011 ON sylius_channel');
}
}
|
Return json-formatted 404 for json requests on invalid routes
|
<?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Http\Controllers;
class FallbackController extends Controller
{
public function __construct()
{
parent::__construct();
if (is_api_request()) {
$this->middleware('api');
} else {
$this->middleware('web');
}
app('route-section')->setError(404);
}
public function index()
{
if (is_json_request()) {
return response([], 404);
}
return ext_view('layout.error', ['statusCode' => 404], 'html', 404);
}
}
|
<?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Http\Controllers;
class FallbackController extends Controller
{
public function __construct()
{
parent::__construct();
if (is_api_request()) {
$this->middleware('api');
} else {
$this->middleware('web');
}
app('route-section')->setError(404);
}
public function index()
{
if (is_api_request()) {
return response([], 404);
}
return ext_view('layout.error', ['statusCode' => 404], 'html', 404);
}
}
|
Add route to list all clicks on a page
|
'use strict';
var express = require('express')
, bodyParser = require('body-parser')
, mongoose = require('mongoose')
, cors = require('./cors')
, app = express();
require('./models/click');
var Click = mongoose.model('Click');
mongoose.connect('mongodb://localhost/heatmap');
app.use(bodyParser.urlencoded({extended: false}));
app.use(cors);
app.post('/event', function (req, res) {
var click = new Click(req.body);
click.save(function (err) {
if (err) console.log(err);
res.status(201).end();
});
});
app.get('/events', function (req, res) {
Click
.distinct('page', function (err, docs) {
if (err) console.log(err);
res.status(200).json({pages: docs}).end();
});
});
app.get('/event/:page', function (req, res) {
Click
.find({page: req.params.page}, '-_id -__v -page -date')
.sort('date')
.exec(function (err, docs) {
if (err) console.log(err);
res.status(200).json({clicks: docs}).end();
});
});
app.listen(3000, function(){
console.log('server listen port 3000');
});
|
'use strict';
var express = require('express')
, bodyParser = require('body-parser')
, mongoose = require('mongoose')
, cors = require('./cors')
, app = express();
require('./models/click');
var Click = mongoose.model('Click');
mongoose.connect('mongodb://localhost/heatmap');
app.use(bodyParser.urlencoded({extended: false}));
app.use(cors);
app.post('/event', function (req, res) {
var click = new Click(req.body);
click.save(function (err) {
if (err) console.log(err);
res.status(201).end();
});
});
app.get('/events', function (req, res) {
Click
.distinct('page', function (err, docs) {
if (err) console.log(err);
res.status(200).json({pages: docs}).end();
});
});
app.listen(3000, function(){
console.log('server listen port 3000');
});
|
Upgrade the Development Status classifier to stable
[skip ci]
|
from setuptools import setup
setup(
name='urlwait',
version='1.0',
description='A CLI utility for blocking until a service is listening',
long_description=open('README.rst').read(),
author='Paul McLanahan',
author_email='paul@mclanahan.net',
license='MIT',
py_modules=['urlwait'],
entry_points={
'console_scripts': ['urlwait = urlwait:main'],
},
url='https://github.com/pmac/urlwait',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Topic :: System :: Systems Administration'
],
keywords=['database_url', 'tcp', 'port', 'docker', 'service',
'deploy', 'deployment'],
)
|
from setuptools import setup
setup(
name='urlwait',
version='1.0',
description='A CLI utility for blocking until a service is listening',
long_description=open('README.rst').read(),
author='Paul McLanahan',
author_email='paul@mclanahan.net',
license='MIT',
py_modules=['urlwait'],
entry_points={
'console_scripts': ['urlwait = urlwait:main'],
},
url='https://github.com/pmac/urlwait',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Topic :: System :: Systems Administration'
],
keywords=['database_url', 'tcp', 'port', 'docker', 'service',
'deploy', 'deployment'],
)
|
Bump version and eduid_common requirement
|
#!/usr/bin/env python
from setuptools import setup, find_packages
import sys
version = '0.1.2b3'
requires = [
'eduid-common[webapp]>=0.2.1b9',
'Flask==0.10.1',
]
test_requires = [
'WebTest==2.0.18',
'mock==1.0.1',
]
testing_extras = test_requires + [
'nose==1.2.1',
'coverage==3.6',
'nosexcover==1.0.8',
]
setup(
name='eduid-webapp',
version=version,
license='bsd',
url='https://www.github.com/eduID/',
author='NORDUnet A/S',
author_email='',
description='authentication service for eduID',
classifiers=[
'Framework :: Flask',
],
packages=find_packages('src'),
package_dir={'': 'src'},
namespace_packages=['eduid_webapp'],
zip_safe=False,
include_package_data=True,
install_requires=requires,
tests_require=test_requires,
extras_require={
'testing': testing_extras,
},
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
import sys
version = '0.1.2b2'
requires = [
'eduid-common[webapp]>=0.2.1b7',
'Flask==0.10.1',
]
test_requires = [
'WebTest==2.0.18',
'mock==1.0.1',
]
testing_extras = test_requires + [
'nose==1.2.1',
'coverage==3.6',
'nosexcover==1.0.8',
]
setup(
name='eduid-webapp',
version=version,
license='bsd',
url='https://www.github.com/eduID/',
author='NORDUnet A/S',
author_email='',
description='authentication service for eduID',
classifiers=[
'Framework :: Flask',
],
packages=find_packages('src'),
package_dir={'': 'src'},
namespace_packages=['eduid_webapp'],
zip_safe=False,
include_package_data=True,
install_requires=requires,
tests_require=test_requires,
extras_require={
'testing': testing_extras,
},
)
|
Watch for changes in the JDL package (rebundle)
|
//
// See https://github.com/jenkinsci/js-builder
//
var builder = require('@jenkins-cd/js-builder');
// Disable js-builder based linting for now.
// Will get fixed with https://github.com/cloudbees/blueocean/pull/55
builder.lint('none');
// Explicitly setting the src paths in order to allow the rebundle task to
// watch for changes in the JDL (js, css, icons etc).
// See https://github.com/jenkinsci/js-builder#setting-src-and-test-spec-paths
builder.src(['src/main/js', 'src/main/less', 'node_modules/@jenkins-cd/design-language/dist']);
//
// Create the main "App" bundle.
// generateNoImportsBundle makes it easier to test with zombie.
//
builder.bundle('src/main/js/blueocean.js')
.withExternalModuleMapping('jquery-detached', 'jquery-detached:jquery2')
.inDir('target/classes/io/jenkins/blueocean')
.less('src/main/less/blueocean.less')
.generateNoImportsBundle();
|
//
// See https://github.com/jenkinsci/js-builder
//
var builder = require('@jenkins-cd/js-builder');
// Disable js-builder based linting for now.
// Will get fixed with https://github.com/cloudbees/blueocean/pull/55
builder.lint('none');
// Explicitly setting the src paths in order to allow the rebundle task to
// watch for changes in the JDL (js, css, icons etc).
// See https://github.com/jenkinsci/js-builder#setting-src-and-test-spec-paths
builder.src(['src/main/js', 'src/main/less', 'node_modules/@jenkins-cd/design-language']);
//
// Create the main "App" bundle.
// generateNoImportsBundle makes it easier to test with zombie.
//
builder.bundle('src/main/js/blueocean.js')
.withExternalModuleMapping('jquery-detached', 'jquery-detached:jquery2')
.inDir('target/classes/io/jenkins/blueocean')
.less('src/main/less/blueocean.less')
.generateNoImportsBundle();
|
Add space in requireEnhancedObjectLiterals error
This adds a missing space to the second } in the error message for consistency.
|
var assert = require('assert');
module.exports = function() { };
module.exports.prototype = {
configure: function(option) {
assert(option === true, this.getOptionName() + ' requires a true value');
},
getOptionName: function() {
return 'requireEnhancedObjectLiterals';
},
check: function(file, errors) {
file.iterateNodesByType('Property', function(node) {
// node.key.name is used when the property key is an unquoted identifier
// node.key.value is used when the property key is a quoted string
var propertyName = node.key.name || node.key.value;
var valueName = node.value.name;
var shorthand = node.shorthand;
// check for non-shorthand properties
if (propertyName && propertyName === valueName && !shorthand) {
errors.add(
'Property assignment should use enhanced object literal function. `{ propName: propName }` is not allowed.',
node.loc.start
);
}
// check for non-method function properties
var valueType = node.value.type;
var valueIsMethod = node.method;
if (valueType === 'FunctionExpression' && !valueIsMethod) {
errors.add(
'Property assignment should use enhanced object literal function. `{ funcName: function() {} }` is not allowed.',
node.loc.start
);
}
});
}
};
|
var assert = require('assert');
module.exports = function() { };
module.exports.prototype = {
configure: function(option) {
assert(option === true, this.getOptionName() + ' requires a true value');
},
getOptionName: function() {
return 'requireEnhancedObjectLiterals';
},
check: function(file, errors) {
file.iterateNodesByType('Property', function(node) {
// node.key.name is used when the property key is an unquoted identifier
// node.key.value is used when the property key is a quoted string
var propertyName = node.key.name || node.key.value;
var valueName = node.value.name;
var shorthand = node.shorthand;
// check for non-shorthand properties
if (propertyName && propertyName === valueName && !shorthand) {
errors.add(
'Property assignment should use enhanced object literal function. `{ propName: propName}` is not allowed.',
node.loc.start
);
}
// check for non-method function properties
var valueType = node.value.type;
var valueIsMethod = node.method;
if (valueType === 'FunctionExpression' && !valueIsMethod) {
errors.add(
'Property assignment should use enhanced object literal function. `{ funcName: function() {} }` is not allowed.',
node.loc.start
);
}
});
}
};
|
Set TERM variable on shell
|
import OverlayRoute from 'ui/pods/overlay/route';
export default OverlayRoute.extend({
model: function() {
var container = this.modelFor('container');
var opt = {
attachStdin: true,
attachStdout: true,
tty: true,
command: ["/bin/sh","-c",'TERM=xterm-256color; export TERM; [ -x /bin/bash ] && exec /bin/bash || exec /bin/sh'],
};
var promise = container.doAction('execute',opt).then(function(exec) {
exec.set('instance', container);
return exec;
});
return promise;
},
renderTemplate: function() {
this.render('container/shell', {into: 'application', outlet: 'overlay'});
},
actions: {
cancel: function() {
this.send('goToPrevious');
},
}
});
|
import OverlayRoute from 'ui/pods/overlay/route';
export default OverlayRoute.extend({
model: function() {
var container = this.modelFor('container');
var opt = {
attachStdin: true,
attachStdout: true,
tty: true,
command: ["/bin/sh","-c",'[ -x /bin/bash ] && exec /bin/bash || exec /bin/sh'],
};
var promise = container.doAction('execute',opt).then(function(exec) {
exec.set('instance', container);
return exec;
});
return promise;
},
renderTemplate: function() {
this.render('container/shell', {into: 'application', outlet: 'overlay'});
},
actions: {
cancel: function() {
this.send('goToPrevious');
},
}
});
|
BAP-10979: Update Existing Workflows
- moved UpdateWorkflowItemFields to v1_14
|
<?php
namespace Oro\Bundle\WorkflowBundle\Migrations\Schema\v1_14;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class UpdateWorkflowItemFieldsMigration implements Migration
{
/**
* {@inheritdoc}
*/
public function up(Schema $schema, QueryBag $queries)
{
$table = $schema->getTable('oro_workflow_item');
if ($table->hasColumn('entity_class')) {
return;
}
$table->addColumn('entity_class', 'string', ['length' => 255, 'notnull' => false]);
$table->changeColumn('entity_id', ['string', 'length' => 255, 'notnull' => false]);
$queries->addPostQuery(
'UPDATE oro_workflow_item AS wi SET entity_class = ' .
'(SELECT related_entity FROM oro_workflow_definition AS wd WHERE wd.name = wi.workflow_name LIMIT 1)'
);
}
}
|
<?php
namespace Oro\Bundle\WorkflowBundle\Migrations\Schema;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class UpdateWorkflowItemFieldsMigration implements Migration
{
/**
* {@inheritdoc}
*/
public function up(Schema $schema, QueryBag $queries)
{
$table = $schema->getTable('oro_workflow_item');
if ($table->hasColumn('entity_class')) {
return;
}
$table->addColumn('entity_class', 'string', ['length' => 255, 'notnull' => false]);
$table->changeColumn('entity_id', ['string', 'length' => 255, 'notnull' => false]);
$queries->addPostQuery(
'UPDATE oro_workflow_item AS wi SET entity_class = ' .
'(SELECT related_entity FROM oro_workflow_definition AS wd WHERE wd.name = wi.workflow_name LIMIT 1)'
);
}
}
|
Drop port from welcome page
|
package web
import (
"html/template"
"log"
"net/http"
"strings"
"github.com/johnmaguire/wbc/database"
)
type IndexHandler struct {
address string
database string
}
func (ih *IndexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
id := getClient("index", r)
// Connect to database
db, err := database.Connect(ih.database)
if err != nil {
log.Fatal(err)
}
// Get URLs from database
urls, err := db.FetchUrls()
if err != nil {
log.Fatal(err)
}
// Load template, parse vars, write to client
t, _ := template.New("index").Parse(indexTemplate)
t.Execute(w, struct {
Client string
URLs []string
}{
id,
urls,
})
}
type WelcomeHandler struct {
address string
database string
}
func (ih *WelcomeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
id := getClient("welcome", r)
// Load template, parse vars, write to client
t, _ := template.New("welcome").Parse(welcomeTemplate)
t.Execute(w, struct {
Client string
RemoteAddr string
}{
id,
r.RemoteAddr[:strings.Index(r.RemoteAddr, ":")],
})
}
|
package web
import (
"html/template"
"log"
"net/http"
"github.com/johnmaguire/wbc/database"
)
type IndexHandler struct {
address string
database string
}
func (ih *IndexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
id := getClient("index", r)
// Connect to database
db, err := database.Connect(ih.database)
if err != nil {
log.Fatal(err)
}
// Get URLs from database
urls, err := db.FetchUrls()
if err != nil {
log.Fatal(err)
}
// Load template, parse vars, write to client
t, _ := template.New("index").Parse(indexTemplate)
t.Execute(w, struct {
Client string
URLs []string
}{
id,
urls,
})
}
type WelcomeHandler struct {
address string
database string
}
func (ih *WelcomeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
id := getClient("welcome", r)
// Load template, parse vars, write to client
t, _ := template.New("welcome").Parse(welcomeTemplate)
t.Execute(w, struct {
Client string
RemoteAddr string
}{
id,
r.RemoteAddr,
})
}
|
Allow putting mp3 sounds in the backpack.
|
// eslint-disable-next-line import/no-unresolved
import soundThumbnail from '!base64-loader!./sound-thumbnail.jpg';
const soundPayload = sound => {
const assetDataUrl = sound.asset.encodeDataURI();
const assetDataFormat = sound.dataFormat;
const payload = {
type: 'sound',
name: sound.name,
thumbnail: soundThumbnail,
// Params to be filled in below
mime: '',
body: ''
};
switch (assetDataFormat) {
case 'wav':
payload.mime = 'audio/x-wav';
payload.body = assetDataUrl.replace('data:audio/x-wav;base64,', '');
break;
case 'mp3':
payload.mime = 'audio/mp3';
// TODO scratch-storage should be fixed so that encodeDataURI does not
// always prepend the wave format header; Once that is fixed, the following
// line will have to change.
payload.body = assetDataUrl.replace('data:audio/x-wav;base64,', '');
break;
default:
alert(`Cannot serialize for format: ${assetDataFormat}`); // eslint-disable-line
}
// Return a promise to make it consistent with other payload constructors like costume-payload
return new Promise(resolve => resolve(payload));
};
export default soundPayload;
|
// eslint-disable-next-line import/no-unresolved
import soundThumbnail from '!base64-loader!./sound-thumbnail.jpg';
const soundPayload = sound => {
const assetDataUrl = sound.asset.encodeDataURI();
const assetDataFormat = sound.dataFormat;
const payload = {
type: 'sound',
name: sound.name,
thumbnail: soundThumbnail,
// Params to be filled in below
mime: '',
body: ''
};
switch (assetDataFormat) {
case 'wav':
payload.mime = 'audio/x-wav';
payload.body = assetDataUrl.replace('data:audio/x-wav;base64,', '');
break;
default:
alert(`Cannot serialize for format: ${assetDataFormat}`); // eslint-disable-line
}
// Return a promise to make it consistent with other payload constructors like costume-payload
return new Promise(resolve => resolve(payload));
};
export default soundPayload;
|
Add support for chayns-call 52
|
import * as jsonCallFunctions from './calls/index';
const jsonCalls = {
1: jsonCallFunctions.toggleWaitCursor,
2: jsonCallFunctions.selectTapp,
4: jsonCallFunctions.showPictures,
14: jsonCallFunctions.requestGeoLocation,
15: jsonCallFunctions.showVideo,
16: jsonCallFunctions.showAlert,
18: jsonCallFunctions.getGlobalData,
30: jsonCallFunctions.dateTimePicker,
50: jsonCallFunctions.selectDialog,
52: jsonCallFunctions.setTobitAccessToken,
54: jsonCallFunctions.tobitLogin,
56: jsonCallFunctions.tobitLogout,
72: jsonCallFunctions.showFloatingButton,
73: jsonCallFunctions.setObjectForKey,
74: jsonCallFunctions.getObjectForKey,
75: jsonCallFunctions.addChaynsCallErrorListener,
77: jsonCallFunctions.setIframeHeight,
78: jsonCallFunctions.getWindowMetric,
81: jsonCallFunctions.scrollToPosition,
92: jsonCallFunctions.updateChaynsId,
102: jsonCallFunctions.addScrollListener,
103: jsonCallFunctions.inputDialog,
112: jsonCallFunctions.sendEventToTopFrame,
113: jsonCallFunctions.closeDialog,
114: jsonCallFunctions.setWebsiteTitle,
115: jsonCallFunctions.setTobitAccessToken,
127: jsonCallFunctions.getSavedIntercomChats,
128: jsonCallFunctions.setIntercomChatData,
129: jsonCallFunctions.closeWindow,
};
export default jsonCalls;
|
import * as jsonCallFunctions from './calls/index';
const jsonCalls = {
1: jsonCallFunctions.toggleWaitCursor,
2: jsonCallFunctions.selectTapp,
4: jsonCallFunctions.showPictures,
14: jsonCallFunctions.requestGeoLocation,
15: jsonCallFunctions.showVideo,
16: jsonCallFunctions.showAlert,
18: jsonCallFunctions.getGlobalData,
30: jsonCallFunctions.dateTimePicker,
50: jsonCallFunctions.selectDialog,
54: jsonCallFunctions.tobitLogin,
56: jsonCallFunctions.tobitLogout,
72: jsonCallFunctions.showFloatingButton,
73: jsonCallFunctions.setObjectForKey,
74: jsonCallFunctions.getObjectForKey,
75: jsonCallFunctions.addChaynsCallErrorListener,
77: jsonCallFunctions.setIframeHeight,
78: jsonCallFunctions.getWindowMetric,
81: jsonCallFunctions.scrollToPosition,
92: jsonCallFunctions.updateChaynsId,
102: jsonCallFunctions.addScrollListener,
103: jsonCallFunctions.inputDialog,
112: jsonCallFunctions.sendEventToTopFrame,
113: jsonCallFunctions.closeDialog,
114: jsonCallFunctions.setWebsiteTitle,
115: jsonCallFunctions.setTobitAccessToken,
127: jsonCallFunctions.getSavedIntercomChats,
128: jsonCallFunctions.setIntercomChatData,
129: jsonCallFunctions.closeWindow,
};
export default jsonCalls;
|
Fix invalid type in JSdoc.
|
/**
* External dependencies
*/
import data, { TYPE_CORE } from 'GoogleComponents/data';
import { trackEvent } from 'assets/js/util/tracking';
const ACCEPTED = 'accepted';
const DISMISSED = 'dismissed';
/**
* Marks the given notification with the provided state.
*
* @param {string} id Notification ID.
* @param {string} state Notification state.
*/
export async function markNotification( id, state ) {
// Invalidate the cache so that notifications will be fetched fresh
// to not show a marked notification again.
data.invalidateCacheGroup( TYPE_CORE, 'site', 'notifications' );
trackEvent( 'site_notifications', state, id );
return await data.set( TYPE_CORE, 'site', 'mark-notification', {
notificationID: id,
notificationState: state,
} );
}
/**
* Marks the given notification as accepted.
*
* @param {string} id Notification ID.
*/
export async function acceptNotification( id ) {
return await markNotification( id, ACCEPTED );
}
/**
* Marks the given notification as dismissed.
*
* @param {string} id Notification ID.
*/
export async function dismissNotification( id ) {
return await markNotification( id, DISMISSED );
}
|
/**
* External dependencies
*/
import data, { TYPE_CORE } from 'GoogleComponents/data';
import { trackEvent } from 'assets/js/util/tracking';
const ACCEPTED = 'accepted';
const DISMISSED = 'dismissed';
/**
* Marks the given notification with the provided state.
*
* @param {string} id Notification ID.
* @param {state} state Notification state.
*/
export async function markNotification( id, state ) {
// Invalidate the cache so that notifications will be fetched fresh
// to not show a marked notification again.
data.invalidateCacheGroup( TYPE_CORE, 'site', 'notifications' );
trackEvent( 'site_notifications', state, id );
return await data.set( TYPE_CORE, 'site', 'mark-notification', {
notificationID: id,
notificationState: state,
} );
}
/**
* Marks the given notification as accepted.
*
* @param {string} id Notification ID.
*/
export async function acceptNotification( id ) {
return await markNotification( id, ACCEPTED );
}
/**
* Marks the given notification as dismissed.
*
* @param {string} id Notification ID.
*/
export async function dismissNotification( id ) {
return await markNotification( id, DISMISSED );
}
|
Add minidump and xbe backends to extras_require
|
try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='cle',
description='CLE Loads Everything (at least, many binary formats!) and provides a pythonic interface to analyze what they are and what they would look like in memory.',
version='8.20.1.7',
python_requires='>=3.5',
packages=packages,
install_requires=[
'pyelftools>=0.25',
'cffi',
'pyvex==8.20.1.7',
'pefile',
'sortedcontainers>=2.0',
],
extras_require={
"minidump": ["minidump==0.0.10"],
"xbe": ["pyxbe==0.0.2"],
}
)
|
try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='cle',
description='CLE Loads Everything (at least, many binary formats!) and provides a pythonic interface to analyze what they are and what they would look like in memory.',
version='8.20.1.7',
python_requires='>=3.5',
packages=packages,
install_requires=[
'pyelftools>=0.25',
'cffi',
'pyvex==8.20.1.7',
'pefile',
'sortedcontainers>=2.0',
]
)
|
Add build check to ensure all faces are included in lib
|
'use strict';
/* Dependencies. */
var fs = require('fs');
var path = require('path');
var gemoji = require('gemoji').name;
var toJSON = require('plain-text-data-to-json');
/* Read. */
var faces = toJSON(fs.readFileSync('faces.txt', 'utf8'));
var all = [];
var unclassified = ['🤖'];
/* Manipulate. */
faces = Object.keys(faces).sort().map(function (name) {
var num = Number(faces[name]);
if (isNaN(num)) {
console.log('Invalid valence for %s: %s', name, faces[name]);
}
if (!gemoji[name]) {
console.log('Invalid gemoji %s', name);
}
all.push(gemoji[name].emoji);
return {
name: name,
emoji: gemoji[name].emoji,
polarity: num
};
});
Object.keys(gemoji).forEach(function (name) {
var info = gemoji[name];
var emoji = info.emoji;
if (info.category !== 'people') {
return;
}
if (!/\bface\b/.test(info.description)) {
return;
}
if (all.indexOf(emoji) === -1 && unclassified.indexOf(emoji) === -1) {
throw new Error('Missing definition for ' + emoji + ' (' + info.description + ')');
}
});
/* Write. */
var doc = JSON.stringify(faces, null, 2) + '\n';
/* Write the dictionary. */
fs.writeFileSync(path.join('index.json'), doc);
|
'use strict';
/* Dependencies. */
var fs = require('fs');
var path = require('path');
var gemoji = require('gemoji').name;
var toJSON = require('plain-text-data-to-json');
/* Read. */
var faces = toJSON(fs.readFileSync('faces.txt', 'utf8'));
/* Manipulate. */
faces = Object.keys(faces).sort().map(function (name) {
var num = Number(faces[name]);
if (isNaN(num)) {
console.log('Invalid valence for %s: %s', name, faces[name]);
}
if (!gemoji[name]) {
console.log('Invalid gemoji %s', name);
}
return {
name: name,
emoji: gemoji[name].emoji,
polarity: num
};
});
/* Write. */
var doc = JSON.stringify(faces, null, 2) + '\n';
/* Write the dictionary. */
fs.writeFileSync(path.join('index.json'), doc);
|
Add comment about possible smoothScrolling in mMF
|
"use strict";
angular.module('arethusa.morph').directive('mirrorMorphForm', [
'morph',
'$location',
'$anchorScroll',
function(morph, $location, $anchorScroll) {
return {
restrict: 'A',
scope: {
form: '=mirrorMorphForm',
tokenId: '='
},
link: function(scope, element, attrs) {
var morphToken = morph.analyses[scope.tokenId];
var menuId = 'mfc' + scope.tokenId;
function newCustomForm() {
var form = angular.copy(scope.form);
// We might want to clean up even more here - such as the
// lexical inventory information. Revisit later.
delete form.origin;
return form;
}
element.bind('click', function() {
scope.$apply(morphToken.customForm = newCustomForm());
$location.hash(menuId);
angular.element(document.getElementById(menuId)).removeClass('hide');
// Sadly doesn't have any smooth scroll capabilities - we might have to
// change this implementation at some point.
$anchorScroll();
});
}
};
}
]);
|
"use strict";
angular.module('arethusa.morph').directive('mirrorMorphForm', [
'morph',
'$location',
'$anchorScroll',
function(morph, $location, $anchorScroll) {
return {
restrict: 'A',
scope: {
form: '=mirrorMorphForm',
tokenId: '='
},
link: function(scope, element, attrs) {
var morphToken = morph.analyses[scope.tokenId];
var menuId = 'mfc' + scope.tokenId;
function newCustomForm() {
var form = angular.copy(scope.form);
// We might want to clean up even more here - such as the
// lexical inventory information. Revisit later.
delete form.origin;
return form;
}
element.bind('click', function() {
scope.$apply(morphToken.customForm = newCustomForm());
$location.hash(menuId);
angular.element(document.getElementById(menuId)).removeClass('hide');
$anchorScroll();
});
}
};
}
]);
|
Allow queries of names without visibility
* Fixes #224
|
export class UIDatabase {
constructor(database) {
this.database = database;
}
objects(type) {
let results = this.database.objects(translateToCoreDatabaseType(type));
switch (type) {
case 'Customer':
results = results.filtered('isVisible == true AND isCustomer == true');
break;
case 'Item':
results = results.filtered('isVisible == true');
break;
default:
break;
}
return results;
}
addListener(...args) { return this.database.addListener(...args); }
removeListener(...args) { return this.database.removeListener(...args); }
alertListeners(...args) { return this.database.alertListeners(...args); }
create(...args) { return this.database.create(...args); }
delete(...args) { return this.database.delete(...args); }
deleteAll(...args) { return this.database.deleteAll(...args); }
save(...args) { return this.database.save(...args); }
update(...args) { return this.database.update(...args); }
write(...args) { return this.database.write(...args); }
}
function translateToCoreDatabaseType(type) {
switch (type) {
case 'Customer':
return 'Name';
default:
return type;
}
}
|
export class UIDatabase {
constructor(database) {
this.database = database;
}
objects(type) {
let results = this.database.objects(translateToCoreDatabaseType(type));
switch (type) {
case 'Customer':
results = results.filtered('isVisible == true AND isCustomer == true');
break;
case 'Item':
results = results.filtered('isVisible == true');
break;
case 'Name':
results = results.filtered('isVisible == true OR type == "inventory_adjustment"');
break;
default:
break;
}
return results;
}
addListener(...args) { return this.database.addListener(...args); }
removeListener(...args) { return this.database.removeListener(...args); }
alertListeners(...args) { return this.database.alertListeners(...args); }
create(...args) { return this.database.create(...args); }
delete(...args) { return this.database.delete(...args); }
deleteAll(...args) { return this.database.deleteAll(...args); }
save(...args) { return this.database.save(...args); }
update(...args) { return this.database.update(...args); }
write(...args) { return this.database.write(...args); }
}
function translateToCoreDatabaseType(type) {
switch (type) {
case 'Customer':
return 'Name';
default:
return type;
}
}
|
Allow indices greater than standard array length
|
import fromPairs from 'lodash.frompairs';
export default class ArrayIndicesProxy {
constructor(targetArray, handler) {
const newHandler = fromPairs(Object.entries(handler).map(([name, trap]) => {
const propertyAccessTraps = ['defineProperty', 'deleteProperty', 'get', 'getOwnPropertyDescriptor', 'has', 'set'];
if (propertyAccessTraps.includes(name)) {
return [name, (target, property, ...other) => {
if (typeof property !== 'symbol') {
const parsed = parseInt(property, 10);
if (parsed >= 0 && parsed <= Number.MAX_VALUE) {
return trap(target, parsed, ...other);
}
}
return Reflect[name](target, property, ...other);
}];
}
return [name, trap];
}));
return new Proxy(targetArray, newHandler);
}
}
|
import fromPairs from 'lodash.frompairs';
export default class ArrayIndicesProxy {
constructor(targetArray, handler) {
const newHandler = fromPairs(Object.entries(handler).map(([name, trap]) => {
const propertyAccessTraps = ['defineProperty', 'deleteProperty', 'get', 'getOwnPropertyDescriptor', 'has', 'set'];
if (propertyAccessTraps.includes(name)) {
return [name, (target, property, ...other) => {
if (typeof property !== 'symbol') {
const parsed = parseInt(property, 10);
const maxArrayLength = 4294967295;
if (parsed >= 0 && parsed <= maxArrayLength) {
return trap(target, parsed, ...other);
}
}
return Reflect[name](target, property, ...other);
}];
}
return [name, trap];
}));
return new Proxy(targetArray, newHandler);
}
}
|
Enable authentication for rest api
|
import json
from restless.dj import DjangoResource
from restless.resources import skip_prepare
from django.conf.urls import patterns, url
from harvest.models import Job
from harvest.jobstatemachine import JobStatemachine
from borg_utils.jobintervals import Triggered
class JobResource(DjangoResource):
def is_authenticated(self):
return self.request.user.is_authenticated()
@staticmethod
def urls():
return patterns('',
url(r'^/?$',JobResource.as_list(),name='api_job_create'),
)
@skip_prepare
def create(self):
job_batch_id = Triggered.instance().job_batch_id
resp = {"status":True, "message":{}}
result = None
for name in self.data.get('publishes') or []:
result = JobStatemachine.create_job_by_name(name,Triggered.instance(),job_batch_id)
if result[0]:
resp["message"][name] = "job id : {0}".format(result[1])
else:
resp["status"] = False
resp["message"][name] = result[1]
return resp
|
import json
from restless.dj import DjangoResource
from restless.resources import skip_prepare
from django.conf.urls import patterns, url
from harvest.models import Job
from harvest.jobstatemachine import JobStatemachine
from borg_utils.jobintervals import Triggered
class JobResource(DjangoResource):
def is_authenticated(self):
return self.request.user.is_authenticated() or True
@staticmethod
def urls():
return patterns('',
url(r'^/?$',JobResource.as_list(),name='api_job_create'),
)
@skip_prepare
def create(self):
job_batch_id = Triggered.instance().job_batch_id
resp = {"status":True, "message":{}}
result = None
for name in self.data.get('publishes') or []:
result = JobStatemachine.create_job_by_name(name,Triggered.instance(),job_batch_id)
if result[0]:
resp["message"][name] = "job id : {0}".format(result[1])
else:
resp["status"] = False
resp["message"][name] = result[1]
return resp
|
Update the Migration ti have accessMask aswell
|
<?php
use Phinx\Migration\AbstractMigration;
class ApiKeys extends AbstractMigration
{
/**
* Change Method.
*
* More information on this method is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-change-method
*
* Uncomment this method if you would like to use it.
*
public function change()
{
}
*/
/**
* Migrate Up.
*/
public function up()
{
$apiKeys = $this->table("apiKeys");
$apiKeys
->addColumn("keyID", "string", array("limit" => 250))
->addColumn("vCode", "string", array("limit" => 250))
->addColumn("userID", "int", array("limit" => 11))
->addColumn("errorCode", "int", array("limit" => 4))
->addColumn("accessMask", "int", array("limit" => 11))
->addColumn("dateAdded", "datetime", array("default" => "CURRENT_TIMESTAMP"))
->addColumn("lastValidation", "datetime", array("default" => "0000-00-00 00:00:00"))
->addIndex(array("keyID"))
->addIndex(array("keyID", "vCode"))
->addIndex(array("keyID", "dateAdded"))
->save();
}
/**
* Migrate Down.
*/
public function down()
{
}
}
|
<?php
use Phinx\Migration\AbstractMigration;
class ApiKeys extends AbstractMigration
{
/**
* Change Method.
*
* More information on this method is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-change-method
*
* Uncomment this method if you would like to use it.
*
public function change()
{
}
*/
/**
* Migrate Up.
*/
public function up()
{
$apiKeys = $this->table("apiKeys");
$apiKeys
->addColumn("keyID", "string", array("limit" => 250))
->addColumn("vCode", "string", array("limit" => 250))
->addColumn("userID", "int", array("limit" => 11))
->addColumn("errorCode", "int", array("limit" => 4))
->addColumn("dateAdded", "datetime", array("default" => "CURRENT_TIMESTAMP"))
->addColumn("lastValidation", "datetime", array("default" => "0000-00-00 00:00:00"))
->addIndex(array("keyID"))
->addIndex(array("keyID", "vCode"))
->addIndex(array("keyID", "dateAdded"))
->save();
}
/**
* Migrate Down.
*/
public function down()
{
}
}
|
Move docstring to appropriately placed comment
|
import textwrap
def test_environ(script, tmpdir):
demo = tmpdir.joinpath('warnings_demo.py')
demo.write_text(textwrap.dedent('''
from logging import basicConfig
from pip._internal.utils import deprecation
deprecation.install_warning_logger()
basicConfig()
deprecation.deprecated("deprecated!", replacement=None, gone_in=None)
'''))
result = script.run('python', demo, expect_stderr=True)
expected = 'WARNING:pip._internal.deprecations:DEPRECATION: deprecated!\n'
assert result.stderr == expected
# $PYTHONWARNINGS was added in python2.7
script.environ['PYTHONWARNINGS'] = 'ignore'
result = script.run('python', demo)
assert result.stderr == ''
|
import textwrap
def test_environ(script, tmpdir):
"""$PYTHONWARNINGS was added in python2.7"""
demo = tmpdir.joinpath('warnings_demo.py')
demo.write_text(textwrap.dedent('''
from logging import basicConfig
from pip._internal.utils import deprecation
deprecation.install_warning_logger()
basicConfig()
deprecation.deprecated("deprecated!", replacement=None, gone_in=None)
'''))
result = script.run('python', demo, expect_stderr=True)
expected = 'WARNING:pip._internal.deprecations:DEPRECATION: deprecated!\n'
assert result.stderr == expected
script.environ['PYTHONWARNINGS'] = 'ignore'
result = script.run('python', demo)
assert result.stderr == ''
|
Add a ci gulp task
|
import gulp from 'gulp';
import defaults from 'lodash/defaults';
import plumber from 'gulp-plumber';
import webpack from 'webpack-stream';
import jscs from 'gulp-jscs';
import jshint from 'gulp-jshint';
import { JSXHINT as linter } from 'jshint-jsx';
import webpackPrd from './conf/webpack.prd.config';
import webpackDev from './conf/webpack.dev.config';
const env = process.env.NODE_ENV || 'dev';
const webpackConf = {
'dev': webpackDev,
'prd': webpackPrd
}[env];
const paths = {
js: [
'*.js',
'src/**/*.js'
]
};
gulp.task('build:scripts', () => {
return webpack(webpackConf)
.pipe(gulp.dest('./dist'));
});
gulp.task('watch:scripts', () => {
return webpack(defaults(webpackConf, {
watch: true,
keepalive: true
}));
});
gulp.task('lint', () => {
return gulp.src(paths.js)
.pipe(plumber())
.pipe(jscs())
.pipe(jshint({linter: linter}))
.pipe(jshint.reporter('jshint-stylish'));
});
gulp.task('watch:lint', () => {
gulp.watch(paths.js, ['lint']);
});
gulp.task('test', []);
gulp.task('watch', ['watch:lint', 'watch:scripts']);
gulp.task('build', ['build:scripts']);
gulp.task('ci', ['lint', 'build', 'test']);
gulp.task('default', ['build', 'test']);
|
import gulp from 'gulp';
import defaults from 'lodash/defaults';
import plumber from 'gulp-plumber';
import webpack from 'webpack-stream';
import jscs from 'gulp-jscs';
import jshint from 'gulp-jshint';
import { JSXHINT as linter } from 'jshint-jsx';
import webpackPrd from './conf/webpack.prd.config';
import webpackDev from './conf/webpack.dev.config';
const env = process.env.NODE_ENV || 'dev';
const webpackConf = {
'dev': webpackDev,
'prd': webpackPrd
}[env];
const paths = {
js: [
'*.js',
'src/**/*.js'
]
};
gulp.task('build:scripts', () => {
return webpack(webpackConf)
.pipe(gulp.dest('./dist'));
});
gulp.task('watch:scripts', () => {
return webpack(defaults(webpackConf, {
watch: true,
keepalive: true
}));
});
gulp.task('lint', () => {
return gulp.src(paths.js)
.pipe(plumber())
.pipe(jscs())
.pipe(jshint({linter: linter}))
.pipe(jshint.reporter('jshint-stylish'));
});
gulp.task('watch:lint', () => {
gulp.watch(paths.js, ['lint']);
});
gulp.task('watch', ['watch:lint', 'watch:scripts']);
gulp.task('build', ['build:scripts']);
gulp.task('default', ['build']);
|
Add Docstrings for class methods.
|
"""
Name: Paul Briant
Date: 11/29/16
Class: Introduction to Python
Session: 08
Assignment: Circle Lab
Description:
Classes for Circle Lab
"""
import math
class Circle:
def __init__(self, radius):
""" Initialize circle attributes radius and diameter"""
self.radius = radius
self.diameter = radius * 2
@classmethod
def from_diameter(cls, diameter):
self = cls(diameter / 2)
return self
def __str__(self):
return "A circle object with radius: {}".format(self.radius)
def __repr__(self):
return "Circle({})".format(self.radius)
@property
def diameter(self):
""" Calculate diameter from radius"""
return self.radius * 2
@diameter.setter
def diameter(self, value):
""" Calculate radius from diameter"""
self.radius = value / 2
@property
def area(self):
""" Calculate area using radius and pi"""
return (self.radius ** 2) * math.pi
|
"""
Name: Paul Briant
Date: 11/29/16
Class: Introduction to Python
Session: 08
Assignment: Circle Lab
Description:
Classes for Circle Lab
"""
import math
class Circle:
def __init__(self, radius):
"""
"""
self.radius = radius
self.diameter = radius * 2
@classmethod
def from_diameter(cls, diameter):
self = cls(diameter / 2)
return self
def __str__(self):
return "A circle object with radius: {}".format(self.radius)
def __repr__(self):
return "Circle({})".format(self.radius)
@property
def diameter(self):
return self.radius * 2
@diameter.setter
def diameter(self, value):
self.radius = value / 2
@property
def area(self):
return (self.radius ** 2) * math.pi
|
Update Twitter test to be more robust
|
from unfurl import Unfurl
import unittest
class TestTwitter(unittest.TestCase):
def test_twitter(self):
""" Test a typical and a unique Twitter url """
test = Unfurl()
test.add_to_queue(
data_type='url', key=None,
value='https://twitter.com/_RyanBenson/status/1098230906194546688')
test.parse_queue()
# check the number of nodes
self.assertEqual(len(test.nodes.keys()), 13)
self.assertEqual(test.total_nodes, 13)
# confirm that snowflake was detected
self.assertIn('Twitter Snowflakes', test.nodes[9].hover)
# embedded timestamp parses correctly
self.assertEqual('2019-02-20 14:40:26.837', test.nodes[13].value)
# make sure the queue finished empty
self.assertTrue(test.queue.empty())
self.assertEqual(len(test.edges), 0)
if __name__ == '__main__':
unittest.main()
|
from unfurl import Unfurl
import unittest
class TestTwitter(unittest.TestCase):
def test_twitter(self):
""" Test a tyipcal and a unique Discord url """
# unit test for a unique Discord url.
test = Unfurl()
test.add_to_queue(data_type='url', key=None,
value='https://twitter.com/_RyanBenson/status/1098230906194546688')
test.parse_queue()
# test number of nodes
self.assertEqual(len(test.nodes.keys()), 13)
self.assertEqual(test.total_nodes, 13)
# is processing finished empty
self.assertTrue(test.queue.empty())
self.assertEqual(len(test.edges), 0)
if __name__ == '__main__':
unittest.main()
|
Revert "adding slot_index to impression_stats_daily"
This reverts commit 71202d2f9e2cafa5bf8ef9e0c6a355a8d65d5c7a.
|
import os
class DefaultConfig(object):
"""
Configuration suitable for use for development
"""
DEBUG = True
APPLICATION_ROOT = None
JSONIFY_PRETTYPRINT_REGULAR = True
STATIC_ENABLED_ENVS = {"dev", "test"}
ENVIRONMENT = "dev"
SECRET_KEY = "moz-splice-development-key"
TEMPLATE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates")
STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
FIXTURES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures")
COUNTRY_FIXTURE_PATH = os.path.join(FIXTURES_DIR, "iso3166.csv")
LOCALE_FIXTURE_PATH = os.path.join(FIXTURES_DIR, "all-locales.mozilla-aurora")
SQLALCHEMY_DATABASE_URI = "postgres://localhost/mozsplice"
SQLALCHEMY_ECHO = False
SQLALCHEMY_POOL_SIZE = 5
SQLALCHEMY_POOL_TIMEOUT = 10
|
import os
class DefaultConfig(object):
"""
Configuration suitable for use for development
"""
DEBUG = True
APPLICATION_ROOT = None
JSONIFY_PRETTYPRINT_REGULAR = True
STATIC_ENABLED_ENVS = {"dev", "test"}
ENVIRONMENT = "dev"
SECRET_KEY = "moz-splice-development-key"
TEMPLATE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates")
STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
FIXTURES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures")
COUNTRY_FIXTURE_PATH = os.path.join(FIXTURES_DIR, "iso3166.csv")
LOCALE_FIXTURE_PATH = os.path.join(FIXTURES_DIR, "all-locales.mozilla-aurora")
SQLALCHEMY_DATABASE_URI = "postgres://postgres:p@ssw0rd66@localhost/mozsplice"
SQLALCHEMY_ECHO = False
SQLALCHEMY_POOL_SIZE = 5
SQLALCHEMY_POOL_TIMEOUT = 10
|
Add chech for short passwords
|
from flask import Flask, jsonify, request
from modals.modals import User, Bucket, Item
from api import create_app, db
from validate_email import validate_email
app = create_app('DevelopmentEnv')
@app.route('/')
def index():
response = jsonify({'Welcome Message': 'Hello'})
response.status_code = 201
return response
@app.route('/auth/register', methods=['POST'])
def register():
request.get_json(force=True)
try:
name = request.json['name']
email = request.json['email']
password = request.json['password']
if not name or not email or not password:
response = jsonify({'Error': 'Missing Values'})
response.status_code = 400
return response
if not validate_email(email):
response = jsonify({'Error': 'Invalid Email'})
response.status_code = 400
return response
if len(password) < 6:
response = jsonify({'Error': 'Password is short'})
response.status_code = 400
return response
except KeyError:
response = jsonify({'Error': 'Invalid Keys detected'})
response.status_code = 500
return response
if __name__ == '__main__':
app.run()
|
from flask import Flask, jsonify, request
from modals.modals import User, Bucket, Item
from api import create_app, db
from validate_email import validate_email
app = create_app('DevelopmentEnv')
@app.route('/')
def index():
response = jsonify({'Welcome Message': 'Hello'})
response.status_code = 201
return response
@app.route('/auth/register', methods=['POST'])
def register():
request.get_json(force=True)
try:
name = request.json['name']
email = request.json['email']
password = request.json['password']
if not name or not email or not password:
response = jsonify({'Error': 'Missing Values'})
response.status_code = 400
return response
if not validate_email(email):
response = jsonify({'Error': 'Invalid Email'})
response.status_code = 400
return response
except KeyError:
response = jsonify({'Error': 'Invalid Keys detected'})
response.status_code = 500
return response
if __name__ == '__main__':
app.run()
|
PUT para atualizar o recurso Livro
|
package com.fabiohideki.socialbooks.resources;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.fabiohideki.socialbooks.domain.Livro;
import com.fabiohideki.socialbooks.repository.LivrosRepository;
@RestController
@RequestMapping("/livros")
public class LivrosResources {
@Autowired
private LivrosRepository livrosRepository;
@RequestMapping(method = RequestMethod.GET)
public List<Livro> listar() {
return livrosRepository.findAll();
}
@RequestMapping(method = RequestMethod.POST)
public void salvar(@RequestBody Livro livro) {
livrosRepository.save(livro);
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Livro buscar(@PathVariable("id") Long id) {
return livrosRepository.findOne(id);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public void deletar(@PathVariable("id") Long id) {
livrosRepository.delete(id);
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public void atualizar(@RequestBody Livro livro, @PathVariable("id") Long id) {
livro.setId(id);
livrosRepository.save(livro);
}
}
|
package com.fabiohideki.socialbooks.resources;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.fabiohideki.socialbooks.domain.Livro;
import com.fabiohideki.socialbooks.repository.LivrosRepository;
@RestController
@RequestMapping("/livros")
public class LivrosResources {
@Autowired
private LivrosRepository livrosRepository;
@RequestMapping(method = RequestMethod.GET)
public List<Livro> listar() {
return livrosRepository.findAll();
}
@RequestMapping(method = RequestMethod.POST)
public void salvar(@RequestBody Livro livro) {
livrosRepository.save(livro);
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Livro buscar(@PathVariable Long id) {
return livrosRepository.findOne(id);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public void deletar(@PathVariable Long id) {
livrosRepository.delete(id);
}
}
|
Add assertion message to acceptance tests
|
import Ember from 'ember';
import { test } from 'qunit';
import moduleForAcceptance from '../../tests/helpers/module-for-acceptance';
const { $ } = Ember;
// Original images sizes (from AJAX Content-Length header)
const uncompressedSizes = {
'jpg': 35863,
'png': 11795,
'svg': 4619
};
moduleForAcceptance('Acceptance | imagemin');
test('Image files are compressed', function(assert) {
assert.expect(3);
visit('/');
andThen(function() {
// Compare the Content-Length of each image against the original
// file size. Dummy app is setup to enable compression, so the
// file sizes should be smaller.
Object.keys(uncompressedSizes).forEach((ext) => {
const url = `/logo.${ext}`;
const uncompressedSize = uncompressedSizes[ext];
$.get(url).then((data, status, xhr) => {
const compressedSize = parseInt(xhr.getResponseHeader('Content-Length'), 10);
assert.ok(compressedSize < uncompressedSize, `${ext} file compressed`);
});
});
});
});
|
import Ember from 'ember';
import { test } from 'qunit';
import moduleForAcceptance from '../../tests/helpers/module-for-acceptance';
const { $ } = Ember;
// Original images sizes (from AJAX Content-Length header)
const uncompressedSizes = {
'jpg': 35863,
'png': 11795,
'svg': 4619
};
moduleForAcceptance('Acceptance | imagemin');
test('Image files are compressed', function(assert) {
assert.expect(3);
visit('/');
andThen(function() {
// Compare the Content-Length of each image against the original
// file size. Dummy app is setup to enable compression, so the
// file sizes should be smaller.
Object.keys(uncompressedSizes).forEach((ext) => {
const url = `/logo.${ext}`;
const uncompressedSize = uncompressedSizes[ext];
$.get(url).then((data, status, xhr) => {
const compressedSize = parseInt(xhr.getResponseHeader('Content-Length'), 10);
assert.ok(compressedSize < uncompressedSize);
});
});
});
});
|
Adjust pending survey table query
|
<?php
namespace App\Http\Livewire;
use App\Models\TestDate;
use Illuminate\Database\Eloquent\Builder;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;
class PendingSurveysTable extends DataTableComponent
{
public string $defaultSortColumn = 'test_date';
public string $defaultSortDirection = 'asc';
public bool $singleColumnSorting = false;
public bool $paginationEnabled = false;
public bool $showSearch = false;
public function columns(): array
{
return [
Column::make('Survey ID', 'id')
->sortable(),
Column::make('Description', 'machine.description'),
Column::make('Date scheduled', 'test_date')
->sortable(),
Column::make('Test Type', 'type.test_type'),
Column::make('Accession'),
Column::make('Survey Note'),
];
}
public function rowView(): string
{
return 'livewire-tables.pending-surveys-row';
}
public function query(): Builder
{
return TestDate::query()
->with('machine', 'type')
->pending();
}
}
|
<?php
namespace App\Http\Livewire;
use App\Models\TestDate;
use Illuminate\Database\Eloquent\Builder;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;
class PendingSurveysTable extends DataTableComponent
{
public string $defaultSortColumn = 'test_date';
public string $defaultSortDirection = 'asc';
public bool $singleColumnSorting = false;
public bool $paginationEnabled = false;
public bool $showSearch = false;
public function columns(): array
{
return [
Column::make('Survey ID', 'id')
->sortable(),
Column::make('Description', 'machine.description'),
Column::make('Date scheduled', 'test_date')
->sortable(),
Column::make('Test Type', 'type.test_type'),
Column::make('Accession'),
Column::make('Survey Note'),
];
}
public function rowView(): string
{
return 'livewire-tables.pending-surveys-row';
}
public function query(): Builder
{
return TestDate::with('machine', 'type')
->pending();
}
}
|
Change custom data type to Map<String, Object>
|
package com.stormpath.sdk.models;
import com.squareup.moshi.Json;
import java.io.Serializable;
import java.util.Map;
public class UserProfile implements Serializable {
@Json(name = "email")
private String email;
@Json(name = "givenName")
private String givenName;
@Json(name = "middleName")
private String middleName;
@Json(name = "surname")
private String surname;
@Json(name = "fullName")
private String fullName;
@Json(name = "status")
private String status;
@Json(name = "username")
private String username;
@Json(name = "customData")
private Map<String, Object> customData;
public String getEmail() {
return email;
}
public String getGivenName() {
return givenName;
}
public String getMiddleName() {
return middleName;
}
public String getSurname() {
return surname;
}
public String getFullName() {
return fullName;
}
public String getStatus() {
return status;
}
public String getUsername() {
return username;
}
public Map<String, Object> getCustomData() {
return customData;
}
}
|
package com.stormpath.sdk.models;
import com.squareup.moshi.Json;
import java.io.Serializable;
import java.util.Map;
public class UserProfile implements Serializable {
@Json(name = "email")
private String email;
@Json(name = "givenName")
private String givenName;
@Json(name = "middleName")
private String middleName;
@Json(name = "surname")
private String surname;
@Json(name = "fullName")
private String fullName;
@Json(name = "status")
private String status;
@Json(name = "username")
private String username;
@Json(name = "customData")
private Map<String, String> customData;
public String getEmail() {
return email;
}
public String getGivenName() {
return givenName;
}
public String getMiddleName() {
return middleName;
}
public String getSurname() {
return surname;
}
public String getFullName() {
return fullName;
}
public String getStatus() {
return status;
}
public String getUsername() {
return username;
}
public Map<String, String> getCustomData() {
return customData;
}
}
|
Add ESLint rule for space-before-function-paren
|
module.exports = {
"parserOptions": {
"ecmaVersion": 8
},
"env": {
"browser": false,
"node": true,
"commonjs": true,
"es6": true,
"mocha": true
},
"extends": "eslint:recommended",
"rules": {
"no-console": 0,
"indent": [
"error",
4
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"space-before-function-paren": [
"error",
{"anonymous": "always", "named": "never"}
],
"max-len": [
"error",
120
]
}
};
|
module.exports = {
"parserOptions": {
"ecmaVersion": 8
},
"env": {
"browser": false,
"node": true,
"commonjs": true,
"es6": true,
"mocha": true
},
"extends": "eslint:recommended",
"rules": {
"no-console": 0,
"indent": [
"error",
4
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"max-len": [
"error",
120
]
}
};
|
Fix the issue as OnInit is no longer a pointer
|
package mongo
import (
"errors"
"fmt"
"golang.org/x/net/context"
"github.com/rs/rest-layer/schema"
"gopkg.in/mgo.v2/bson"
)
var (
// NewObjectID is a field hook handler that generates a new Mongo ObjectID hex if
// value is nil to be used in schema with OnInit.
NewObjectID = func(ctx context.Context, value interface{}) interface{} {
if value == nil {
value = bson.NewObjectId().Hex()
}
return value
}
// ObjectIDField is a common schema field configuration that generate an Object ID
// for new item id.
ObjectIDField = schema.Field{
Required: true,
ReadOnly: true,
OnInit: NewObjectID,
Filterable: true,
Sortable: true,
Validator: &ObjectID{},
}
)
// ObjectID validates and serialize unique id
type ObjectID struct{}
// Validate implements FieldValidator interface
func (v ObjectID) Validate(value interface{}) (interface{}, error) {
s, ok := value.(string)
if !ok {
return nil, errors.New("invalid object id")
}
if len(s) != 24 {
return nil, errors.New("invalid object id length")
}
if !bson.IsObjectIdHex(s) {
return nil, fmt.Errorf("invalid object id")
}
return bson.ObjectIdHex(s), nil
}
|
package mongo
import (
"errors"
"fmt"
"golang.org/x/net/context"
"github.com/rs/rest-layer/schema"
"gopkg.in/mgo.v2/bson"
)
var (
// NewObjectID is a field hook handler that generates a new Mongo ObjectID hex if
// value is nil to be used in schema with OnInit.
NewObjectID = func(ctx context.Context, value interface{}) interface{} {
if value == nil {
value = bson.NewObjectId().Hex()
}
return value
}
// ObjectIDField is a common schema field configuration that generate an Object ID
// for new item id.
ObjectIDField = schema.Field{
Required: true,
ReadOnly: true,
OnInit: &NewObjectID,
Filterable: true,
Sortable: true,
Validator: &ObjectID{},
}
)
// ObjectID validates and serialize unique id
type ObjectID struct{}
// Validate implements FieldValidator interface
func (v ObjectID) Validate(value interface{}) (interface{}, error) {
s, ok := value.(string)
if !ok {
return nil, errors.New("invalid object id")
}
if len(s) != 24 {
return nil, errors.New("invalid object id length")
}
if !bson.IsObjectIdHex(s) {
return nil, fmt.Errorf("invalid object id")
}
return bson.ObjectIdHex(s), nil
}
|
Fix typo breaking the TS6 feature.
|
from merc import errors
from merc import feature
from merc import message
from merc import util
class SidFeature(feature.Feature):
NAME = __name__
install = SidFeature.install
@SidFeature.register_server_command
class Sid(message.Command):
NAME = "SID"
MIN_ARITY = 4
def __init__(self, server_name, hopcount, sid, description, *args):
self.server_name = server_name
self.hopcount = hopcount
self.sid = sid
self.description = description
def as_command_params(self):
return [self.server_name, self.hopcount, self.sid, self.description]
def handle_for(self, app, server, prefix):
# TODO: handle me!
pass
@SidFeature.hook("network.burst.sid")
def burst_sids(app, server):
for source, target in app.network.all_links():
server.send(source.sid, Sid(target.name, "1", target.sid,
target.description))
|
from merc import errors
from merc import feature
from merc import message
from merc import util
class SidFeature(feature.Feature):
NAME = __name__
install = SidFeature.install
@SidFeature.register_server_command
class Sid(message.Command):
NAME = "SID"
MIN_ARITY = 4
def __init__(self, server_name, hopcount, sid, description, *args):
self.server_name = server_name
self.hopcount = hopcount
self.sid = sid
self.description = description
def as_command_params(self):
return [self.server_name, self.hopcount, self.sid, self.description]
def handle_for(self, app, server, prefix):
# TODO: handle me!
@SidFeature.hook("network.burst.sid")
def burst_sids(app, server):
for source, target in app.network.all_links():
server.send(source.sid, Sid(target.name, "1", target.sid,
target.description))
|
Fix silly bug where non-empty argument lists didn't work.
|
/* © 2012 David Given
* This file is made available under the terms of the two-clause BSD
* license. See the file COPYING in the distribution directory for the
* full license text.
*/
package com.cowlark.cowbel.parser.parsers;
import com.cowlark.cowbel.parser.core.Location;
import com.cowlark.cowbel.parser.core.ParseResult;
public class ArgumentListParser extends Parser
{
@Override
protected ParseResult parseImpl(Location location)
{
ParseResult pr = OpenParenthesisParser.parse(location);
if (pr.failed())
return pr;
ParseResult argumentspr = ExpressionListParser.parse(pr.end());
if (argumentspr.failed())
return argumentspr;
pr = CloseParenthesisParser.parse(argumentspr.end());
if (pr.failed())
return pr;
/* Very nasty */
argumentspr.setEnd(pr.end());
return argumentspr;
}
}
|
/* © 2012 David Given
* This file is made available under the terms of the two-clause BSD
* license. See the file COPYING in the distribution directory for the
* full license text.
*/
package com.cowlark.cowbel.parser.parsers;
import com.cowlark.cowbel.parser.core.Location;
import com.cowlark.cowbel.parser.core.ParseResult;
public class ArgumentListParser extends Parser
{
@Override
protected ParseResult parseImpl(Location location)
{
ParseResult pr = OpenParenthesisParser.parse(location);
if (pr.failed())
return pr;
ParseResult argumentspr = ExpressionListParser.parse(pr.end());
if (argumentspr.failed())
return argumentspr;
pr = CloseParenthesisParser.parse(pr.end());
if (pr.failed())
return pr;
/* Very nasty */
argumentspr.setEnd(pr.end());
return argumentspr;
}
}
|
Fix paste event for IE
|
import lists from '../core/lists';
export default class Clipboard {
constructor(context) {
this.context = context;
this.$editable = context.layoutInfo.editable;
}
initialize() {
this.$editable.on('paste', this.pasteByEvent.bind(this));
}
/**
* paste by clipboard event
*
* @param {Event} event
*/
pasteByEvent(event) {
const clipboardData = event.originalEvent.clipboardData;
if (clipboardData && clipboardData.items && clipboardData.items.length) {
const item = clipboardData.items.length > 1 ? clipboardData.items[1] : lists.head(clipboardData.items);
if (item.kind === 'file' && item.type.indexOf('image/') !== -1) {
// paste img file
this.context.invoke('editor.insertImagesOrCallback', [item.getAsFile()]);
} else if (item.kind === 'string') {
// paste text with maxTextLength check
if (this.context.invoke('editor.isLimited', clipboardData.getData('Text').length)) {
event.preventDefault();
}
}
} else if (window.clipboardData) {
// for IE
let text = window.clipboardData.getData('text');
if (this.context.invoke('editor.isLimited', text.length)) {
event.preventDefault();
}
}
this.context.invoke('editor.afterCommand');
}
}
|
import lists from '../core/lists';
export default class Clipboard {
constructor(context) {
this.context = context;
this.$editable = context.layoutInfo.editable;
}
initialize() {
this.$editable.on('paste', this.pasteByEvent.bind(this));
}
/**
* paste by clipboard event
*
* @param {Event} event
*/
pasteByEvent(event) {
const clipboardData = event.originalEvent.clipboardData;
if (clipboardData && clipboardData.items && clipboardData.items.length) {
const item = clipboardData.items.length > 1 ? clipboardData.items[1] : lists.head(clipboardData.items);
if (item.kind === 'file' && item.type.indexOf('image/') !== -1) {
// paste img file
this.context.invoke('editor.insertImagesOrCallback', [item.getAsFile()]);
this.context.invoke('editor.afterCommand');
} else if (item.kind === 'string') {
// paste text with maxTextLength check
if (this.context.invoke('editor.isLimited', clipboardData.getData('Text').length)) {
event.preventDefault();
} else {
this.context.invoke('editor.afterCommand');
}
}
}
}
}
|
nir: Remove spurious ; after nir_builder functions.
Makes -pedantic happy.
Reviewed-by: Connor Abbott <71178acffcc112b21e5858656e5751f5e4aa9364@gmail.com>
|
#! /usr/bin/env python
template = """\
/* Copyright (C) 2015 Broadcom
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef _NIR_BUILDER_OPCODES_
#define _NIR_BUILDER_OPCODES_
% for name, opcode in sorted(opcodes.iteritems()):
ALU${opcode.num_inputs}(${name})
% endfor
#endif /* _NIR_BUILDER_OPCODES_ */"""
from nir_opcodes import opcodes
from mako.template import Template
print Template(template).render(opcodes=opcodes)
|
#! /usr/bin/env python
template = """\
/* Copyright (C) 2015 Broadcom
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef _NIR_BUILDER_OPCODES_
#define _NIR_BUILDER_OPCODES_
% for name, opcode in sorted(opcodes.iteritems()):
ALU${opcode.num_inputs}(${name});
% endfor
#endif /* _NIR_BUILDER_OPCODES_ */"""
from nir_opcodes import opcodes
from mako.template import Template
print Template(template).render(opcodes=opcodes)
|
Fix little glitch in project list when there is no icon
|
<div class="table-list-icons">
<?php if ($project['is_public']): ?>
<i class="fa fa-share-alt fa-fw" title="<?= t('Shared project') ?>"></i>
<?php endif ?>
<?php if ($project['is_private']): ?>
<i class="fa fa-lock fa-fw" title="<?= t('Private project') ?>"></i>
<?php endif ?>
<?php if ($this->user->hasAccess('ProjectUserOverviewController', 'managers')): ?>
<span class="tooltip" title="<?= t('Members') ?>" data-href="<?= $this->url->href('ProjectUserOverviewController', 'users', array('project_id' => $project['id'])) ?>"><i class="fa fa-users"></i></span>
<?php endif ?>
<?php if (! empty($project['description'])): ?>
<span class="tooltip" title="<?= $this->text->markdownAttribute($project['description']) ?>">
<i class="fa fa-info-circle"></i>
</span>
<?php endif ?>
<?php if ($project['is_active'] == 0): ?>
<i class="fa fa-ban fa-fw" aria-hidden="true" title="<?= t('Closed') ?>"></i><?= t('Closed') ?>
<?php endif ?>
</div>
|
<div class="table-list-icons">
<?php if ($project['is_public']): ?>
<i class="fa fa-share-alt fa-fw" title="<?= t('Shared project') ?>"></i>
<?php endif ?>
<?php if ($project['is_private']): ?>
<i class="fa fa-lock fa-fw" title="<?= t('Private project') ?>"></i>
<?php endif ?>
<?php if ($this->user->hasAccess('ProjectUserOverviewController', 'managers')): ?>
<span class="tooltip" title="<?= t('Members') ?>" data-href="<?= $this->url->href('ProjectUserOverviewController', 'users', array('project_id' => $project['id'])) ?>"><i class="fa fa-users"></i></span>
<?php endif ?>
<?php if (! empty($project['description'])): ?>
<span class="tooltip" title="<?= $this->text->markdownAttribute($project['description']) ?>">
<i class="fa fa-info-circle"></i>
</span>
<?php endif ?>
<?php if ($project['is_active'] == 0): ?>
<i class="fa fa-ban fa-fw" aria-hidden="true" title="<?= t('Closed') ?>"></i><?= t('Closed') ?>
<?php endif ?>
</div>
|
Set no embed-codes option for multi-page-test-project
|
var gulp = require('gulp');
var defs = [
{
title: 'Test Index Title',
path: '',
description: 'Test index description',
twitterImage: '20euro.png',
openGraphImage: '50euro.png',
schemaImage: '100euro.png'
},
{
path: '/subpage',
title: 'Test Subpage Title',
description: 'Test subpage description',
twitterImage: '100euro.png',
openGraphImage: '50euro.png',
schemaImage: '20euro.png'
}
];
var opts = {
paths: ['node_modules/lucify-commons', 'test_modules/module1'],
publishFromFolder: 'dist',
assetContext: 'test-path/',
pageDefs: defs,
embedCodes: false,
iframeResize: false
}
var builder = require('../../index.js'); // lucify-component-builder
builder(gulp, opts);
|
var gulp = require('gulp');
var defs = [
{
title: 'Test Index Title',
path: '',
description: 'Test index description',
twitterImage: '20euro.png',
openGraphImage: '50euro.png',
schemaImage: '100euro.png'
},
{
path: '/subpage',
title: 'Test Subpage Title',
description: 'Test subpage description',
twitterImage: '100euro.png',
openGraphImage: '50euro.png',
schemaImage: '20euro.png'
}
];
var opts = {
paths: ['node_modules/lucify-commons', 'test_modules/module1'],
publishFromFolder: 'dist',
assetContext: 'test-path/',
pageDefs: defs
}
var builder = require('../../index.js'); // lucify-component-builder
builder(gulp, opts);
|
Add validation to logout request
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Vincent Zhang/PhoenixLAB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package co.phoenixlab.discord.api.request;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.NotEmpty;
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class LogoutRequest {
@NotEmpty
private String token;
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Vincent Zhang/PhoenixLAB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package co.phoenixlab.discord.api.request;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class LogoutRequest {
private String token;
}
|
Revert to string based class name because of PHP 5.4 support
|
<?php
/*
* This file is part of the Indigo Guardian package.
*
* (c) Indigo Development Team
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Indigo\Guardian\Authenticator;
use BeatSwitch\Lock\Callers\Caller;
use Assert\Assertion;
/**
* Authenticate using a username-password pair
*
* @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
*/
class UserPassword extends HasherAware
{
/**
* {@inheritdoc}
*/
public function authenticate(array $subject, Caller $caller)
{
Assertion::choicesNotEmpty($subject, ['password']);
Assertion::isInstanceOf(
$caller,
'Indigo\Guardian\Caller\User',
sprintf('The caller was expected to be an instance of "%s"', 'Indigo\Guardian\Caller\User')
);
return $this->hasher->verify($subject['password'], $caller->getPassword());
}
}
|
<?php
/*
* This file is part of the Indigo Guardian package.
*
* (c) Indigo Development Team
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Indigo\Guardian\Authenticator;
use BeatSwitch\Lock\Callers\Caller;
use Indigo\Guardian\Caller\User;
use Assert\Assertion;
/**
* Authenticate using a username-password pair
*
* @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
*/
class UserPassword extends HasherAware
{
/**
* {@inheritdoc}
*/
public function authenticate(array $subject, Caller $caller)
{
Assertion::choicesNotEmpty($subject, ['password']);
Assertion::isInstanceOf(
$caller,
User::CLASS,
sprintf('The caller was expected to be an instance of "%s"', User::CLASS)
);
return $this->hasher->verify($subject['password'], $caller->getPassword());
}
}
|
Use correct fields for address formatting
|
<?php
namespace HbgEventImporter;
class Location extends \HbgEventImporter\Entity\PostManager
{
public $post_type = 'location';
public function afterSave()
{
$res = Helper\Address::gmapsGetAddressComponents($this->postal_address . ' ' . $this->postal_code . ' ' . $this->city . ' ' . $this->country);
if (!isset($res->geometry->location)) {
return;
}
update_post_meta($this->ID, 'map', array(
'address' => $res->formatted_address,
'lat' => $res->geometry->location->lat,
'lng' => $res->geometry->location->lng
));
update_post_meta($this->ID, 'formatted_address', $res->formatted_address);
}
}
|
<?php
namespace HbgEventImporter;
class Location extends \HbgEventImporter\Entity\PostManager
{
public $post_type = 'location';
public function afterSave()
{
$res = Helper\Address::gmapsGetAddressComponents($this->postalAddress . ' ' . $this->postcode . ' ' . $this->city . ' ' . $this->country);
if (!isset($res->geometry->location)) {
return;
}
update_post_meta($this->ID, 'map', array(
'address' => $res->formatted_address,
'lat' => $res->geometry->location->lat,
'lng' => $res->geometry->location->lng
));
update_post_meta($this->ID, 'formatted_address', $res->formatted_address);
}
}
|
Add tray minimize, restore and quit
|
import path from 'path';
import os from 'os';
import { Tray, Menu } from 'electron';
export default function buildTray(win) {
const PLATFORM = os.platform();
let icon;
if (process.env.NODE_ENV === 'development') {
icon = PLATFORM === 'darwin' || PLATFORM === 'linux'
? path.join(__dirname, '../../assets/images/icon-mac@2x.png')
: path.join(__dirname, '../../assets/images/icon-windows@2x.png');
} else {
icon = PLATFORM === 'darwin' || PLATFORM === 'linux'
? path.join(__dirname, 'assets/images/icon-mac@2x.png')
: path.join(__dirname, 'assets/images/icon-windows@2x.png');
}
const trayMenu = Menu.buildFromTemplate([
{
label: 'ZenFocus',
click() {
win.show();
}
},
{
label: 'Minimize to tray',
click() {
win.hide();
}
},
{ type: 'separator' },
{
label: 'Quit',
click() {
win.close();
}
}
]);
const tray = new Tray(icon);
tray.setToolTip('ZenFocus');
tray.setContextMenu(trayMenu);
tray.on('double-click', () => win.show());
return tray;
}
|
import path from 'path';
import os from 'os';
import { Tray } from 'electron';
export default function buildTray(win) {
const PLATFORM = os.platform();
let icon;
if (process.env.NODE_ENV === 'development') {
icon = PLATFORM === 'darwin' || PLATFORM === 'linux'
? path.join(__dirname, '../../assets/images/icon-mac@2x.png')
: path.join(__dirname, '../../assets/images/icon-windows@2x.png');
} else {
icon = PLATFORM === 'darwin' || PLATFORM === 'linux'
? path.join(__dirname, 'assets/images/icon-mac@2x.png')
: path.join(__dirname, 'assets/images/icon-windows@2x.png');
}
const tray = new Tray(icon);
tray.on('click', () => win.isVisible() ? win.hide() : win.show());
return tray;
}
|
Make op address and child addresses mutable
|
package org.cf.smalivm.opcode;
import org.cf.smalivm.SideEffect;
public abstract class Op {
private int address;
private int[] childAddresses;
private final String opName;
Op(int address, String opName, int childAddress) {
this(address, opName, new int[] { childAddress });
}
Op(int address, String opName, int[] childAddresses) {
this.address = address;
this.opName = opName;
this.childAddresses = childAddresses;
}
public final int getAddress() {
return address;
}
public final String getName() {
return opName;
}
public final int[] getPossibleChildren() {
return childAddresses;
}
public SideEffect.Level sideEffectLevel() {
return SideEffect.Level.NONE;
}
public void setAddress(int address) {
this.address = address;
}
public void setPossibleChildren(int[] childAddresses) {
this.childAddresses = childAddresses;
}
@Override
public abstract String toString();
}
|
package org.cf.smalivm.opcode;
import org.cf.smalivm.SideEffect;
public abstract class Op {
private final int address;
private final int[] childAddresses;
private final String opName;
Op(int address, String opName, int childAddress) {
this(address, opName, new int[] { childAddress });
}
Op(int address, String opName, int[] childAddresses) {
this.address = address;
this.opName = opName;
this.childAddresses = childAddresses;
}
public final int getAddress() {
return address;
}
public final String getName() {
return opName;
}
public final int[] getPossibleChildren() {
return childAddresses;
}
public SideEffect.Level sideEffectLevel() {
return SideEffect.Level.NONE;
}
@Override
public abstract String toString();
}
|
Add error handling to user events
|
var express = require('express');
var DataStore = require('./regard-data-store.js');
var router = express.Router();
var dataStore = new DataStore('regard', 'website');
router.get('/userevents/:id', function (req, res, next) {
var id = req.params.id;
dataStore.getEventsForUser(id).then(function (events) {
res.json({
userevents: [{
_id: id,
events: JSON.parse(events)
}]
});
}, next);
});
router.post('/userevents/:id/delete-data', function (req, res, next) {
var id = req.params.id;
dataStore.deleteData(id).then(function () {
res.send(200);
}, next);
});
module.exports = router;
|
var express = require('express');
var DataStore = require('./regard-data-store.js');
var router = express.Router();
var dataStore = new DataStore('regard', 'website');
router.get('/userevents/:id', function (req, res, next) {
var id = req.params.id;
dataStore.getEventsForUser(id).then(function (events) {
res.json({
userevents: [{
_id: id,
events: JSON.parse(events)
}]
});
});
});
router.post('/userevents/:id/delete-data', function (req, res, next) {
var id = req.params.id;
dataStore.deleteData(id).then(function () {
res.send(200);
}, next);
});
module.exports = router;
|
Fix 'put is not a command' error on static commands
|
"""List drivers and send them commands."""
import logging
import flask
from appengine import device, rest
class Query(object):
def iter(self):
for name, cls in device.DEVICE_TYPES.iteritems():
yield Driver(name, cls)
class Driver(object):
"""This is a fake for compatibility with the rest module"""
def __init__(self, name, cls):
self._name = name
self._cls = cls
def to_dict(self):
return {'name': self._name}
# This is a trampoline through to the driver
# mainly for commands
def __getattr__(self, name):
func = getattr(self._cls, name)
if func is None or not getattr(func, 'is_static', False):
logging.error('Command %s does not exist or is not a static command',
name)
flask.abort(400)
return func
@staticmethod
def put():
pass
@staticmethod
def query():
return Query()
@staticmethod
def get_by_id(_id):
return Driver(_id, device.DEVICE_TYPES[_id])
# pylint: disable=invalid-name
blueprint = flask.Blueprint('driver', __name__)
rest.register_class(blueprint, Driver, None)
|
"""List drivers and send them commands."""
import logging
import flask
from appengine import device, rest
class Query(object):
def iter(self):
for name, cls in device.DEVICE_TYPES.iteritems():
yield Driver(name, cls)
class Driver(object):
"""This is a fake for compatibility with the rest module"""
def __init__(self, name, cls):
self._name = name
self._cls = cls
def to_dict(self):
return {'name': self._name}
# This is a trampoline through to the driver
# mainly for commands
def __getattr__(self, name):
func = getattr(self._cls, name)
if func is None or not getattr(func, 'is_static', False):
logging.error('Command %s does not exist or is not a static command',
name)
flask.abort(400)
return func
@staticmethod
def query():
return Query()
@staticmethod
def get_by_id(_id):
return Driver(_id, device.DEVICE_TYPES[_id])
# pylint: disable=invalid-name
blueprint = flask.Blueprint('driver', __name__)
rest.register_class(blueprint, Driver, None)
|
Update for new jar and dynamic demo
|
<?php
require_once "../StyleJS/json/JSON.php";
$json = new Services_JSON();
$url1 = $_GET["url1"];
$url2 = $_GET["url2"];
$type = $_GET["type"];
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w")
);
if($type == 1)
{
$config="config_image.xml";
}
elseif($type == 2)
{
$config="config_content.xml";
}
else
{
$config="config_hybrid.xml";
}
$cmd = "java -jar Pagelyzer-0.0.1-SNAPSHOT-jar-with-dependencies.jar -url1 ".$url1." -url2 ".$url2." -config ".$config." 2>&1";
$p=proc_open ($cmd, $descriptorspec, $pipes);
$out = stream_get_contents($pipes[1]) ;
$out2 = $json->encode($out);
$parts = explode('\n', $out2);
$output = array();
for ($i = 1; $i < sizeof($parts); $i++) {
$output[] = $json->encode($parts[$i]);
}
echo json_encode($output);
proc_close($p);
?>
|
<?php
$url1 = $_GET["url1"];
$url2 = $_GET["url2"];
$type = $_GET["type"];
$pagelyze="DISPLAY=:98 java -jar /var/lib/pagelyzer/jPagelyzer.jar -get score -cmode ";
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w")
);
if($type == 1)
{
$cmd = $pagelyze."images -url1 ".$url1." -url2 ".$url2." 2>&1";
}
elseif($type == 2)
{
$cmd = $pagelyze."structure -url1 ".$url1." -url2 ".$url2." 2>&1";
}
else
{
$cmd = $pagelyze."hybrid -url1 ".$url1." -url2 ".$url2." 2>&1";
}
$p=proc_open ($cmd, $descriptorspec, $pipes);
$out = stream_get_contents($pipes[1]) ;
$out2 = json_encode($out);
$parts = explode('\n', $out2);
$result = json_encode($parts[sizeof($parts)-2]);
print($result);
proc_close($p);
?>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.