text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Update example to use more terse "-loader"-less format
|
import NpmInstallPlugin from "npm-install-webpack-plugin";
import path from "path";
export const defaults = {
context: process.cwd(),
externals: [],
module: {
loaders: [
{ test: /\.css$/, loader: "style" },
{ test: /\.css$/, loader: "css", query: { localIdentName: "[name]-[local]--[hash:base64:5]" } },
{ test: /\.eot$/, loader: "file" },
{ test: /\.js$/, loader: "babel", query: { cacheDirectory: true }, exclude: /node_modules/ },
{ test: /\.json$/, loader: "json" },
{ test: /\.(png|jpg)$/, loader: "url", query: { limit: 8192 } }, // Inline base64 URLs for <= 8K images
{ test: /\.svg$/, loader: "url", query: { mimetype: "image/svg+xml" } },
{ test: /\.ttf$/, loader: "url", query: { mimetype: "application/octet-stream" } },
{ test: /\.(woff|woff2)$/, loader: "url", query: { mimetype: "application/font-woff" } },
],
},
output: {
chunkFilename: "[id].[hash:5]-[chunkhash:7].js",
devtoolModuleFilenameTemplate: "[absolute-resource-path]",
filename: "[name].js",
},
plugins: [
new NpmInstallPlugin(),
],
};
|
import NpmInstallPlugin from "npm-install-webpack-plugin";
import path from "path";
export const defaults = {
context: process.cwd(),
externals: [],
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader" },
{ test: /\.css$/, loader: "css-loader", query: { localIdentName: "[name]-[local]--[hash:base64:5]" } },
{ test: /\.eot$/, loader: "file-loader" },
{ test: /\.js$/, loader: "babel-loader", query: { cacheDirectory: true }, exclude: /node_modules/ },
{ test: /\.json$/, loader: "json-loader" },
{ test: /\.(png|jpg)$/, loader: "url-loader", query: { limit: 8192 } }, // Inline base64 URLs for <= 8K images
{ test: /\.svg$/, loader: "url-loader", query: { mimetype: "image/svg+xml" } },
{ test: /\.ttf$/, loader: "url-loader", query: { mimetype: "application/octet-stream" } },
{ test: /\.(woff|woff2)$/, loader: "url-loader", query: { mimetype: "application/font-woff" } },
],
},
output: {
chunkFilename: "[id].[hash:5]-[chunkhash:7].js",
devtoolModuleFilenameTemplate: "[absolute-resource-path]",
filename: "[name].js",
},
plugins: [
new NpmInstallPlugin(),
],
};
|
Move the insertion to the class performing the action.
|
import NodePatcher from './../../../patchers/NodePatcher.js';
import type { Editor, Node, ParseContext } from './../../../patchers/types.js';
export default class ArrayInitialiserPatcher extends NodePatcher {
constructor(node: Node, context: ParseContext, editor: Editor, members: Array<NodePatcher>) {
super(node, context, editor);
this.members = members;
}
initialize() {
this.members.forEach(member => member.setRequiresExpression());
}
patchAsExpression() {
this.members.forEach((member, i, members) => {
let isLast = i === members.length - 1;
let needsComma = !isLast && !member.hasTokenAfter(',');
member.patch();
if (needsComma) {
this.insert(member.after, ',');
}
});
}
patchAsStatement() {
this.patchAsExpression();
}
}
|
import NodePatcher from './../../../patchers/NodePatcher.js';
import type { Editor, Node, ParseContext } from './../../../patchers/types.js';
export default class ArrayInitialiserPatcher extends NodePatcher {
constructor(node: Node, context: ParseContext, editor: Editor, members: Array<NodePatcher>) {
super(node, context, editor);
this.members = members;
}
initialize() {
this.members.forEach(member => member.setRequiresExpression());
}
patchAsExpression() {
this.members.forEach((member, i, members) => {
let isLast = i === members.length - 1;
let needsComma = !isLast && !member.hasTokenAfter(',');
member.patch();
if (needsComma) {
member.insertAfter(',');
}
});
}
patchAsStatement() {
this.patchAsExpression();
}
}
|
Add more exemplar primitive generators
|
from .context import tohu
from tohu.v4.primitive_generators import *
from tohu.v4.derived_generators import *
__all__ = ['EXEMPLAR_GENERATORS', 'EXEMPLAR_PRIMITIVE_GENERATORS', 'EXEMPLAR_DERIVED_GENERATORS']
def add(x, y):
return x + y
EXEMPLAR_PRIMITIVE_GENERATORS = [
Boolean(p=0.3),
Constant("quux"),
FakerGenerator(method="name"),
Float(12.34, 56.78),
HashDigest(length=6),
Integer(100, 200),
IterateOver('abcdefghijklmnopqrstuvwxyz'),
SelectOne('abcdefghijklmnopqrstuvwxyz'),
SelectOne('abcde', p=[0.1, 0.05, 0.7, 0.03, 0.12]),
Timestamp(date='2018-01-01'),
]
EXEMPLAR_DERIVED_GENERATORS = [
Apply(add, Integer(100, 200), Integer(300, 400)),
Apply(add, Apply(add, Integer(100, 200), Integer(300, 400)), Apply(add, Integer(500, 600), Integer(700, 800))),
]
EXEMPLAR_CUSTOM_GENERATORS = []
EXEMPLAR_GENERATORS = EXEMPLAR_PRIMITIVE_GENERATORS + EXEMPLAR_DERIVED_GENERATORS + EXEMPLAR_CUSTOM_GENERATORS
|
from .context import tohu
from tohu.v4.primitive_generators import *
from tohu.v4.derived_generators import *
__all__ = ['EXEMPLAR_GENERATORS', 'EXEMPLAR_PRIMITIVE_GENERATORS', 'EXEMPLAR_DERIVED_GENERATORS']
def add(x, y):
return x + y
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Integer(100, 200),
HashDigest(length=6),
FakerGenerator(method="name"),
IterateOver('abcdefghijklmnopqrstuvwxyz'),
SelectOne('abcdefghijklmnopqrstuvwxyz'),
SelectOne('abcde', p=[0.1, 0.05, 0.7, 0.03, 0.12]),
Timestamp(date='2018-01-01'),
]
EXEMPLAR_DERIVED_GENERATORS = [
Apply(add, Integer(100, 200), Integer(300, 400)),
Apply(add, Apply(add, Integer(100, 200), Integer(300, 400)), Apply(add, Integer(500, 600), Integer(700, 800))),
]
EXEMPLAR_CUSTOM_GENERATORS = []
EXEMPLAR_GENERATORS = EXEMPLAR_PRIMITIVE_GENERATORS + EXEMPLAR_DERIVED_GENERATORS + EXEMPLAR_CUSTOM_GENERATORS
|
Use reference list to print fibonacci series in command.
|
<?php
namespace Storo\Command;
use Storo\Math\Fibonacci;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class FibonacciCommand extends Command
{
protected function configure()
{
$this
->setName('storo:fibonacci')
->setDescription('Prints `howMany` fibonacci series.')
->addArgument(
'howMany',
InputArgument::OPTIONAL,
'',
10
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$howMany = $input->getArgument('howMany', 10);
$fibonacci = new Fibonacci();
$result = $fibonacci->recursive($howMany, $list);
$list = implode(', ', $list);
$output->writeln("<info>Result:</info> {$list}.");
}
}
|
<?php
namespace Storo\Command;
use Storo\Math\Fibonacci;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class FibonacciCommand extends Command
{
protected function configure()
{
$this
->setName('storo:fibonacci')
->setDescription('Prints `howMany` fibonacci series.')
->addArgument(
'howMany',
InputArgument::OPTIONAL,
'',
10
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$howMany = $input->getArgument('howMany', 10);
$fibonacci = new Fibonacci();
$output->write("<info>Result: </info>");
for ($i=1; $i <= $howMany; $i++) {
$result = $fibonacci->recursive($i);
$output->write($result . ' ');
}
$output->write("\n");
}
}
|
Add ability to specify a function instead of a string for dynamic configs
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-docker-config',
contentFor: function(type, config) {
if (type === 'head') {
return '<script type="text/javascript">window.DynamicENV = ' +
this.dynamicConfig(config.DynamicConfig) +
';</script>';
}
},
dynamicConfig: function(config) {
var param;
if (!config) {
return '';
}
var configParams = [];
for (param in config) {
switch (typeof config[param]) {
case 'object':
configParams.push('"' + param + '": ' + this.dynamicConfig(config[param]));
break;
case 'string':
if (process.env[config[param]]) {
configParams.push('"' + param + '": "' + process.env[config[param]] + '"');
}
break;
case 'function':
configParams.push('"' + param + '": "' + config[param](process.env) + '"');
break;
}
}
return '{' + configParams.join(',') + '}';
}
};
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-docker-config',
contentFor: function(type, config) {
if (type === 'head') {
return '<script type="text/javascript">window.DynamicENV = ' +
this.dynamicConfig(config.DynamicConfig) +
';</script>';
}
},
dynamicConfig: function(config) {
var param;
if (!config) {
return '';
}
var configParams = [];
for (param in config) {
if (typeof config[param] === 'object') {
configParams.push('"' + param + '": ' + this.dynamicConfig(config[param]));
} else {
if (process.env[config[param]]) {
configParams.push('"' + param + '": "' + process.env[config[param]] + '"');
}
}
}
return '{' + configParams.join(',') + '}';
}
};
|
Correct issue with "bindings" conduit attachment
Summary: Ref T13641. These conditions are swapped, and "activeBindings" loads more data than necessary while "bindings" doesn't load enough.
Test Plan: Called method with each attachment, got good results instead of an exception.
Maniphest Tasks: T13641
Differential Revision: https://secure.phabricator.com/D21657
|
<?php
final class AlmanacBindingsSearchEngineAttachment
extends AlmanacSearchEngineAttachment {
private $isActive;
public function setIsActive($is_active) {
$this->isActive = $is_active;
return $this;
}
public function getIsActive() {
return $this->isActive;
}
public function getAttachmentName() {
return pht('Almanac Bindings');
}
public function getAttachmentDescription() {
return pht('Get Almanac bindings for the service.');
}
public function willLoadAttachmentData($query, $spec) {
$query->needProperties(true);
if ($this->getIsActive()) {
$query->needActiveBindings(true);
} else {
$query->needBindings(true);
}
}
public function getAttachmentForObject($object, $data, $spec) {
$bindings = array();
if ($this->getIsActive()) {
$service_bindings = $object->getActiveBindings();
} else {
$service_bindings = $object->getBindings();
}
foreach ($service_bindings as $binding) {
$bindings[] = $this->getAlmanacBindingDictionary($binding);
}
return array(
'bindings' => $bindings,
);
}
}
|
<?php
final class AlmanacBindingsSearchEngineAttachment
extends AlmanacSearchEngineAttachment {
private $isActive;
public function setIsActive($is_active) {
$this->isActive = $is_active;
return $this;
}
public function getIsActive() {
return $this->isActive;
}
public function getAttachmentName() {
return pht('Almanac Bindings');
}
public function getAttachmentDescription() {
return pht('Get Almanac bindings for the service.');
}
public function willLoadAttachmentData($query, $spec) {
$query->needProperties(true);
if ($this->getIsActive()) {
$query->needBindings(true);
} else {
$query->needActiveBindings(true);
}
}
public function getAttachmentForObject($object, $data, $spec) {
$bindings = array();
if ($this->getIsActive()) {
$service_bindings = $object->getActiveBindings();
} else {
$service_bindings = $object->getBindings();
}
foreach ($service_bindings as $binding) {
$bindings[] = $this->getAlmanacBindingDictionary($binding);
}
return array(
'bindings' => $bindings,
);
}
}
|
Fix Invalid Variable + Session Leak
|
'use strict';
const Express = require('express');
const Proxy = require('express-http-proxy');
const Router = Express.Router();
const env = process.env;
/*
* Helpers, In-House Modules
*/
const hlp_health = require('../helper/healthcheck');
Router.get('/stats/api', (req, res, next) => {
hlp_health.http('xen-mid-rest', 4567, '/').then(() => {
res.sendStatus(200);
}).catch((err) => {
next(err);
});
});
Router.get('/stats/xen', (req, res, next) => {
hlp_health.https(env.XAPI_PATH, Number(env.XAPI_PORT), '/', true).then(() => {
res.sendStatus(200);
}).catch((err) => {
next(err);
});
});
module.exports = Router;
|
'use strict';
const Express = require('express');
const Proxy = require('express-http-proxy');
const Router = Express.Router();
const env = process.env;
/*
* Helpers, In-House Modules
*/
const hlp_health = require('../helper/healthcheck');
Router.get('/stats/api', (req, res, next) => {
hlp_health.http('xen-mid-rest', 80, '/').then(() => {
res.sendStatus(200);
}).catch((err) => {
next(err);
});
});
Router.get('/stats/xen', (req, res, next) => {
hlp_health.https(env.XAPI_PATH, Number(env.XAPI_PORT), '/', true).then(() => {
res.sendStatus(200);
}).catch((err) => {
next(err);
});
});
module.exports = Router;
|
Add test for getReplicantContext with zones enabled
|
package replicant;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class ConvergerTest
extends AbstractReplicantTest
{
@Test
public void construct_withUnnecessaryContext()
{
final ReplicantContext context = Replicant.context();
final IllegalStateException exception =
expectThrows( IllegalStateException.class, () -> Converger.create( context ) );
assertEquals( exception.getMessage(),
"Replicant-0124: SubscriptioConvergernService passed a context but Replicant.areZonesEnabled() is false" );
}
@Test
public void getReplicantContext()
{
final ReplicantContext context = Replicant.context();
final Converger converger = context.getConverger();
assertEquals( converger.getReplicantContext(), context );
assertEquals( getFieldValue( converger, "_context" ), null );
}
@Test
public void getReplicantContext_zonesEnabled()
{
ReplicantTestUtil.enableZones();
ReplicantTestUtil.resetState();
final ReplicantContext context = Replicant.context();
final Converger converger = context.getConverger();
assertEquals( converger.getReplicantContext(), context );
assertEquals( getFieldValue( converger, "_context" ), context );
}
}
|
package replicant;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class ConvergerTest
extends AbstractReplicantTest
{
@Test
public void construct_withUnnecessaryContext()
{
final ReplicantContext context = Replicant.context();
final IllegalStateException exception =
expectThrows( IllegalStateException.class, () -> Converger.create( context ) );
assertEquals( exception.getMessage(),
"Replicant-0124: SubscriptioConvergernService passed a context but Replicant.areZonesEnabled() is false" );
}
@Test
public void getReplicantContext()
{
final ReplicantContext context = Replicant.context();
final Converger converger = context.getConverger();
assertEquals( converger.getReplicantContext(), context );
assertEquals( getFieldValue( converger, "_context" ), null );
}
}
|
Mark websocket as external for webpack
|
const { resolve, join } = require("path");
const { IgnorePlugin } = require("webpack");
const path = require("path");
const moduleRoot = resolve(__dirname, "..");
const outputPath = join(moduleRoot, "dist");
module.exports = {
mode: "production",
entry: join(moduleRoot, "src", "index.js"),
target: "node",
devtool: "source-map",
output: {
path: outputPath,
filename: "index.js",
library: "truffle-hdwallet-provider",
libraryTarget: "umd",
umdNamedDefine: true
},
externals: ["fs", "bindings", "any-promise", "websocket"],
resolve: {
alias: {
// eth-block-tracker is es6 but automatically builds an es5 version for us on install. thanks eth-block-tracker!
"eth-block-tracker": "eth-block-tracker/dist/es5/index.js",
// replace native `scrypt` module with pure js `js-scrypt`
"scrypt": "js-scrypt",
// replace native `secp256k1` with pure js `elliptic.js`
"secp256k1": "secp256k1/elliptic.js",
}
},
plugins: [
// ignore these plugins completely
new IgnorePlugin(/^(?:electron|ws)$/)
]
};
|
const { resolve, join } = require("path");
const { IgnorePlugin } = require("webpack");
const path = require("path");
const moduleRoot = resolve(__dirname, "..");
const outputPath = join(moduleRoot, "dist");
module.exports = {
mode: "production",
entry: join(moduleRoot, "src", "index.js"),
target: "node",
devtool: "source-map",
output: {
path: outputPath,
filename: "index.js",
library: "truffle-hdwallet-provider",
libraryTarget: "umd",
umdNamedDefine: true
},
externals: ["fs", "bindings", "any-promise"],
resolve: {
alias: {
// eth-block-tracker is es6 but automatically builds an es5 version for us on install. thanks eth-block-tracker!
"eth-block-tracker": "eth-block-tracker/dist/es5/index.js",
// replace native `scrypt` module with pure js `js-scrypt`
"scrypt": "js-scrypt",
// replace native `secp256k1` with pure js `elliptic.js`
"secp256k1": "secp256k1/elliptic.js",
// fix websocket require path
"websocket": path.resolve(__dirname, "../")
}
},
plugins: [
// ignore these plugins completely
new IgnorePlugin(/^(?:electron|ws)$/)
]
};
|
Add another button for thumbnails
- btn sizes 250, 500, 800, 1200
|
<div class="row">
<div class="col-md-7"><img src="{{ url("/notes/img/$img?w=250") }}" alt="images"></div>
<div class="col-md-5 text-center">
<button data-src="{{url("/notes/img/$img?w=250")}}" type="button" class="btn btn-block add-image">
Thumbnail
</button>
<button data-src="{{url("/notes/img/$img?w=480")}}" type="button" class="btn btn-block add-image">
Small Photo
</button>
<button data-src="{{url("/notes/img/$img?w=800")}}" type="button" class="btn btn-block add-image">
Medium Photo
</button>
<button data-src="{{url("/notes/img/$img?w=1200")}}" type="button" class="btn btn-block add-image">
Large Photo
</button>
</div>
</div>
<hr>
|
<div class="row">
<div class="col-md-7"><img src="{{ url("/notes/img/$img?w=250") }}" alt="images"></div>
<div class="col-md-5 text-center">
<button data-src="{{url("/notes/img/$img?w=250")}}" type="button" class="btn btn-block add-image">
Small Photo
</button>
<button data-src="{{url("/notes/img/$img?w=500")}}" type="button" class="btn btn-block add-image">
Medium Photo
</button>
<button data-src="{{url("/notes/img/$img?w=800")}}" type="button" class="btn btn-block add-image">
Large Photo
</button>
</div>
</div>
<hr>
|
Add download URL for PyPI
|
#!/usr/bin/env python
# Author: Aziz Alto
# email: iamaziz.alto@gmail.com
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='pydataset',
description=("Provides instant access to many popular datasets right from "
"Python (in dataframe structure)."),
author='Aziz Alto',
url='https://github.com/iamaziz/PyDataset',
download_url='https://github.com/iamaziz/PyDataset/tarball/0.1.0',
license = 'MIT',
author_email='iamaziz.alto@gmail.com',
version='0.1.0',
install_requires=['pandas'],
packages=['pydataset', 'pydataset.utils'],
package_data={'pydataset': ['*.gz', 'resources.tar.gz']}
)
|
#!/usr/bin/env python
# Author: Aziz Alto
# email: iamaziz.alto@gmail.com
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='pydataset',
description=("Provides instant access to many popular datasets right from "
"Python (in dataframe structure)."),
author='Aziz Alto',
url='https://github.com/iamaziz/PyDataset',
download_url='https://github.com/iamaziz/PyDataset/archive/master.zip',
license = 'MIT',
author_email='iamaziz.alto@gmail.com',
version='0.1.0',
install_requires=['pandas'],
packages=['pydataset', 'pydataset.utils'],
package_data={'pydataset': ['*.gz', 'resources.tar.gz']}
)
|
Rewrite test so it tests the right thing.
Since both return values are now checked explicitly, remove check that
the concatinated package path matches the original input, since it
won't always (the point of this function is to normalize input).
|
package util
import (
"testing"
)
func TestNormalizeName(t *testing.T) {
packages := []struct {
input string
root string
extra string
}{
{
input: "github.com/Masterminds/cookoo/web/io/foo",
root: "github.com/Masterminds/cookoo",
extra: "web/io/foo",
},
{
input: `github.com\Masterminds\cookoo\web\io\foo`,
root: "github.com/Masterminds/cookoo",
extra: "web/io/foo",
},
{
input: "golang.org/x/crypto/ssh",
root: "golang.org/x/crypto",
extra: "ssh",
},
{
input: "incomplete/example",
root: "incomplete/example",
extra: "",
},
{
input: "net",
root: "net",
extra: "",
},
}
for _, test := range packages {
root, extra := NormalizeName(test.input)
switch {
case root != test.root:
t.Errorf("%s: Expected root '%s', got '%s'", test.input, test.root, root)
case extra != test.extra:
t.Errorf("%s: Expected extra '%s', got '%s'", test.input, test.extra, extra)
}
}
}
|
package util
import (
"testing"
)
func TestNormalizeName(t *testing.T) {
packages := map[string]string{
"github.com/Masterminds/cookoo/web/io/foo": "github.com/Masterminds/cookoo",
`github.com\Masterminds\cookoo\web\io\foo`: "github.com/Masterminds/cookoo",
"golang.org/x/crypto/ssh": "golang.org/x/crypto",
"incomplete/example": "incomplete/example",
"net": "net",
}
for start, expected := range packages {
if finish, extra := NormalizeName(start); expected != finish {
t.Errorf("Expected '%s', got '%s'", expected, finish)
} else if start != finish && start != finish+"/"+extra {
t.Errorf("Expected %s to end with %s", finish, extra)
}
}
}
|
Make examples build more verbose
|
var childProcess = require('child_process');
var fs = require('fs');
process.chdir('examples');
childProcess.execSync('npm install', { stdio: 'inherit' });
childProcess.execSync('npm run update', { stdio: 'inherit' });
process.chdir('..');
// Build all of the example folders.
dirs = fs.readdirSync('examples');
var cmd;
for (var i = 0; i < dirs.length; i++) {
if (dirs[i].indexOf('.') !== -1) {
continue;
}
if (dirs[i].indexOf('node_modules') !== -1) {
continue;
}
console.log('\n***********\nBuilding: ' + dirs[i] + '...');
process.chdir('examples/' + dirs[i]);
childProcess.execSync('npm run build', { stdio: 'inherit' });
process.chdir('../..');
}
console.log('\n********\nDone!');
|
var childProcess = require('child_process');
var fs = require('fs');
process.chdir('examples');
childProcess.execSync('npm install', { stdio: 'inherit' });
childProcess.execSync('npm run update', { stdio: 'inherit' });
process.chdir('..');
// Build all of the example folders.
dirs = fs.readdirSync('examples');
var cmd;
for (var i = 0; i < dirs.length; i++) {
if (dirs[i].indexOf('.') !== -1) {
continue;
}
if (dirs[i].indexOf('node_modules') !== -1) {
continue;
}
console.log('Building: ' + dirs[i] + '...');
process.chdir('examples/' + dirs[i]);
childProcess.execSync('npm run build', { stdio: 'inherit' });
process.chdir('../..');
}
|
Add Python 3 classifier trove
|
import os
from setuptools import setup
setup(
name = "django-jsonfield",
version = open(os.path.join(os.path.dirname(__file__), 'jsonfield', 'VERSION')).read().strip(),
description = "JSONField for django models",
long_description = open("README.rst").read(),
url = "http://bitbucket.org/schinckel/django-jsonfield/",
author = "Matthew Schinckel",
author_email = "matt@schinckel.net",
packages = [
"jsonfield",
],
classifiers = [
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
],
test_suite='tests.main',
include_package_data=True,
)
|
import os
from setuptools import setup
setup(
name = "django-jsonfield",
version = open(os.path.join(os.path.dirname(__file__), 'jsonfield', 'VERSION')).read().strip(),
description = "JSONField for django models",
long_description = open("README.rst").read(),
url = "http://bitbucket.org/schinckel/django-jsonfield/",
author = "Matthew Schinckel",
author_email = "matt@schinckel.net",
packages = [
"jsonfield",
],
classifiers = [
'Programming Language :: Python',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
],
test_suite='tests.main',
include_package_data=True,
)
|
Use baps3protocol package, not old tokeniser
|
package main
import "os"
import "fmt"
import "net"
import "bufio"
import "bytes"
import "github.com/UniversityRadioYork/ury-rapid-go/baps3protocol"
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:1350")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
t := baps3protocol.NewTokeniser()
for {
data, err := bufio.NewReader(conn).ReadBytes('\n')
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lines := t.Parse(data)
buffer := new(bytes.Buffer)
for _, line := range lines {
for _, word := range line {
buffer.WriteString(word + " ")
}
fmt.Println(buffer.String())
}
}
}
|
package main
import "os"
import "fmt"
import "net"
import "bufio"
import "bytes"
import "github.com/UniversityRadioYork/ury-rapid-go/tokeniser"
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:1350")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
t := tokeniser.NewTokeniser()
for {
data, err := bufio.NewReader(conn).ReadBytes('\n')
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lines := t.Parse(data)
buffer := new(bytes.Buffer)
for _, line := range lines {
for _, word := range line {
buffer.WriteString(word + " ")
}
fmt.Println(buffer.String())
}
}
}
|
Add environment variable to disable automatic instrumentation
|
from __future__ import absolute_import
import os
import opentracing
from .sensor import Sensor
from .tracer import InstanaTracer
from .options import Options
if "INSTANA_DISABLE_AUTO_INSTR" not in os.environ:
# Import & initialize instrumentation
from .instrumentation import urllib3
"""
The Instana package has two core components: the sensor and the tracer.
The sensor is individual to each python process and handles process metric
collection and reporting.
The tracer upholds the OpenTracing API and is responsible for reporting
span data to Instana.
"""
__author__ = 'Instana Inc.'
__copyright__ = 'Copyright 2017 Instana Inc.'
__credits__ = ['Pavlo Baron', 'Peter Giacomo Lombardo']
__license__ = 'MIT'
__version__ = '0.7.0'
__maintainer__ = 'Peter Giacomo Lombardo'
__email__ = 'peter.lombardo@instana.com'
# For any given Python process, we only want one sensor as multiple would
# collect/report metrics in duplicate, triplicate etc..
#
# Usage example:
#
# import instana
# instana.global_sensor
#
global_sensor = Sensor(Options())
# The global OpenTracing compatible tracer used internally by
# this package.
#
# Usage example:
#
# import instana
# instana.internal_tracer.start_span(...)
#
internal_tracer = InstanaTracer()
# Set ourselves as the tracer.
opentracing.tracer = internal_tracer
|
from __future__ import absolute_import
import opentracing
from .sensor import Sensor
from .tracer import InstanaTracer
from .options import Options
# Import & initialize instrumentation
from .instrumentation import urllib3
"""
The Instana package has two core components: the sensor and the tracer.
The sensor is individual to each python process and handles process metric
collection and reporting.
The tracer upholds the OpenTracing API and is responsible for reporting
span data to Instana.
"""
__author__ = 'Instana Inc.'
__copyright__ = 'Copyright 2017 Instana Inc.'
__credits__ = ['Pavlo Baron', 'Peter Giacomo Lombardo']
__license__ = 'MIT'
__version__ = '0.7.0'
__maintainer__ = 'Peter Giacomo Lombardo'
__email__ = 'peter.lombardo@instana.com'
# For any given Python process, we only want one sensor as multiple would
# collect/report metrics in duplicate, triplicate etc..
#
# Usage example:
#
# import instana
# instana.global_sensor
#
global_sensor = Sensor(Options())
# The global OpenTracing compatible tracer used internally by
# this package.
#
# Usage example:
#
# import instana
# instana.internal_tracer.start_span(...)
#
internal_tracer = InstanaTracer()
# Set ourselves as the tracer.
opentracing.tracer = internal_tracer
|
Add venue heading for title bar
|
<?php
/*******************************************************************************
* Copyright (c) 2015 Eclipse Foundation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Christopher Guindon (Eclipse Foundation) - Initial implementation
*******************************************************************************/
if (!defined('ABSPATH')) exit;
?>
<ul class="nav navbar-nav navbar-right">
<!--<li><a href="./cfp.php">Call For Proposals</a></li>-->
<li><a href="./index.php#registration">Register</a></li>
<li><a href="./committee.php">Our Committee</a></li>
<li><a href="./venue.php">Venue</a></li>
<li><a href="./terms.php">Terms</a></li>
<li><a href="./conduct.php">Code of Conduct</a></li>
<li><a href="./index.php#schedule">Schedule</a></li>
<li><a href="./index.php#sponsorship">Sponsorship</a></li>
</ul>
|
<?php
/*******************************************************************************
* Copyright (c) 2015 Eclipse Foundation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Christopher Guindon (Eclipse Foundation) - Initial implementation
*******************************************************************************/
if (!defined('ABSPATH')) exit;
?>
<ul class="nav navbar-nav navbar-right">
<!--<li><a href="./cfp.php">Call For Proposals</a></li>-->
<li><a href="./index.php#registration">Register</a></li>
<li><a href="./committee.php">Our Committee</a></li>
<li><a href="./terms.php">Terms</a></li>
<li><a href="./conduct.php">Code of Conduct</a></li>
<li><a href="./index.php#schedule">Schedule</a></li>
<li><a href="./index.php#sponsorship">Sponsorship</a></li>
</ul>
|
Upgrade django-sort-order-field to version 1.2
|
from setuptools import setup, find_packages
setup(
name="web-stuartmccall-ca",
version="1.0",
author="Dylan McCall",
author_email="dylan@dylanmccall.com",
url="http://www.stuartmccall.ca",
packages=find_packages(),
include_package_data=True,
scripts=['manage.py'],
python_requires='>=3.4',
setup_requires=[
'wheel>=0.31.1'
],
install_requires=[
'django-compressor-autoprefixer>=0.1.0',
'django-compressor>=2.4',
'django-dbbackup>=3.3.0',
'django-extensions>=2.2.9',
'django-simplemde>=0.1.3',
'django-tinycontent>=0.8.0',
'django-sort-order-field>=1.2',
'Django>=2.2,<2.3',
'Markdown>=3.2.1',
'Pillow>=7.1.2',
'python-memcached>=1.59',
'pytz==2020.1',
'sorl-thumbnail>=12.6.3'
],
tests_require=[
'nose2>=0.8.0'
]
)
|
from setuptools import setup, find_packages
setup(
name="web-stuartmccall-ca",
version="1.0",
author="Dylan McCall",
author_email="dylan@dylanmccall.com",
url="http://www.stuartmccall.ca",
packages=find_packages(),
include_package_data=True,
scripts=['manage.py'],
python_requires='>=3.4',
setup_requires=[
'wheel>=0.31.1'
],
install_requires=[
'django-compressor-autoprefixer>=0.1.0',
'django-compressor>=2.4',
'django-dbbackup>=3.3.0',
'django-extensions>=2.2.9',
'django-simplemde>=0.1.3',
'django-tinycontent>=0.8.0',
'django-sort-order-field>=1.0',
'Django>=2.2,<2.3',
'Markdown>=3.2.1',
'Pillow>=7.1.2',
'python-memcached>=1.59',
'pytz==2020.1',
'sorl-thumbnail>=12.6.3'
],
tests_require=[
'nose2>=0.8.0'
]
)
|
Check if MergeManager's addResourceToMerge(String, String) had been called
|
package com.izforge.izpack.compiler.packager.impl;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.io.IOException;
import org.dom4j.dom.DOMElement;
import org.junit.Test;
import com.izforge.izpack.api.adaptator.IXMLElement;
import com.izforge.izpack.api.adaptator.impl.XMLElementImpl;
import com.izforge.izpack.compiler.resource.ResourceFinder;
import com.izforge.izpack.merge.MergeManager;
public class PackagerTest {
@Test
public void testWritePacks() throws IOException {
final ResourceFinder resourceFinder = new ResourceFinder(null, null,
null, null) {
@Override
public IXMLElement getXMLTree() throws IOException {
final DOMElement rootNode = new DOMElement("installation");
final DOMElement guiPrefsNode = new DOMElement("guiprefs");
rootNode.add(guiPrefsNode);
return new XMLElementImpl(rootNode);
}
};
final MergeManager mockMergeManager = mock(MergeManager.class);
final Packager packager = new Packager(null, null, null, null, null,
null, null, mockMergeManager, null, null, null, resourceFinder);
packager.writeManifest();
verify(mockMergeManager).addResourceToMerge(anyString(), anyString());
}
}
|
package com.izforge.izpack.compiler.packager.impl;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.dom4j.dom.DOMElement;
import org.junit.Test;
import org.mockito.Mockito;
import com.izforge.izpack.api.adaptator.IXMLElement;
import com.izforge.izpack.api.adaptator.impl.XMLElementImpl;
import com.izforge.izpack.compiler.resource.ResourceFinder;
import com.izforge.izpack.merge.MergeManager;
public class PackagerTest {
@Test
public void testWritePacks() throws IOException {
final ResourceFinder resourceFinder = new ResourceFinder(null, null,
null, null) {
@Override
public IXMLElement getXMLTree() throws IOException {
final DOMElement rootNode = new DOMElement("installation");
final DOMElement guiPrefsNode = new DOMElement("guiprefs");
rootNode.add(guiPrefsNode);
return new XMLElementImpl(rootNode);
}
};
final MergeManager mockMergeManager = Mockito.mock(MergeManager.class);
final Packager packager = new Packager(null, null, null, null, null,
null, null, mockMergeManager, null, null, null, resourceFinder);
packager.writeManifest();
fail("Not yet implemented");
}
}
|
Clean up names and comments for consistency
|
# pylint: disable=wildcard-import,unused-wildcard-import,missing-docstring
from __future__ import absolute_import
from unittest import TestCase
from nose.tools import *
from mock import *
from dear_astrid.rtm.importer import *
class TestRTMImport(TestCase):
def setUp(self):
self.patches = dict(
time = patch('time.sleep'),
rtm = patch('rtm.createRTM'),
)
self.mocks = dict()
for (k, v) in self.patches.items():
self.mocks[k] = v.start()
def test_sleep_before_rtm(self):
imp = Importer(['task'])
imp._rtm = Mock()
assert not self.mocks['time'].called
# Assert that it is in fact our mock object.
assert_equal(imp.rtm, imp._rtm)
self.mocks['time'].assert_called_once_with(1)
# Test chaining method calls.
imp.rtm.foo.bar
self.mocks['time'].assert_has_calls([ call(1), call(1) ])
# Not used this time.
assert not self.mocks['rtm'].called
def test_deobfuscator(self):
imp = Importer(['task'])
imp.key = 'a92'
assert imp.key == '21a'
imp.secret = 'deadbeef'
assert imp.secret == '56253667'
|
# pylint: disable=wildcard-import,unused-wildcard-import,missing-docstring
from __future__ import absolute_import
from unittest import TestCase
from nose.tools import *
from mock import *
from dear_astrid.rtm.importer import Importer as rtmimp
class TestRTMImport(TestCase):
def setUp(self):
self.patches = dict(
time = patch('time.sleep'),
rtm = patch('rtm.createRTM'),
)
self.mocks = dict()
for (k, v) in self.patches.items():
self.mocks[k] = v.start()
def test_sleep_before_rtm(self):
imp = rtmimp(['task'])
imp._rtm = Mock()
assert not self.mocks['time'].called
# assert that it is our mock object
assert_equal(imp.rtm, imp._rtm)
self.mocks['time'].assert_called_once_with(1)
# test calling other methods
imp.rtm.foo.bar
self.mocks['time'].assert_has_calls([ call(1), call(1) ])
# not used this time
assert not self.mocks['rtm'].called
def test_deobfuscator(self):
imp = rtmimp(['task'])
imp.key = 'a92'
assert imp.key == '21a'
imp.secret = 'deadbeef'
assert imp.secret == '56253667'
|
tests/scale: Simplify length & alignment tests
|
from hypothesis import assume, given, strategies as st
from pytest import raises # type: ignore
from ppb_vector import Vector
from utils import angle_isclose, isclose, lengths, vectors
@given(v=vectors(), length=st.floats(max_value=0))
def test_scale_negative_length(v: Vector, length: float):
"""Test that Vector.scale_to raises ValueError on negative lengths."""
assume(length < 0)
with raises(ValueError):
v.scale_to(length)
@given(x=vectors(), length=lengths())
def test_scale_to_length(x: Vector, length: float):
"""Test that the length of x.scale_to(length) is length with x non-null."""
assume(x != (0, 0))
assert isclose(x.scale_to(length).length, length)
@given(x=vectors(), length=lengths())
def test_scale_aligned(x: Vector, length: float):
"""Test that x.scale_to(length) is aligned with x."""
assume(length > 0 and x != (0, 0))
assert angle_isclose(x.scale_to(length).angle(x), 0)
|
from hypothesis import assume, given, strategies as st
from pytest import raises # type: ignore
from ppb_vector import Vector
from utils import angle_isclose, isclose, lengths, vectors
@given(v=vectors(), length=st.floats(max_value=0))
def test_scale_negative_length(v: Vector, length: float):
"""Test that Vector.scale_to raises ValueError on negative lengths."""
assume(length < 0)
with raises(ValueError):
v.scale_to(length)
@given(x=vectors(), length=lengths())
def test_scale_to_length(x: Vector, length: float):
"""Test that the length of x.scale_to(length) is length.
Additionally, scale_to may raise ZeroDivisionError if the vector is null.
"""
try:
assert isclose(x.scale_to(length).length, length)
except ZeroDivisionError:
assert x == (0, 0)
@given(x=vectors(), length=lengths())
def test_scale_aligned(x: Vector, length: float):
"""Test that x.scale_to(length) is aligned with x."""
assume(length > 0)
try:
assert angle_isclose(x.scale_to(length).angle(x), 0)
except ZeroDivisionError:
assert x == (0, 0)
|
Use id() instead of increments('id')
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class OrchestraMemoryCreateOptionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('orchestra_options', function (Blueprint $table) {
$table->id();
$table->string('name', 64);
$table->longText('value');
$table->unique('name');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('orchestra_options');
}
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class OrchestraMemoryCreateOptionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('orchestra_options', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 64);
$table->longText('value');
$table->unique('name');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('orchestra_options');
}
}
|
Add function for getting starting power
|
package io.github.aquerr.eaglefactions.logic;
import io.github.aquerr.eaglefactions.config.ConfigAccess;
import io.github.aquerr.eaglefactions.config.IConfig;
import io.github.aquerr.eaglefactions.config.MainConfig;
import ninja.leaping.configurate.ConfigurationNode;
public class MainLogic
{
private static IConfig mainConfig = MainConfig.getConfig();
public static boolean getAllianceFriendlyFire()
{
ConfigurationNode friendlyFireNode = ConfigAccess.getConfig(mainConfig).getNode("eaglefactions", "friendlyFire", "alliance");
Boolean friendlyFire = friendlyFireNode.getBoolean();
return friendlyFire;
}
public static int getPlayerMaxPower()
{
ConfigurationNode maxPowerNode = ConfigAccess.getConfig(mainConfig).getNode("eaglefactions", "power", "maxpower");
int maxPower = maxPowerNode.getInt();
return maxPower;
}
public static int getStartingPower()
{
ConfigurationNode startingPowerNode = ConfigAccess.getConfig(mainConfig).getNode("eaglefactions", "power", "startpower");
int startPower = startingPowerNode.getInt();
return startPower;
}
}
|
package io.github.aquerr.eaglefactions.logic;
import io.github.aquerr.eaglefactions.config.ConfigAccess;
import io.github.aquerr.eaglefactions.config.IConfig;
import io.github.aquerr.eaglefactions.config.MainConfig;
import ninja.leaping.configurate.ConfigurationNode;
public class MainLogic
{
private static IConfig mainConfig = MainConfig.getConfig();
public static boolean getAllianceFriendlyFire()
{
ConfigurationNode friendlyFireNode = ConfigAccess.getConfig(mainConfig).getNode("eaglefactions", "friendlyFire", "alliance");
Boolean friendlyFire = friendlyFireNode.getBoolean();
return friendlyFire;
}
public static int getPlayerMaxPower()
{
ConfigurationNode maxPowerNode = ConfigAccess.getConfig(mainConfig).getNode("eaglefactions", "power", "maxpower");
int maxPower = maxPowerNode.getInt();
return maxPower;
}
}
|
Remove use of deprecated types.
Reviewer: Hugo Parente Lima <e250cbdf6b5a11059e9d944a6e5e9282be80d14c@openbossa.org>,
Luciano Wolf <luciano.wolf@openbossa.org>
|
'''Test cases for QDeclarativeView'''
import unittest
from PySide.QtCore import QUrl
from PySide.QtDeclarative import QDeclarativeView
from helper import adjust_filename, TimedQApplication
class TestQDeclarativeView(TimedQApplication):
def testQDeclarativeViewList(self):
view = QDeclarativeView()
dataList = ["Item 1", "Item 2", "Item 3", "Item 4"]
ctxt = view.rootContext()
ctxt.setContextProperty("myModel", dataList)
url = QUrl.fromLocalFile(adjust_filename('view.qml', __file__))
view.setSource(url)
view.show()
self.assertEqual(view.status(), QDeclarativeView.Ready)
self.app.exec_()
if __name__ == '__main__':
unittest.main()
|
'''Test cases for QDeclarativeView'''
import unittest
from PySide.QtCore import QUrl, QStringList, QVariant
from PySide.QtGui import QPushButton
from PySide.QtDeclarative import QDeclarativeView
from helper import adjust_filename, TimedQApplication
class TestQDeclarativeView(TimedQApplication):
def testQDeclarativeViewList(self):
view = QDeclarativeView()
dataList = QStringList(["Item 1", "Item 2", "Item 3", "Item 4"])
ctxt = view.rootContext()
ctxt.setContextProperty("myModel", dataList)
url = QUrl.fromLocalFile(adjust_filename('view.qml', __file__))
view.setSource(url)
view.show()
self.assertEqual(view.status(), QDeclarativeView.Ready)
self.app.exec_()
if __name__ == '__main__':
unittest.main()
|
Change max length for image URLs
Images length are longer. So multiple the regular URL length by 2.
|
<?php
/**
* @author Pierre-Henry Soria <hello@ph7cms.com>
* @copyright (c) 2017, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / Framework / Service / SearchImage
*/
namespace PH7\Framework\Service\SearchImage;
defined('PH7') or exit('Restricted access');
class Url
{
/**
* @param string $sUrl
*
* @throws InvalidUrlException
*/
public function __construct($sUrl)
{
if (
filter_var($sUrl, FILTER_VALIDATE_URL) === false ||
strlen($sUrl) >= $this->getMaxImageLength()
) {
throw new InvalidUrlException('Invalid URL');
}
$this->sUrl = $sUrl;
}
/**
* @param string
*/
public function getValue()
{
return $this->sUrl;
}
/**
* Images length are longer. It multiples the regular URL length by 2.
*
* @return int
*/
private function getMaxImageLength()
{
return PH7_MAX_URL_LENGTH * 2;
}
}
|
<?php
/**
* @author Pierre-Henry Soria <hello@ph7cms.com>
* @copyright (c) 2017, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / Framework / Service / SearchImage
*/
namespace PH7\Framework\Service\SearchImage;
defined('PH7') or exit('Restricted access');
class Url
{
/**
* @param string $sUrl
*
* @throws InvalidUrlException
*/
public function __construct($sUrl)
{
if (
filter_var($sUrl, FILTER_VALIDATE_URL) === false ||
strlen($sUrl) >= PH7_MAX_URL_LENGTH
) {
throw new InvalidUrlException('Invalid URL');
}
$this->sUrl = $sUrl;
}
/**
* @param string
*/
public function getValue()
{
return $this->sUrl;
}
}
|
Fix draggability on top of other conveyers.
|
package net.mostlyoriginal.game.system.drag;
import com.artemis.Aspect;
import com.artemis.Entity;
import com.artemis.EntitySystem;
import com.artemis.World;
import com.artemis.annotations.Wire;
import com.artemis.utils.IntBag;
import net.mostlyoriginal.api.system.physics.CollisionSystem;
import net.mostlyoriginal.game.component.Conveyer;
import net.mostlyoriginal.game.component.Draggable;
/**
* @author Daan van Yperen
*/
@Wire
public class GridOverlapHelperSystem extends EntitySystem {
CollisionSystem collisionSystem;
private Entity flyweightEntity;
public GridOverlapHelperSystem() {
super(Aspect.one(Draggable.class, Conveyer.class));
}
@Override
protected void setWorld(World world) {
super.setWorld(world);
flyweightEntity = createFlyweightEntity();
}
/**
* Does passed entity overlap any grid entity? (except self)
*/
public boolean overlaps(Entity e) {
IntBag actives = subscription.getEntities();
int[] array = actives.getData();
for (int i = 0, s = actives.size(); s > i; i++) {
flyweightEntity.id = array[i];
if (flyweightEntity.getId() != e.getId() && collisionSystem.overlaps(flyweightEntity, e)) {
return true;
}
}
return false;
}
@Override
protected void processSystem() {
}
}
|
package net.mostlyoriginal.game.system.drag;
import com.artemis.Aspect;
import com.artemis.Entity;
import com.artemis.EntitySystem;
import com.artemis.World;
import com.artemis.annotations.Wire;
import com.artemis.utils.IntBag;
import net.mostlyoriginal.api.system.physics.CollisionSystem;
import net.mostlyoriginal.game.component.Draggable;
/**
* @author Daan van Yperen
*/
@Wire
public class GridOverlapHelperSystem extends EntitySystem {
CollisionSystem collisionSystem;
private Entity flyweightEntity;
public GridOverlapHelperSystem() {
super(Aspect.all(Draggable.class));
}
@Override
protected void setWorld(World world) {
super.setWorld(world);
flyweightEntity = createFlyweightEntity();
}
/**
* Does passed entity overlap any grid entity? (except self)
*/
public boolean overlaps(Entity e) {
IntBag actives = subscription.getEntities();
int[] array = actives.getData();
for (int i = 0, s = actives.size(); s > i; i++) {
flyweightEntity.id = array[i];
if (flyweightEntity.getId() != e.getId() && collisionSystem.overlaps(flyweightEntity, e)) {
return true;
}
}
return false;
}
@Override
protected void processSystem() {
}
}
|
Write message string direct to loggly
|
package gop
import (
"fmt"
"github.com/segmentio/go-loggly"
)
// A timber.LogWriter for the loggly service.
// LogglyWriter is a Timber writer to send logging to the loggly
// service. See: https://loggly.com.
type LogglyWriter struct {
c *loggly.Client
}
// NewLogEntriesWriter creates a new writer for sending logging to logentries.
func NewLogglyWriter(token string, tags ...string) (*LogglyWriter, error) {
return &LogglyWriter{c: loggly.New(token, tags...)}, nil
}
// LogWrite the message to the logenttries server async. Satifies the timber.LogWrite interface.
func (w *LogglyWriter) LogWrite(msg string) {
// using type for the message string is how the Info etc methods on the
// loggly client work.
// TODO: Add a "level" key for info, error..., proper timestamp etc
// Buffers the message for async send
// TODO - Stat for the bytes written return?
if _, err := w.c.Write([]byte(msg)); err != nil {
// TODO: What is best todo here as if we log it will loop?
fmt.Println("loggly send error: %s", err.Error())
}
}
// Close the write. Satifies the timber.LogWriter interface.
func (w *LogglyWriter) Close() {
w.c.Flush()
}
|
package gop
import (
"fmt"
"github.com/segmentio/go-loggly"
)
// A timber.LogWriter for the loggly service.
// LogglyWriter is a Timber writer to send logging to the loggly
// service. See: https://loggly.com.
type LogglyWriter struct {
c *loggly.Client
}
// NewLogEntriesWriter creates a new writer for sending logging to logentries.
func NewLogglyWriter(token string, tags ...string) (*LogglyWriter, error) {
return &LogglyWriter{c: loggly.New(token, tags...)}, nil
}
// LogWrite the message to the logenttries server async. Satifies the timber.LogWrite interface.
func (w *LogglyWriter) LogWrite(msg string) {
// using type for the message string is how the Info etc methods on the
// loggly client work.
// TODO: Add a "level" key for info, error..., proper timestamp etc
// Buffers the message for async send
lmsg := loggly.Message{"type": msg}
if err := w.c.Send(lmsg); err != nil {
// TODO: What is best todo here as if we log it will loop?
fmt.Println("loggly send error: %s", err.Error())
}
}
// Close the write. Satifies the timber.LogWriter interface.
func (w *LogglyWriter) Close() {
w.c.Flush()
}
|
Update the PyPI version to 7.0.15.
|
# -*- 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.15',
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.14',
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',
),
)
|
Make test asynchronous if it wants to be
|
/* global describe, it */
import {exec} from '../../../src/utils/util';
import assert from 'assert';
require('chai').should();
describe("Oi CLI", () => {
it("can be invoked", (done) => {
const result = exec('node dist/bin/oi.js -v');
console.log(result);
console.log(result.toString());
console.log(result.code);
console.log(result.stdout);
console.log(result.stdout.trim());
console.log(result.stdout.trim().match(/^\d+\.\d+\.\d+$/));
try {
result.toString().trim().should.match(/^\d+\.\d+\.\d+$/);
done();
} catch (e) {
console.error('ERROR:', e);
done(e);
throw Error('FAIL');
}
});
});
|
/* global describe, it */
import {exec} from '../../../src/utils/util';
import assert from 'assert';
require('chai').should();
describe("Oi CLI", () => {
it("can be invoked", (done) => {
const result = exec('node dist/bin/oi.js -v');
console.log(result);
console.log(result.toString());
console.log(result.code);
console.log(result.stdout);
console.log(result.stdout.trim());
console.log(result.stdout.trim().match(/^\d+\.\d+\.\d+$/));
try {
result.stdout.trim().should.match(/^\d+\.\d+\.\d+$/);
done();
} catch (e) {
console.error('ERROR:', e);
done(e);
throw Error('FAIL');
}
});
});
|
Change qurl.org for tinyurl.com as URL shortener service
|
package com.github.NewsBotIRC;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by Geronimo on 11/6/16.
*/
public class UrlShortener {
public static String shortenUrl(String myUrl)
{
String shortenedUrl = myUrl;
try {
String encoded = URLEncoder.encode(myUrl, "UTF-8");
URL url = new URL("https://tinyurl.com/api-create.php?url=" + encoded);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream()));
shortenedUrl = reader.readLine();
} catch (IOException e) {
System.out.println(e.getMessage());
}
return shortenedUrl;
}
}
|
package com.github.NewsBotIRC;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Geronimo on 11/6/16.
*/
public class UrlShortener {
public static String shortenUrl(String myUrl)
{
String shortenedUrl = myUrl;
try {
String encoded = URLEncoder.encode(myUrl, "UTF-8");
URL url = new URL("http://qurl.org/api/url?url=" + encoded);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream()));
JSONObject json = new JSONObject( reader.readLine() );
shortenedUrl = json.optString("url");
} catch (IOException | JSONException e) {
System.out.println(e.getMessage());
}
return shortenedUrl;
}
}
|
Switch to a built-in long_description so pip succeeds
|
from distutils.core import setup
classifiers = [
'Development Status :: 5 - Production/Stable',
'Environment :: Win32 (MS Windows)',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: Microsoft :: Windows',
'Topic :: System :: Systems Administration',
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
]
long_description = """winshell
========
The winshell module is a light wrapper around the Windows shell functionality.
It includes convenience functions for accessing special folders, for using
the shell's file copy, rename & delete functionality, and a certain amount
of support for structured storage.
Docs are hosted at: http://winshell.readthedocs.org/
"""
setup (
name = "winshell",
version = "0.4",
description = "Windows shell functions",
author = "Tim Golden",
author_email = "mail@timgolden.me.uk",
url = "https://github.com/tjguk/winshell",
license = "http://www.opensource.org/licenses/mit-license.php",
py_modules = ["winshell"],
long_description=long_description
)
|
from distutils.core import setup
classifiers = [
'Development Status :: 5 - Production/Stable',
'Environment :: Win32 (MS Windows)',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: Microsoft :: Windows',
'Topic :: System :: Systems Administration',
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
]
setup (
name = "winshell",
version = "0.4",
description = "Windows shell functions",
author = "Tim Golden",
author_email = "mail@timgolden.me.uk",
url = "https://github.com/tjguk/winshell",
license = "http://www.opensource.org/licenses/mit-license.php",
py_modules = ["winshell"],
long_description=open ("docs/readme.rst").read ()
)
|
Use 7 chars for git commit hash, not 8
Consistent with GitHub
|
const fs = require("fs");
const path = require("path");
const gitDir = path.resolve(__dirname, "..", ".git");
function getPackageVersion() {
const packageJson = require("../package.json");
return packageJson.version;
}
function getHeadCommitHash() {
try {
fs.accessSync(gitDir);
} catch (e) {
return null;
}
// Find HEAD ref and read the commit hash from that ref
const headRefInfo = fs.readFileSync(path.resolve(gitDir, "HEAD"), { encoding: "utf8" });
if (headRefInfo.startsWith("ref:")) {
const refPath = headRefInfo.slice(5).trim(); // ref: refs/heads/... to refs/heads/...
return fs.readFileSync(path.resolve(gitDir, refPath), { encoding: "utf8" }).trim();
} else {
// Detached head, just the commit hash
return headRefInfo.trim();
}
}
function getPrettyVersion() {
const packageVersion = getPackageVersion();
const headCommitHash = getHeadCommitHash();
return headCommitHash
? `v${packageVersion} (${headCommitHash.slice(0, 7)})`
: packageVersion;
}
module.exports = {
getPrettyVersion,
};
|
const fs = require("fs");
const path = require("path");
const gitDir = path.resolve(__dirname, "..", ".git");
function getPackageVersion() {
const packageJson = require("../package.json");
return packageJson.version;
}
function getHeadCommitHash() {
try {
fs.accessSync(gitDir);
} catch (e) {
return null;
}
// Find HEAD ref and read the commit hash from that ref
const headRefInfo = fs.readFileSync(path.resolve(gitDir, "HEAD"), { encoding: "utf8" });
if (headRefInfo.startsWith("ref:")) {
const refPath = headRefInfo.slice(5).trim(); // ref: refs/heads/... to refs/heads/...
return fs.readFileSync(path.resolve(gitDir, refPath), { encoding: "utf8" }).trim();
} else {
// Detached head, just the commit hash
return headRefInfo.trim();
}
}
function getPrettyVersion() {
const packageVersion = getPackageVersion();
const headCommitHash = getHeadCommitHash();
return headCommitHash
? `v${packageVersion} (${headCommitHash.slice(0, 8)})`
: packageVersion;
}
module.exports = {
getPrettyVersion,
};
|
Add createChannel and recreateChannel and handle channel error and close event
|
var amqp = require('amqplib');
var amqpUrl, amqpConnection, intervalID;
function connect(_amqpUrl) {
amqpUrl = amqpUrl || _amqpUrl || process.env.AMQP_URL || 'amqp://localhost';
return amqp.connect(amqpUrl)
.then(function (_connection) {
amqpConnection = _connection;
_connection.on('close', reconnect);
_connection.on('error', reconnect);
intervalID = clearInterval(intervalID);
return createChannel();
});
}
function createChannel() {
if (amqpConnection) {
return amqpConnection.createChannel()
.then(function (_channel) {
_channel.on('close', recreateChannel);
_channel.on('error', recreateChannel);
intervalID = clearInterval(intervalID);
return _channel;
});
} else {
reconnect();
}
}
function recreateChannel() {
if (!intervalID) {
intervalID = setInterval(createChannel, 1000);
}
}
function reconnect() {
if (!intervalID) {
intervalID = setInterval(connect, 1000);
}
}
function disconnect() {
if (amqpConnection) {
amqpConnection.close();
}
}
module.exports = function () {
return {
connect: connect,
reconnect: reconnect,
disconnect: disconnect
};
};
|
var amqp = require('amqplib');
var amqpUrl, amqpConnection, intervalID;
function connect(_amqpUrl) {
amqpUrl = amqpUrl || _amqpUrl || process.env.AMQP_URL || 'amqp://localhost';
return amqp.connect(amqpUrl)
.then(function (_connection) {
amqpConnection = _connection;
_connection.on('close', reconnect);
_connection.on('error', reconnect);
intervalID = clearInterval(intervalID);
return _connection.createChannel()
.then(function (_channel) {
return _channel;
});
});
}
function reconnect() {
if (!intervalID) {
intervalID = setInterval(connect, 1000);
}
}
function disconnect() {
if (amqpConnection) {
amqpConnection.close();
}
}
module.exports = function () {
return {
connect: connect,
reconnect: reconnect,
disconnect: disconnect
};
};
|
Add check for multiplication overflow in ptypes.ReverseInt function
|
// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package ptypes
import "math"
// ReverseInt returns reversed x digits.
// 0, false is returned if x cannot be reversed because of int64 overflow.
// The time complexity is O(n), where n is the number of digits in x.
// The space complexity is O(1).
func ReverseInt(x int64) (r int64, ok bool) {
const cutoff = math.MaxInt64/10 + 1 // The first smallest number such that cutoff*10 > MaxInt64.
var n uint64
neg := x < 0
u := uint64(x)
if neg {
u = -u
}
for u > 0 {
if n >= cutoff { // Check if n*10 overflows.
return 0, false // TODO: cover this in tests!
}
n = n*10 + u%10
if neg && n > -math.MinInt64 || !neg && n > math.MaxInt64 { // -n < math.MinInt64 || n > math.MaxInt64
return 0, false
}
u /= 10
}
r = int64(n)
if neg {
r = -r
}
return r, true
}
|
// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package ptypes
import "math"
// ReverseInt returns reversed x digits.
// 0, false is returned if x cannot be reversed because of int64 overflow.
// The time complexity is O(n), where n is the number of digits in x.
// The space complexity is O(1).
func ReverseInt(x int64) (r int64, ok bool) {
var n uint64
neg := x < 0
u := uint64(x)
if neg {
u = -u
}
for u > 0 {
n = n*10 + u%10
if neg && n > -math.MinInt64 || !neg && n > math.MaxInt64 { // -n < math.MinInt64 || n > math.MaxInt64
return 0, false
}
u /= 10
}
r = int64(n)
if neg {
r = -r
}
return r, true
}
|
Add tests for numbers 11 to 19
|
import unittest
from number_to_words import NumberToWords
class TestNumberToWords(unittest.TestCase):
def setUp(self):
self.n2w = NumberToWords()
def tearDown(self):
self.n2w = None
def test_zero_and_single_digits(self):
NUMBERS = {
0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'
}
self.assert_numbers_equal_to_strings(NUMBERS)
def test_eleven_to_nineteen(self):
NUMBERS = {
11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen',
15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen',
19: 'nineteen'
}
self.assert_numbers_equal_to_strings(NUMBERS)
def assert_numbers_equal_to_strings(self, numbers):
for number, string in numbers.iteritems():
self.assertEqual(string, self.n2w.convert(number))
if __name__ == '__main__':
unittest.main()
|
import unittest
from number_to_words import NumberToWords
class TestNumberToWords(unittest.TestCase):
def setUp(self):
self.n2w = NumberToWords()
def tearDown(self):
self.n2w = None
def test_zero_and_single_digits(self):
NUMBERS = {
0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'
}
self.assert_numbers_equal_to_strings(NUMBERS)
def assert_numbers_equal_to_strings(self, numbers):
for number, string in numbers.iteritems():
self.assertEqual(string, self.n2w.convert(number))
if __name__ == '__main__':
unittest.main()
|
Add routes to handle login GET and POST
|
const express = require('express')
const app = express()
const http = require('http').Server(app)
const path = require('path')
const bodyParser = require('body-parser')
const register = require('./routes/register')
const login = require('./routes/login')
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
// Looks for external JS file holding front-end logic
app.use(express.static(path.join(__dirname, '/public')))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/', (req, res) => {
res.render('chat_ui')
})
app.get('/register', register.form)
app.post('/register', register.submit)
app.get('/login', login.form)
app.post('/login', login.submit)
http.listen(3000, () => {
console.log('Server is listening at * 3000')
})
const socket = require('./lib/chat_server')
socket.listen(http)
|
const express = require('express')
const app = express()
const http = require('http').Server(app)
const path = require('path')
const bodyParser = require('body-parser')
const register = require('./routes/register')
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
// Looks for external JS file holding front-end logic
app.use(express.static(path.join(__dirname, '/public')))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/', (req, res) => {
res.render('chat_ui')
})
app.get('/register', register.form)
app.post('/register', register.submit)
http.listen(3000, () => {
console.log('Server is listening at * 3000')
})
const socket = require('./lib/chat_server')
socket.listen(http)
|
Raise KeyboardInterrupt to allow the run to handle logout
|
import discord
import asyncio
import os
import signal
import sys
#Set up Client State
CLIENT_TOKEN=os.environ['TOKEN']
#Create Discord client
client = discord.Client()
#Handle shutdown gracefully
async def sigterm_handler(signum, frame):
print("Logging out...")
raise KeyboardInterrupt
print('Shutting down...')
sys.exit(1)
#Register SIGTERM Handler
signal.signal(signal.SIGTERM, sigterm_handler)
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
@client.event
async def on_message(message):
if message.content.startswith('!test'):
counter = 0
tmp = await client.send_message(message.channel, 'Calculating messages...')
async for log in client.logs_from(message.channel, limit=100):
if log.author == message.author:
counter += 1
await client.edit_message(tmp, 'You have {} messages.'.format(counter))
elif message.content.startswith('!sleep'):
await asyncio.sleep(5)
await client.send_message(message.channel, 'Done sleeping')
client.run(CLIENT_TOKEN)
|
import discord
import asyncio
import os
import signal
import sys
#Set up Client State
CLIENT_TOKEN=os.environ['TOKEN']
#Create Discord client
client = discord.Client()
#Handle shutdown gracefully
def sigterm_handler(signum, frame):
print("Logging out...")
client.logout()
print('Shutting down...')
sys.exit(1)
#Register SIGTERM Handler
signal.signal(signal.SIGTERM, sigterm_handler)
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
@client.event
async def on_message(message):
if message.content.startswith('!test'):
counter = 0
tmp = await client.send_message(message.channel, 'Calculating messages...')
async for log in client.logs_from(message.channel, limit=100):
if log.author == message.author:
counter += 1
await client.edit_message(tmp, 'You have {} messages.'.format(counter))
elif message.content.startswith('!sleep'):
await asyncio.sleep(5)
await client.send_message(message.channel, 'Done sleeping')
client.run(CLIENT_TOKEN)
|
Add encoding parameter to open jsonld
|
__all__ = ['process_jsonld_file', 'process_jsonld']
import json
import logging
from indra.sources.hume import processor
logger = logging.getLogger(__name__)
def process_jsonld_file(fname):
"""Process a JSON-LD file in the new format to extract Statements.
Parameters
----------
fname : str
The path to the JSON-LD file to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
with open(fname, 'r', encoding='utf-8') as fh:
json_dict = json.load(fh)
return process_jsonld(json_dict)
def process_jsonld(jsonld):
"""Process a JSON-LD string in the new format to extract Statements.
Parameters
----------
jsonld : dict
The JSON-LD object to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
hp = processor.HumeJsonLdProcessor(jsonld)
hp.extract_relations()
hp.extract_events()
return hp
|
__all__ = ['process_jsonld_file', 'process_jsonld']
import json
import logging
from indra.sources.hume import processor
logger = logging.getLogger(__name__)
def process_jsonld_file(fname):
"""Process a JSON-LD file in the new format to extract Statements.
Parameters
----------
fname : str
The path to the JSON-LD file to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
with open(fname, 'r') as fh:
json_dict = json.load(fh)
return process_jsonld(json_dict)
def process_jsonld(jsonld):
"""Process a JSON-LD string in the new format to extract Statements.
Parameters
----------
jsonld : dict
The JSON-LD object to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
hp = processor.HumeJsonLdProcessor(jsonld)
hp.extract_relations()
hp.extract_events()
return hp
|
Add getter for filename to interface
|
/*-
* Copyright 2016 Diamond Light Source Ltd.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.dawnsci.analysis.api.processing;
import java.util.List;
/**
* Interface to set up an operation processing run
*/
public interface IOperationBean {
public void setDataKey(String dataKey);
public void setFilePath(String filePath);
public String getFilePath();
public void setOutputFilePath(String outputFilePath);
public String getOutputFilePath();
public void setDatasetPath(String datasetPath);
public void setSlicing(String slicing);
public void setProcessingPath(String processingPath);
public void setAxesNames(List<String>[] axesNames);
public void setDeleteProcessingFile(boolean deleteProcessingFile);
public void setXmx(String xmx);
public void setDataDimensions(int[] dataDimensions);
public void setScanRank(int scanRank);
public void setReadable(boolean readable);
public void setName(String name);
public void setRunDirectory(String runDirectory);
public void setNumberOfCores(int numberOfCores);
}
|
/*-
* Copyright 2016 Diamond Light Source Ltd.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.dawnsci.analysis.api.processing;
import java.util.List;
/**
* Interface to set up an operation processing run
*/
public interface IOperationBean {
public void setDataKey(String dataKey);
public void setFilePath(String filePath);
public void setOutputFilePath(String outputFilePath);
public String getOutputFilePath();
public void setDatasetPath(String datasetPath);
public void setSlicing(String slicing);
public void setProcessingPath(String processingPath);
public void setAxesNames(List<String>[] axesNames);
public void setDeleteProcessingFile(boolean deleteProcessingFile);
public void setXmx(String xmx);
public void setDataDimensions(int[] dataDimensions);
public void setScanRank(int scanRank);
public void setReadable(boolean readable);
public void setName(String name);
public void setRunDirectory(String runDirectory);
public void setNumberOfCores(int numberOfCores);
}
|
Add method to partition id into thumbnail path
|
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"path"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
type ThumbnailSize struct {
Width uint
Height uint
}
var ThumbnailSizes = map[string]ThumbnailSize{
"small": ThumbnailSize{100, 100},
"large": ThumbnailSize{500, 500},
}
type Config struct {
SourceFolderPath string `json:"source_folder_path"`
DestinationFolderPath string `json:"destination_folder_path"`
ThumbnailsFolderPath string `json:"thumbnails_folder_path"`
DatabaseConnectionString string `json:"database_connection_string"`
}
func LoadConfig(configPath string) (Config, error) {
var config Config
file, err := ioutil.ReadFile(configPath)
if err != nil {
return config, err
}
err = json.Unmarshal(file, &config)
return config, err
}
func SetupDatabase(connectionString string) gorm.DB {
db, err := gorm.Open("postgres", connectionString)
if err != nil {
panic("Unable to open database")
}
db.AutoMigrate(&Photo{}, &SimilarPhoto{})
return db
}
func PartitionIdAsPath(input int64) string {
inputRunes := []rune(fmt.Sprintf("%09d", input))
return path.Join(
string(inputRunes[0:3]),
string(inputRunes[3:6]),
string(inputRunes[6:]),
)
}
|
package main
import (
"encoding/json"
"io/ioutil"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
type ThumbnailSize struct {
Width uint
Height uint
}
var ThumbnailSizes = map[string]ThumbnailSize{
"small": ThumbnailSize{100, 100},
"large": ThumbnailSize{500, 500},
}
type Config struct {
SourceFolderPath string `json:"source_folder_path"`
DestinationFolderPath string `json:"destination_folder_path"`
ThumbnailsFolderPath string `json:"thumbnails_folder_path"`
DatabaseConnectionString string `json:"database_connection_string"`
}
func LoadConfig(configPath string) (Config, error) {
var config Config
file, err := ioutil.ReadFile(configPath)
if err != nil {
return config, err
}
err = json.Unmarshal(file, &config)
return config, err
}
func SetupDatabase(connectionString string) gorm.DB {
db, err := gorm.Open("postgres", connectionString)
if err != nil {
panic("Unable to open database")
}
db.AutoMigrate(&Photo{}, &SimilarPhoto{})
return db
}
|
Add oanda environment selector from runtime environments.
|
# -*- encoding:utf8 -*-
import os
from model.oandapy import oandapy
class OrderBook(object):
def get_latest_orderbook(self, instrument, period, history):
oanda_token = os.environ.get('OANDA_TOKEN')
oanda_environment = os.environ.get('OANDA_ENVIRONMENT', 'practice')
oanda = oandapy.API(environment=oanda_environment, access_token=oanda_token)
orders = oanda.get_orderbook(instrument=instrument)
try:
timeset = orders.keys()
timeset.sort()
timeset.reverse()
target_time = timeset[history]
except:
return None
order = orders[target_time]
order['time'] = target_time
return order
|
# -*- encoding:utf8 -*-
import os
from model.oandapy import oandapy
class OrderBook(object):
def get_latest_orderbook(self, instrument, period, history):
oanda_token = os.environ.get('OANDA_TOKEN')
oanda = oandapy.API(environment="practice", access_token=oanda_token)
orders = oanda.get_orderbook(instrument=instrument)
try:
timeset = orders.keys()
timeset.sort()
timeset.reverse()
target_time = timeset[history]
except:
return None
order = orders[target_time]
order['time'] = target_time
return order
|
Add some preconditions to check state of constructor arguments.
|
package uk.ac.ebi.quickgo.index.annotation.coterms;
import uk.ac.ebi.quickgo.index.annotation.Annotation;
import com.google.common.base.Preconditions;
import java.util.function.Predicate;
import org.springframework.batch.item.ItemProcessor;
/**
* @author Tony Wardell
* Date: 06/09/2016
* Time: 16:30
* Created with IntelliJ IDEA.
*
* A version of ItemProcessor for adding details from an {@link uk.ac.ebi.quickgo.index.annotation.Annotation}
* to a matrix of permutations where GOTerm A and GOTerm B both annotate the same Gene Product.
*
* Version of GPAFileToSummary from Beta
*/
public class AnnotationCoStatsProcessor implements ItemProcessor<Annotation, Annotation> {
private final CoStatsPermutations coStatsPermutations;
private final Predicate<Annotation> toBeProcessed;
public AnnotationCoStatsProcessor(CoStatsPermutations coStatsPermutations,Predicate<Annotation> toBeProcessed) {
Preconditions.checkArgument(coStatsPermutations!=null);
Preconditions.checkArgument(toBeProcessed!=null);
this.coStatsPermutations = coStatsPermutations;
this.toBeProcessed = toBeProcessed;
}
@Override
public Annotation process(Annotation annotation) throws Exception {
if(toBeProcessed.test(annotation)){
coStatsPermutations.addRowToMatrix(annotation);
}
return annotation;
}
}
|
package uk.ac.ebi.quickgo.index.annotation.coterms;
import uk.ac.ebi.quickgo.index.annotation.Annotation;
import java.util.function.Predicate;
import org.springframework.batch.item.ItemProcessor;
/**
* @author Tony Wardell
* Date: 06/09/2016
* Time: 16:30
* Created with IntelliJ IDEA.
*
* A version of ItemProcessor for adding details from an {@link uk.ac.ebi.quickgo.index.annotation.Annotation}
* to a matrix of permutations where GOTerm A and GOTerm B both annotate the same Gene Product.
*
* Version of GPAFileToSummary from Beta
*/
public class AnnotationCoStatsProcessor implements ItemProcessor<Annotation, Annotation> {
private final CoStatsPermutations coStatsPermutations;
private final Predicate<Annotation> toBeProcessed;
public AnnotationCoStatsProcessor(CoStatsPermutations coStatsPermutations,
Predicate<Annotation> toBeProcessed) {
this.coStatsPermutations = coStatsPermutations;
this.toBeProcessed = toBeProcessed;
}
@Override
public Annotation process(Annotation annotation) throws Exception {
if(toBeProcessed.test(annotation)){
coStatsPermutations.addRowToMatrix(annotation);
}
return annotation;
}
}
|
Allow spreading with ununsed underscore-prefixed vars
|
module.exports = {
extends: ['eslint:recommended', 'prettier'],
parser: 'babel-eslint',
plugins: ['import', 'prettier'],
env: {
node: true,
es6: true,
},
root: true,
rules: {
'prettier/prettier': [
'error',
{ trailingComma: 'es5', singleQuote: true, printWidth: 90, tabWidth: 4 },
],
'import/order': [
'error',
{
groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'],
},
],
'no-unused-vars': [
'error',
{ vars: 'all', args: 'none', varsIgnorePattern: '^_' },
],
'no-underscore-dangle': 'off',
'no-param-reassign': 'off',
'no-console': 'off',
'no-warning-comments': ['warn', { terms: ['fixme'], location: 'start' }],
},
};
|
module.exports = {
extends: ['eslint:recommended', 'prettier'],
parser: 'babel-eslint',
plugins: ['import', 'prettier'],
env: {
node: true,
es6: true,
},
root: true,
rules: {
'prettier/prettier': [
'error',
{ trailingComma: 'es5', singleQuote: true, printWidth: 90, tabWidth: 4 },
],
'import/order': [
'error',
{
groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'],
},
],
'no-unused-vars': ['error', { vars: 'all', args: 'none' }],
'no-underscore-dangle': 'off',
'no-param-reassign': 'off',
'no-console': 'off',
'no-warning-comments': ['warn', { terms: ['fixme'], location: 'start' }],
},
};
|
Add code to test the parser
|
package com.davidmogar.nji;
import com.davidmogar.nji.lexicon.Lexicon;
import com.davidmogar.nji.syntactic.Parser;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("Input file expected.");
System.exit(0);
}
File inputFile = null;
FileReader fileReader = null;
try {
inputFile = new File(args[0]);
fileReader = new FileReader(inputFile);
} catch (IOException e) {
System.err.println(e.getMessage());
System.exit(-1);
}
Lexicon lexicon = new Lexicon(fileReader);
Parser parser = new Parser(lexicon);
parser.run();
System.out.println("fin");
}
}
|
package com.davidmogar.nji;
import com.davidmogar.nji.lexicon.Lexicon;
import com.davidmogar.nji.syntactic.Parser;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("Input file expected.");
System.exit(0);
}
File inputFile = null;
FileReader fileReader = null;
try {
inputFile = new File(args[0]);
fileReader = new FileReader(inputFile);
} catch (IOException e) {
System.err.println(e.getMessage());
System.exit(-1);
}
Lexicon lexicon = new Lexicon(fileReader);
Parser parser = new Parser(lexicon);
parser.run();
}
}
|
Remove unused code identified by the UCDetector
git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1636563 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.util.net;
public class Constants {
/**
* Name of the system property containing
* the tomcat instance installation path
*/
public static final String CATALINA_BASE_PROP = "catalina.base";
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.util.net;
public class Constants {
/**
* Name of the system property containing
* the tomcat instance installation path
*/
public static final String CATALINA_BASE_PROP = "catalina.base";
/**
* Has security been turned on?
*/
public static final boolean IS_SECURITY_ENABLED =
(System.getSecurityManager() != null);
}
|
Fix indents, from 2 to 4 spaces.
|
# -*- coding: utf-8 -*-
from flask import current_app, g
from flask.ext.script import Manager, Server, prompt_bool
from massa import create_app
manager = Manager(create_app)
manager.add_option('-c', '--config', dest='config', required=False)
manager.add_command('runserver', Server(
use_debugger = True,
use_reloader = True,
host = '0.0.0.0',
port = 5000,
))
@manager.command
def db_create_tables():
"""Create all the db tables."""
current_app.preprocess_request()
db = g.sl('db')
db.create_tables()
@manager.command
def db_drop_tables():
"""Drop all the db tables."""
if prompt_bool('Are you sure you want to drop all the db tables?'):
current_app.preprocess_request()
db = g.sl('db')
db.drop_tables()
@manager.command
def db_recreate_tables():
"""Drop and create all the db tables."""
if prompt_bool('Are you sure you want to recreate all the db tables?'):
current_app.preprocess_request()
db = g.sl('db')
db.drop_tables()
db.create_tables()
if __name__ == '__main__':
manager.run()
|
# -*- coding: utf-8 -*-
from flask import current_app, g
from flask.ext.script import Manager, Server, prompt_bool
from massa import create_app
manager = Manager(create_app)
manager.add_option('-c', '--config', dest='config', required=False)
manager.add_command('runserver', Server(
use_debugger = True,
use_reloader = True,
host = '0.0.0.0',
port = 5000,
))
@manager.command
def db_create_tables():
"""Create all the db tables."""
current_app.preprocess_request()
db = g.sl('db')
db.create_tables()
@manager.command
def db_drop_tables():
"""Drop all the db tables."""
if prompt_bool('Are you sure you want to drop all the db tables?'):
current_app.preprocess_request()
db = g.sl('db')
db.drop_tables()
@manager.command
def db_recreate_tables():
"""Drop and create all the db tables."""
if prompt_bool('Are you sure you want to recreate all the db tables?'):
current_app.preprocess_request()
db = g.sl('db')
db.drop_tables()
db.create_tables()
if __name__ == '__main__':
manager.run()
|
Use `find_packages()` instead of naming packages
The `templatetags/` files were missed because they were not named. Using
`find_packages()` will ensure this does not happen again.
|
#!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='django-bleach',
version="0.1.2",
description='Easily use bleach with Django models and templates',
author='Tim Heap',
author_email='heap.tim@gmail.com',
url='https://bitbucket.org/ionata/django-bleach',
packages=find_packages(),
install_requires=['bleach'],
package_data={},
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
)
|
#!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='django-bleach',
version="0.1.2",
description='Easily use bleach with Django models and templates',
author='Tim Heap',
author_email='heap.tim@gmail.com',
url='https://bitbucket.org/ionata/django-bleach',
packages=['django_bleach'],
install_requires=['bleach'],
package_data={},
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
)
|
Allow log time to be passed into logger
|
import sqlite3
import time
class SQLiteLogger:
def __init__(self, filename="test.db"):
self.filename = filename
self.connection = None
def __enter__(self):
try:
with open(self.filename):
self.connection = sqlite3.connect(self.filename)
except IOError:
self.connection = sqlite3.connect(self.filename)
cursor = self.connection.cursor()
cursor.execute('''CREATE TABLE readings
(date real, device text, property text, value real)''')
self.connection.commit()
return self
def __exit__(self, type, value, traceback):
self.connection.close()
self.connection = None
def log(self, device, property, value, t=None):
if t is None:
t = time.time()
values = (t, device, property, value)
cursor = self.connection.cursor()
cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values)
self.connection.commit()
|
import sqlite3
import time
class SQLiteLogger:
def __init__(self, filename="test.db"):
self.filename = filename
self.connection = None
def __enter__(self):
try:
with open(self.filename):
self.connection = sqlite3.connect(self.filename)
except IOError:
self.connection = sqlite3.connect(self.filename)
cursor = self.connection.cursor()
cursor.execute('''CREATE TABLE readings
(date real, device text, property text, value real)''')
self.connection.commit()
return self
def __exit__(self, type, value, traceback):
self.connection.close()
self.connection = None
def log(self, device, property, value):
now = time.time()
values = (now, device, property, value)
cursor = self.connection.cursor()
cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values)
self.connection.commit()
|
:new: Support comma separated watch targets in cli
|
#!/usr/bin/env node
'use strict'
process.title = 'ucompiler'
require('debug').enable('UCompiler:*')
var UCompiler = require('..')
var knownCommands = ['go', 'watch']
var parameters = process.argv.slice(2)
if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
console.log('Usage: ucompiler go|watch [path]')
process.exit(0)
}
const options = {
save: true,
saveIncludedFiles: false,
errorCallback: function(e) {
console.log(e.stack)
}
}
if (parameters[0] === 'go') {
UCompiler.compile(process.cwd(), options, parameters[1] || null).then(function(result) {
if (!result.status) {
process.exit(1)
}
}, function(e) {
console.error(e.stack)
process.exit(1)
})
} else if (parameters[0] === 'watch') {
UCompiler.watch(
process.cwd(),
options,
parameters[1] ?
parameters[1]
.split(',')
.map(function(_) { return _.trim()})
.filter(function(_) { return _}) : parameters[1]
).catch(e => console.log(e.stack))
}
|
#!/usr/bin/env node
'use strict'
process.title = 'ucompiler'
require('debug').enable('UCompiler:*')
var UCompiler = require('..')
var knownCommands = ['go', 'watch']
var parameters = process.argv.slice(2)
if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
console.log('Usage: ucompiler go|watch [path]')
process.exit(0)
}
const options = {
save: true,
saveIncludedFiles: false,
errorCallback: function(e) {
console.log(e.stack)
}
}
if (parameters[0] === 'go') {
UCompiler.compile(process.cwd(), options, parameters[1] || null).then(function(result) {
if (!result.status) {
process.exit(1)
}
}, function(e) {
console.error(e.stack)
process.exit(1)
})
} else if (parameters[0] === 'watch') {
UCompiler.watch(process.cwd(), options, parameters[1] ? [parameters[1]] : []).catch(e => console.log(e.stack))
}
|
Change `print` utility function to print repl prompt on end.
|
/* vim:set ts=2 sw=2 sts=2 expandtab */
/*jshint asi: true undef: true es5: true node: true browser: true devel: true
forin: true latedef: false globalstrict: true */
'use strict';
var reduce = require('./accumulator').reduce;
var when = require('eventual/eventual').when;
function print(source) {
var open = false
var promise = reduce(source, function(_, value) {
if (!open) process.stdout.write('<stream ')
open = true
process.stdout.write(JSON.stringify(value, 2, 2) + ' ')
}, false)
when(promise, function() {
if (!open) process.stdout.write('<stream ')
process.stdout.write('/>\n> ')
}, function(error) {
if (!open) process.stdout.write('<stream ')
process.stdout.write('/Error: ')
process.stdout.write(error + ' ' + JSON.stringify(error, 2, 2))
process.stdout.write('>\n> ')
})
}
exports.print = print
|
/* vim:set ts=2 sw=2 sts=2 expandtab */
/*jshint asi: true undef: true es5: true node: true browser: true devel: true
forin: true latedef: false globalstrict: true */
'use strict';
var reduce = require('./accumulator').reduce;
var when = require('eventual/eventual').when;
function print(source) {
var open = false
var promise = reduce(source, function(_, value) {
if (!open) process.stdout.write('<stream ')
open = true
process.stdout.write(JSON.stringify(value, 2, 2) + ' ')
}, false)
when(promise, function() {
if (!open) process.stdout.write('<stream ')
process.stdout.write('/>\n')
}, function(error) {
if (!open) process.stdout.write('<stream ')
process.stdout.write('/Error: ')
process.stdout.write(error + ' ' + JSON.stringify(error, 2, 2))
process.stdout.write('>\n')
})
}
exports.print = print
|
[FIX] partner_industry_Secondary: Make api constrains multi to avoid error when create a company with 2 contacts
|
# Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta
# Copyright 2016 Tecnativa S.L. - Vicent Cubells
# Copyright 2018 Eficent Business and IT Consulting Services, S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, exceptions, fields, models, _
class ResPartner(models.Model):
_inherit = 'res.partner'
industry_id = fields.Many2one(string='Main Industry')
secondary_industry_ids = fields.Many2many(
comodel_name='res.partner.industry', string="Secondary Industries",
domain="[('id', '!=', industry_id)]")
@api.constrains('industry_id', 'secondary_industry_ids')
def _check_industries(self):
for partner in self:
if partner.industry_id in partner.secondary_industry_ids:
raise exceptions.ValidationError(
_('The main industry must be different '
'from the secondary industries.'))
|
# Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta
# Copyright 2016 Tecnativa S.L. - Vicent Cubells
# Copyright 2018 Eficent Business and IT Consulting Services, S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, exceptions, fields, models, _
class ResPartner(models.Model):
_inherit = 'res.partner'
industry_id = fields.Many2one(string='Main Industry')
secondary_industry_ids = fields.Many2many(
comodel_name='res.partner.industry', string="Secondary Industries",
domain="[('id', '!=', industry_id)]")
@api.constrains('industry_id', 'secondary_industry_ids')
def _check_industries(self):
if self.industry_id in self.secondary_industry_ids:
raise exceptions.ValidationError(
_('The main industry must be different '
'from the secondary industries.'))
|
Add extend and from to Id spec
|
function Id(a) {
this.value = a;
}
// Semigroup (value must also be a Semigroup)
Id.prototype.concat = function(b) {
return new Id(this.value.concat(b.value));
};
// Monoid (value must also be a Monoid)
Id.prototype.empty = function() {
return new Id(this.value.empty ? this.value.empty() : this.value.constructor.empty());
};
// Functor
Id.prototype.map = function(f) {
return new Id(f(this.value));
};
// Applicative
Id.prototype.ap = function(b) {
return new Id(this.value(b.value));
};
// Chain
Id.prototype.chain = function(f) {
return f(this.value);
};
// Extend
Id.prototype.extend = function(f){
return new Id(f(this.value));
}
// Monad
Id.of = function(a) {
return new Id(a);
};
// Comonad
Id.from = function(a){
return a.value;
}
if(typeof module == 'object') module.exports = Id;
|
function Id(a) {
this.value = a;
}
// Semigroup (value must also be a Semigroup)
Id.prototype.concat = function(b) {
return new Id(this.value.concat(b.value));
};
// Monoid (value must also be a Monoid)
Id.prototype.empty = function() {
return new Id(this.value.empty ? this.value.empty() : this.value.constructor.empty());
};
// Functor
Id.prototype.map = function(f) {
return new Id(f(this.value));
};
// Applicative
Id.prototype.ap = function(b) {
return new Id(this.value(b.value));
};
// Chain
Id.prototype.chain = function(f) {
return f(this.value);
};
// Monad
Id.of = function(a) {
return new Id(a);
};
if(typeof module == 'object') module.exports = Id;
|
Allow subdomain gateway to use http
go-ipfs 0.5.0 can use a subdomain as gateway to preserve origin security. This updates orbit.chat to be able to load without an https error.
|
'use strict'
import React from 'react'
import { render } from 'react-dom'
import { version } from '../package.json'
import redirectToHttps from './utils/https'
import { BigSpinner } from './components/Spinner'
import './styles/normalize.css'
import './styles/Fonts.scss'
import './styles/Main.scss'
import './styles/flaticon.css'
redirectToHttps(!(window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' || window.location.hostname === 'orbit.chat.ipns.localhost'))
const App = React.lazy(() => import(/* webpackChunkName: "App" */ './views/App'))
render(
<React.Suspense fallback={<BigSpinner />}>
<App />
</React.Suspense>,
document.getElementById('root')
)
console.info(`Version ${version} running in ${process.env.NODE_ENV} mode`)
|
'use strict'
import React from 'react'
import { render } from 'react-dom'
import { version } from '../package.json'
import redirectToHttps from './utils/https'
import { BigSpinner } from './components/Spinner'
import './styles/normalize.css'
import './styles/Fonts.scss'
import './styles/Main.scss'
import './styles/flaticon.css'
redirectToHttps(!(window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'))
const App = React.lazy(() => import(/* webpackChunkName: "App" */ './views/App'))
render(
<React.Suspense fallback={<BigSpinner />}>
<App />
</React.Suspense>,
document.getElementById('root')
)
console.info(`Version ${version} running in ${process.env.NODE_ENV} mode`)
|
Fix Highmaps exports from Highcharts base package
|
import { withSeriesType } from 'react-jsx-highcharts';
export {
Chart,
Credits,
Debug,
Loading,
Legend,
Series,
Subtitle,
Title,
Tooltip,
useHighcharts,
useChart,
useAxis,
useSeries,
useModifiedProps,
withHighcharts as withHighmaps,
withSeriesType
} from 'react-jsx-highcharts';
// Charts
export { default as HighchartsMapChart } from './components/HighchartsMapChart';
// Graph Parts
export { default as MapNavigation } from './components/MapNavigation';
export { default as XAxis } from './components/XAxis';
export { default as YAxis } from './components/YAxis';
// Series
const parentAxisId = { axisId: 'yAxis' };
export const MapBubbleSeries = withSeriesType('MapBubble', parentAxisId);
export const MapLineSeries = withSeriesType('MapLine', parentAxisId);
export const MapPointSeries = withSeriesType('MapPoint', parentAxisId);
export const MapSeries = withSeriesType('Map', parentAxisId);
|
import { withSeriesType } from 'react-jsx-highcharts';
export {
Chart,
Credits,
Debug,
Loading,
Legend,
Series,
Subtitle,
Title,
Tooltip,
HighchartsContext,
HighchartsChartContext,
HighchartsAxisContext,
HighchartsSeriesContext,
withHighcharts as withHighmaps,
withSeriesType
} from 'react-jsx-highcharts';
// Charts
export { default as HighchartsMapChart } from './components/HighchartsMapChart';
// Graph Parts
export { default as MapNavigation } from './components/MapNavigation';
export { default as XAxis } from './components/XAxis';
export { default as YAxis } from './components/YAxis';
// Series
const parentAxisId = { axisId: 'yAxis' };
export const MapBubbleSeries = withSeriesType('MapBubble', parentAxisId);
export const MapLineSeries = withSeriesType('MapLine', parentAxisId);
export const MapPointSeries = withSeriesType('MapPoint', parentAxisId);
export const MapSeries = withSeriesType('Map', parentAxisId);
|
Store stack analysis in the context
|
from behave import when, then
from features.src.support import helpers
from features.src.stackAnalyses import StackAnalyses
from pyshould import should_not
@when(u'I send Maven package manifest pom-effective.xml to stack analysis')
def when_send_manifest(context):
sa = StackAnalyses()
spaceName = helpers.getSpaceName()
codebaseUrl = sa.getCodebaseUrl()
stackAnalysesKey = sa.getReportKey(codebaseUrl)
helpers.setStackReportKey(stackAnalysesKey)
stackAnalysesKey | should_not.be_none().desc("Obtained Stack Analyses key")
context.sa = sa
@then(u'I should receive JSON response with stack analysis data')
def then_receive_stack_json(context):
spaceName = helpers.getSpaceName()
stackAnalysesKey = helpers.getStackReportKey()
reportText = context.sa.getStackReport(stackAnalysesKey)
reportText | should_not.be_none().desc("Obtained Stack Analyses Report")
|
from behave import when, then
from features.src.support import helpers
from features.src.stackAnalyses import StackAnalyses
from pyshould import should_not
@when(u'I send Maven package manifest pom-effective.xml to stack analysis')
def when_send_manifest(context):
global sa
sa = StackAnalyses()
spaceName = helpers.getSpaceName()
codebaseUrl = sa.getCodebaseUrl()
stackAnalysesKey = sa.getReportKey(codebaseUrl)
helpers.setStackReportKey(stackAnalysesKey)
stackAnalysesKey | should_not.be_none().desc("Obtained Stack Analyses key")
@then(u'I should receive JSON response with stack analysis data')
def then_receive_stack_json(context):
spaceName = helpers.getSpaceName()
stackAnalysesKey = helpers.getStackReportKey()
reportText = sa.getStackReport(stackAnalysesKey)
reportText | should_not.be_none().desc("Obtained Stack Analyses Report")
|
Fix index bench read range
|
const Benchmark = require('benchmark');
const benchmarks = require('beautify-benchmark');
const fs = require('fs-extra');
const Suite = new Benchmark.Suite('index');
Suite.on('start', () => fs.emptyDirSync('data'));
Suite.on('cycle', (event) => benchmarks.add(event.target));
Suite.on('complete', () => benchmarks.log());
Suite.on('error', (e) => console.log(e.target.error));
const Stable = require('event-storage');
const Latest = require('../index');
const WRITES = 1000;
function bench(index) {
index.open();
for (let i = 1; i<=WRITES; i++) {
index.add(new Stable.Index.Entry(i,2,4,8));
}
index.close();
let number;
index.open();
for (let entry of index.range(-WRITES + 1)) {
number = entry.number;
}
index.close();
if (number < WRITES) throw new Error('Not all entries were written! Last entry was '+number);
}
Suite.add('index [stable]', function() {
bench(new Stable.Index(this.cycles + '.index', { dataDirectory: 'data/stable' }));
});
Suite.add('index [latest]', function() {
bench(new Latest.Index(this.cycles + '.index', { dataDirectory: 'data/latest' }));
});
Suite.run();
|
const Benchmark = require('benchmark');
const benchmarks = require('beautify-benchmark');
const fs = require('fs-extra');
const Suite = new Benchmark.Suite('index');
Suite.on('start', () => fs.emptyDirSync('data'));
Suite.on('cycle', (event) => benchmarks.add(event.target));
Suite.on('complete', () => benchmarks.log());
Suite.on('error', (e) => console.log(e.target.error));
const Stable = require('event-storage');
const Latest = require('../index');
const WRITES = 1000;
function bench(index) {
index.open();
for (let i = 1; i<=WRITES; i++) {
index.add(new Stable.Index.Entry(i,2,4,8));
}
index.close();
let number;
index.open();
for (let entry of index.all()) {
number = entry.number;
}
index.close();
if (number < WRITES) throw new Error('Not all entries were written! Last entry was '+number);
}
Suite.add('index [stable]', function() {
bench(new Stable.Index(this.cycles + '.index', { dataDirectory: 'data/stable' }));
});
Suite.add('index [latest]', function() {
bench(new Latest.Index(this.cycles + '.index', { dataDirectory: 'data/latest' }));
});
Suite.run();
|
Add support for Meteor 1.2
|
// Meteor package definition.
Package.describe({
name: 'aramk:quill',
version: '0.1.0',
summary: 'Quill Rich Text Editor',
git: 'https://github.com/aramk/meteor-quill.git'
});
Package.onUse(function (api) {
api.versionsFrom('METEOR@1.2.0.1');
api.use([
'coffeescript',
'underscore',
'templating',
'jquery',
'less',
'trever:quill@0.0.5',
], 'client');
api.use([
'aldeed:autoform@5.4.1',
], 'client', {weak: true});
api.addFiles([
'src/quillToolbarAdvanced.html',
'src/quill.html',
'src/quill.coffee',
'src/quill.less'
], 'client');
});
|
// Meteor package definition.
Package.describe({
name: 'aramk:quill',
version: '0.1.0',
summary: 'Quill Rich Text Editor',
git: 'https://github.com/aramk/meteor-quill.git'
});
Package.onUse(function (api) {
api.versionsFrom('METEOR@0.9.0');
api.use([
'coffeescript',
'underscore',
'templating',
'jquery',
'less',
'trever:quill@0.0.5',
], 'client');
api.use([
'aldeed:autoform@5.4.1',
], 'client', {weak: true});
api.addFiles([
'src/quillToolbarAdvanced.html',
'src/quill.html',
'src/quill.coffee',
'src/quill.less'
], 'client');
});
|
Enable figlet to render text using custom fonts
Summary:
Figlet with more fonts will make Phabricator
```
_/ _/ _/ _/_/ _/
_/_/ _/ _/ _/ _/ _/_/ _/
_/ _/ _/ _/ _/ _/
_/ _/ _/ _/ _/ _/ _/_/
_/ _/ _/ _/ _/_/
_/_/_/ _/_/ _/_/ _/ _/_/ _/_/
_/ _/ _/ _/ _/ _/_/ _/_/_/_/
_/ _/ _/ _/ _/ _/ _/
_/ _/ _/ _/_/ _/ _/_/_/
_/
_/_/_/ _/_/ _/ _/_/ _/_/ _/ _/ _/_/_/
_/_/ _/_/_/_/ _/_/ _/ _/ _/ _/ _/ _/_/
_/_/ _/ _/ _/ _/ _/ _/ _/ _/_/
_/_/_/ _/_/_/ _/ _/ _/_/ _/_/_/ _/_/_/
```
Test Plan:
Use figlet in comment with no font/various fonts as argument (e.g. lean, script)
and see preview with no errors.
Reviewers: #blessed_reviewers, epriestley
Reviewed By: epriestley
CC: epriestley, aran
Differential Revision: https://secure.phabricator.com/D7815
|
<?php
final class PhabricatorRemarkupBlockInterpreterFiglet
extends PhutilRemarkupBlockInterpreter {
public function getInterpreterName() {
return 'figlet';
}
public function markupContent($content, array $argv) {
if (!Filesystem::binaryExists('figlet')) {
return $this->markupError(
pht('Unable to locate the `figlet` binary. Install figlet.'));
}
$font = idx($argv, 'font', 'standard');
$safe_font = preg_replace('/[^0-9a-zA-Z-_.]/', '', $font);
$future = id(new ExecFuture('figlet -f %s', $safe_font))
->setTimeout(15)
->write(trim($content, "\n"));
list($err, $stdout, $stderr) = $future->resolve();
if ($err) {
return $this->markupError(
pht(
'Execution of `figlet` failed:', $stderr));
}
if ($this->getEngine()->isTextMode()) {
return $stdout;
}
return phutil_tag(
'div',
array(
'class' => 'PhabricatorMonospaced remarkup-figlet',
),
$stdout);
}
}
|
<?php
final class PhabricatorRemarkupBlockInterpreterFiglet
extends PhutilRemarkupBlockInterpreter {
public function getInterpreterName() {
return 'figlet';
}
public function markupContent($content, array $argv) {
if (!Filesystem::binaryExists('figlet')) {
return $this->markupError(
pht('Unable to locate the `figlet` binary. Install figlet.'));
}
$future = id(new ExecFuture('figlet'))
->setTimeout(15)
->write(trim($content, "\n"));
list($err, $stdout, $stderr) = $future->resolve();
if ($err) {
return $this->markupError(
pht(
'Execution of `figlet` failed:', $stderr));
}
if ($this->getEngine()->isTextMode()) {
return $stdout;
}
return phutil_tag(
'div',
array(
'class' => 'PhabricatorMonospaced remarkup-figlet',
),
$stdout);
}
}
|
Fix pylama isort integration not to include check=True redundly
|
import os
import sys
from contextlib import contextmanager
from typing import Any, Dict, List
from pylama.lint import Linter as BaseLinter
from . import api
@contextmanager
def supress_stdout():
stdout = sys.stdout
with open(os.devnull, "w") as devnull:
sys.stdout = devnull
yield
sys.stdout = stdout
class Linter(BaseLinter):
def allow(self, path: str) -> bool:
"""Determine if this path should be linted."""
return path.endswith(".py")
def run(self, path: str, **meta: Any) -> List[Dict[str, Any]]:
"""Lint the file. Return an array of error dicts if appropriate."""
with supress_stdout():
if api.check_file(path):
return [
{"lnum": 0, "col": 0, "text": "Incorrectly sorted imports.", "type": "ISORT"}
]
else:
return []
|
import os
import sys
from contextlib import contextmanager
from typing import Any, Dict, List
from pylama.lint import Linter as BaseLinter
from . import api
@contextmanager
def supress_stdout():
stdout = sys.stdout
with open(os.devnull, "w") as devnull:
sys.stdout = devnull
yield
sys.stdout = stdout
class Linter(BaseLinter):
def allow(self, path: str) -> bool:
"""Determine if this path should be linted."""
return path.endswith(".py")
def run(self, path: str, **meta: Any) -> List[Dict[str, Any]]:
"""Lint the file. Return an array of error dicts if appropriate."""
with supress_stdout():
if api.check_file(path, check=True):
return [
{"lnum": 0, "col": 0, "text": "Incorrectly sorted imports.", "type": "ISORT"}
]
else:
return []
|
Add en_US translation as fallback
|
import translations from './translations/accessibility-cloud.js-widget/translations';
function findLocaleWithCountry(localeWithoutCountry) {
const regexp = new RegExp(`^${localeWithoutCountry}_`);
return Object.keys(translations).find(locale => locale.match(regexp));
}
function translate(string, locale) {
const localeWithoutCountry = locale.replace(/_[A-Z][A-Z]$/);
const localeHasCountry = locale !== localeWithoutCountry;
const localeWithDefaultCountry = localeHasCountry ? locale : findLocaleWithCountry(locale);
const defaultLocale = 'en_US';
const translation = translations[locale] || {};
const translationWithoutCountry = translations[localeWithoutCountry] || {};
const translationWithDefaultCountry = translations[localeWithDefaultCountry] || {};
const translationWithDefaultLocale = translations[defaultLocale] || {};
return translation[string] ||
translationWithoutCountry[string] ||
translationWithDefaultCountry[string] ||
translationWithDefaultLocale ||
string;
}
// Note that we don't support template strings for now.
// eslint-disable-next-line import/prefer-default-export
export function t(arg) {
// eslint-disable-next-line no-undef
return translate(arg, AccessibilityCloud.locale);
}
|
import translations from './translations/accessibility-cloud.js-widget/translations';
function findLocaleWithCountry(localeWithoutCountry) {
const regexp = new RegExp(`^${localeWithoutCountry}_`);
return Object.keys(translations).find(locale => locale.match(regexp));
}
function translate(string, locale) {
const localeWithoutCountry = locale.replace(/_[A-Z][A-Z]$/);
const localeHasCountry = locale !== localeWithoutCountry;
const localeWithDefaultCountry = localeHasCountry ? locale : findLocaleWithCountry(locale);
const translation = translations[locale] || {};
const translationWithoutCountry = translations[localeWithoutCountry] || {};
const translationWithDefaultCountry = translations[localeWithDefaultCountry] || {};
return translation[string] ||
translationWithoutCountry[string] ||
translationWithDefaultCountry[string] ||
string;
}
// Note that we don't support template strings for now.
// eslint-disable-next-line import/prefer-default-export
export function t(arg) {
// eslint-disable-next-line no-undef
return translate(arg, AccessibilityCloud.locale);
}
|
Fix issue with time field string conversion (there wasn't any).
git-svn-id: 0503cfb7d358eaa9bd718f348f448f10022ea703@955332 13f79535-47bb-0310-9956-ffa450edef68
|
/* $Id$ */
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lcf.core.interfaces;
/** This is a class which uniquely identifiers a time marker, for the database layer.
*/
public class TimeMarker
{
public static final String _rcsid = "@(#)$Id$";
long timeValue;
/** Constructor.
*@param timeValue is the time value.
*/
public TimeMarker(long timeValue)
{
this.timeValue = timeValue;
}
public long longValue()
{
return timeValue;
}
public String toString()
{
return new Long(timeValue).toString();
}
}
|
/* $Id$ */
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lcf.core.interfaces;
/** This is a class which uniquely identifiers a time marker, for the database layer.
*/
public class TimeMarker
{
public static final String _rcsid = "@(#)$Id$";
long timeValue;
/** Constructor.
*@param timeValue is the time value.
*/
public TimeMarker(long timeValue)
{
this.timeValue = timeValue;
}
public long longValue()
{
return timeValue;
}
}
|
Use ssl:cert isntead of SSL_CERT from nconf
|
var fs = require('fs')
var path = require('path')
var config = require('../lib/config')
var features = require('../lib/features')
module.exports = function(req, res) {
fs.readFile(path.join(__dirname+'/../package.json'), function(error, packagejson) {
fs.readFile(config.get('ssl:cert'), function(error, certificate) {
var properties = {
documentation: "https://codius.org/docs/using-codius/getting-started",
version: JSON.parse(packagejson.toString()).version,
billing: [],
public_key: certificate.toString()
}
if (features.isEnabled('RIPPLE_BILLING')) {
properties.billing.push({
network: 'ripple',
cpu_per_xrp: parseFloat(config.get('compute_units_per_drop')) * 1000000
})
}
if (features.isEnabled('BITCOIN_BILLING')) {
properties.billing.push({
network: 'bitcoin',
cpu_per_bitcoin: config.get('compute_units_per_bitcoin')
})
}
res.status(200).send({
properties: properties
})
})
})
}
|
var fs = require('fs')
var path = require('path')
var config = require('../lib/config')
var features = require('../lib/features')
module.exports = function(req, res) {
fs.readFile(path.join(__dirname+'/../package.json'), function(error, packagejson) {
fs.readFile(config.get('SSL_CERT'), function(error, certificate) {
var properties = {
documentation: "https://codius.org/docs/using-codius/getting-started",
version: JSON.parse(packagejson.toString()).version,
billing: [],
public_key: certificate.toString()
}
if (features.isEnabled('RIPPLE_BILLING')) {
properties.billing.push({
network: 'ripple',
cpu_per_xrp: parseFloat(config.get('compute_units_per_drop')) * 1000000
})
}
if (features.isEnabled('BITCOIN_BILLING')) {
properties.billing.push({
network: 'bitcoin',
cpu_per_bitcoin: config.get('compute_units_per_bitcoin')
})
}
res.status(200).send({
properties: properties
})
})
})
}
|
Add isAnswerInDomain validation method [ci skip]
|
/*
* Copyright 2015 Dmitry Ustalov
*
* 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 mtsar.api.validation;
import io.dropwizard.validation.ValidationMethod;
import mtsar.api.Answer;
import mtsar.api.Task;
import java.util.ArrayList;
import java.util.List;
public class TaskAnswerValidation {
private final Task task;
private final Answer answer;
public TaskAnswerValidation(Task task, Answer answer) {
this.task = task;
this.answer = answer;
}
@ValidationMethod(message = "#answer-not-in-task: task has no such an answer in possible ones")
public boolean isAnswerInDomain() {
final List<String> answers = new ArrayList<>(answer.getAnswers());
answers.removeAll(task.getAnswers());
return answers.isEmpty();
}
@ValidationMethod(message = "#task-single-no-answer: task type 'single' requires one answer")
public boolean isAnswerPresentForTypeSingle() {
return !task.getType().equalsIgnoreCase("single") || answer.getAnswers().size() == 1;
}
}
|
/*
* Copyright 2015 Dmitry Ustalov
*
* 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 mtsar.api.validation;
import io.dropwizard.validation.ValidationMethod;
import mtsar.api.Answer;
import mtsar.api.Task;
public class TaskAnswerValidation {
private final Task task;
private final Answer answer;
public TaskAnswerValidation(Task task, Answer answer) {
this.task = task;
this.answer = answer;
}
@ValidationMethod(message = "#task-single-no-answer: task type 'single' requires one answer")
public boolean isAnswerPresentForTypeSingle() {
return !task.getType().equalsIgnoreCase("single") || answer.getAnswers().size() == 1;
}
}
|
Make linestyles2 test runnable (should probably fix this for other tests)
|
#!/usr/bin/env python
from boomslang import Line, Plot
from ImageComparisonTestCase import ImageComparisonTestCase
import unittest
class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase):
def __init__(self, testCaseName):
super(LineStyles2Test, self).__init__(testCaseName)
self.imageName = "linestyles2.png"
def constructImage(self):
plot = Plot()
for i in xrange(6):
line = Line()
line.xValues = xrange(5)
line.yValues = [(i+1) * x for x in line.xValues]
line.label = "Line %d" % (i + 1)
plot.add(line)
plot.addLineColor("red")
plot.addLineColor("blue")
plot.addLineColor("green")
plot.addMarker('')
plot.addMarker('x')
plot.hasLegend(columns=2)
plot.save(self.imageName)
ImageComparisonTestCase.register(LineStyles2Test)
if __name__ == "__main__":
test = LineStyles2Test("testImageComparison")
test.constructImage()
|
#!/usr/bin/env python
from boomslang import Line, Plot
from ImageComparisonTestCase import ImageComparisonTestCase
import unittest
class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase):
def __init__(self, testCaseName):
super(LineStyles2Test, self).__init__(testCaseName)
self.imageName = "linestyles2.png"
def constructImage(self):
plot = Plot()
for i in xrange(6):
line = Line()
line.xValues = xrange(5)
line.yValues = [(i+1) * x for x in line.xValues]
line.label = "Line %d" % (i + 1)
plot.add(line)
plot.addLineColor("red")
plot.addLineColor("blue")
plot.addLineColor("green")
plot.addMarker('')
plot.addMarker('x')
plot.hasLegend(columns=2)
plot.save(self.imageName)
ImageComparisonTestCase.register(LineStyles2Test)
if __name__ == "__main__":
test = LineStyles2Test()
test.constructImage()
|
Add default saturation, brightness, contrast value
|
import React from 'react';
import { requireNativeComponent } from 'react-native';
import PropTypes from 'prop-types';
const RNPdfScanner = requireNativeComponent('RNPdfScanner', PdfScanner);
class PdfScanner extends React.Component {
sendOnPictureTakenEvent(event) {
return this.props.onPictureTaken(event.nativeEvent);
}
render() {
return (
<RNPdfScanner
{...this.props}
onPictureTaken={this.sendOnPictureTakenEvent.bind(this)}
brightness={this.props.brightness||0}
saturation={this.props.saturation||1}
contrast={this.props.contrast||1}
/>;
);
}
}
PdfScanner.propTypes = {
onPictureTaken: PropTypes.func,
overlayColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
enableTorch: PropTypes.bool,
saturation: PropTypes.number,
brightness: PropTypes.number,
contrast: PropTypes.number,
};
export default PdfScanner;
|
import React from 'react';
import { requireNativeComponent } from 'react-native';
import PropTypes from 'prop-types';
const RNPdfScanner = requireNativeComponent('RNPdfScanner', PdfScanner);
class PdfScanner extends React.Component {
sendOnPictureTakenEvent(event) {
return this.props.onPictureTaken(event.nativeEvent);
}
render() {
return (
<RNPdfScanner
{...this.props}
onPictureTaken={this.sendOnPictureTakenEvent.bind(this)}
/>
);
}
}
PdfScanner.propTypes = {
onPictureTaken: PropTypes.func,
overlayColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
enableTorch: PropTypes.bool,
saturation: PropTypes.number,
brightness: PropTypes.number,
contrast: PropTypes.number,
};
export default PdfScanner;
|
Use libjass.min.js for production build.
|
/**
* libjass-demo-react
*
* https://github.com/Arnavion/libjass-demo-react
*
* Copyright 2016 Arnav Singh
*
* 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.
*/
var path = require("path");
var webpack = require("webpack");
var config = require("./webpack.config");
config.plugins = [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: '"production"'
}
})
];
config.resolve.alias["libjass"] = path.resolve(require.resolve("libjass"), "..", "libjass.min.js");
module.exports = config;
|
/**
* libjass-demo-react
*
* https://github.com/Arnavion/libjass-demo-react
*
* Copyright 2016 Arnav Singh
*
* 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.
*/
var webpack = require("webpack");
var config = require("./webpack.config");
config.plugins = [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: '"production"'
}
})
];
module.exports = config;
|
[Command] Check base command returns a UUID on creation
|
<?php
namespace SmoothPhp\CommandBus;
use Ramsey\Uuid\Uuid;
use SmoothPhp\Contracts\CommandBus\Command;
/**
* Class Command
* @package SmoothPhp\CommandBus
* @author Simon Bennett <simon.bennett@smoothphp.com>
*/
abstract class BaseCommand implements Command
{
/**
* @var string
*/
private $commandId;
/**
* Give the command a Uuid, Used to logging and auditing
*/
public function __construct()
{
$this->commandId = (string)Uuid::uuid4();
}
/**
* @return string
*/
public function __toString()
{
return get_class($this) . ':' . $this->commandId;
}
/**
* @return string
*/
public function getCommandId()
{
return $this->commandId;
}
}
|
<?php
namespace SmoothPhp\CommandBus;
use Ramsey\Uuid\Uuid;
use SmoothPhp\Contracts\CommandBus\Command;
/**
* Class Command
* @package SmoothPhp\CommandBus
* @author Simon Bennett <simon.bennett@smoothphp.com>
*/
abstract class BaseCommand implements Command
{
/**
* @var string
*/
public $commandId;
/**
* Give the command a Uuid, Used to logging and auditing
*/
public function __construct()
{
$this->commandId = (string)Uuid::uuid4();
}
/**
* @return string
*/
public function __toString()
{
return get_class($this) . ':' . $this->commandId;
}
/**
* @return string
*/
public function getCommandId()
{
return $this->commandId;
}
}
|
Use an additional function to scope everything properly
|
import os.path
import unittest
import munge_js
class TestCase(unittest.TestCase):
pass
TestCase.assert_false = TestCase.assertFalse
TestCase.assert_equal = TestCase.assertEqual
fixture_root = os.path.join(os.path.dirname(__file__), 'fixtures')
def get_fixtures():
dir = os.path.join(fixture_root, 'input')
files = os.listdir(dir)
files.sort()
names = [file[0:len(file)-3] for file in files if file.endswith('.js')]
return names
class MungeJsTest(TestCase):
pass
def generate(fixture):
def test(self):
with open(os.path.join(fixture_root, 'input', fixture + '.js')) as f:
input = f.read()
with open(os.path.join(fixture_root, 'output', fixture + '.js')) as f:
expected = f.read()
actual = munge_js.convert(input)
self.assert_equal(expected, actual)
return test
for fixture in get_fixtures():
setattr(MungeJsTest, 'test_' + fixture, generate(fixture))
if __name__ == '__main__':
unittest.main()
|
import os.path
import unittest
import munge_js
class TestCase(unittest.TestCase):
pass
TestCase.assert_false = TestCase.assertFalse
TestCase.assert_equal = TestCase.assertEqual
fixture_root = os.path.join(os.path.dirname(__file__), 'fixtures')
def get_fixtures():
dir = os.path.join(fixture_root, 'input')
files = os.listdir(dir)
files.sort()
names = [file[0:len(file)-3] for file in files if file.endswith('.js')]
return names
class MungeJsTest(TestCase):
pass
for fixture in get_fixtures():
def test(self):
with open(os.path.join(fixture_root, 'input', fixture + '.js')) as f:
input = f.read()
with open(os.path.join(fixture_root, 'output', fixture + '.js')) as f:
expected = f.read()
actual = munge_js.convert(input)
self.assert_equal(expected, actual)
setattr(MungeJsTest, 'test_' + fixture, test)
if __name__ == '__main__':
unittest.main()
|
Fix issue found by go vet
|
//
// Copyright (c) 2014 The heketi Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package requests
// Structs for messages
type VolumeInfoResp struct {
Name string `json:"name"`
Size uint64 `json:"size"`
Id uint64 `json:"id"`
}
type VolumeCreateRequest struct {
Name string `json:"name"`
Size uint64 `json:"size"`
}
type VolumeListResponse struct {
Volumes []VolumeInfoResp `json:"volumes"`
}
|
//
// Copyright (c) 2014 The heketi Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package requests
// Structs for messages
type VolumeInfoResp struct {
Name string `json:"name"`
Size uint64 `json:"size"`
Id uint64 `json: "id"`
}
type VolumeCreateRequest struct {
Name string `json:"name"`
Size uint64 `json:"size"`
}
type VolumeListResponse struct {
Volumes []VolumeInfoResp `json:"volumes"`
}
|
Set port to env variable or 8080.
|
var express = require('express');
var favicon = require('serve-favicon');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
function configure() {
var app = express();
app.set('views', path.join(__dirname, '..', 'views'));
app.set('view engine', 'jade');
app.set('port', process.env.PORT | 8080);
app.use(favicon(path.join(__dirname, '..', 'public/images', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '..', 'public')));
app.use(passport.initialize());
app.use(passport.session());
if (app.get('env') === 'development') {
app.locals.pretty = true;
}
return app;
}
module.exports = {
configure: configure
};
|
var express = require('express');
var favicon = require('serve-favicon');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
function configure() {
var app = express();
app.set('views', path.join(__dirname, '..', 'views'));
app.set('view engine', 'jade');
app.set('port', 8080);
app.use(favicon(path.join(__dirname, '..', 'public/images', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '..', 'public')));
app.use(passport.initialize());
app.use(passport.session());
if (app.get('env') === 'development') {
app.locals.pretty = true;
}
return app;
}
module.exports = {
configure: configure
};
|
Update the version to 3.1.1
Change-Id: Ia24c8a9e62330243fa7413a649f885c2a40dd4fb
|
# Copyright 2012-2014 Hewlett Packard Development Company, L.P.
# 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.
"""
HP 3PAR Client.
:Author: Walter A. Boring IV
:Author: Kurt Martin
:Copyright: Copyright 2012-2014, Hewlett Packard Development Company, L.P.
:License: Apache v2.0
"""
version_tuple = (3, 1, 1)
def get_version_string():
"""Current version of HP3PARClient."""
if isinstance(version_tuple[-1], str):
return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1]
return '.'.join(map(str, version_tuple))
version = get_version_string()
|
# Copyright 2012-2014 Hewlett Packard Development Company, L.P.
# 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.
"""
HP 3PAR Client.
:Author: Walter A. Boring IV
:Author: Kurt Martin
:Copyright: Copyright 2012-2014, Hewlett Packard Development Company, L.P.
:License: Apache v2.0
"""
version_tuple = (3, 1, 0)
def get_version_string():
"""Current version of HP3PARClient."""
if isinstance(version_tuple[-1], str):
return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1]
return '.'.join(map(str, version_tuple))
version = get_version_string()
|
Fix label on "new message" form
|
from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
|
from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(widget=forms.Textarea)
|
Check that it returns the same class
|
<?php
/*
* This file is part of Laravel Algolia.
*
* (c) Vincent Klaiber <hello@vinkla.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Vinkla\Tests\Algolia;
use AlgoliaSearch\Client;
use GrahamCampbell\TestBenchCore\ServiceProviderTrait;
use Vinkla\Algolia\AlgoliaFactory;
use Vinkla\Algolia\AlgoliaManager;
/**
* This is the service provider test class.
*
* @author Vincent Klaiber <hello@vinkla.com>
*/
class ServiceProviderTest extends AbstractTestCase
{
use ServiceProviderTrait;
public function testAlgoliaFactoryIsInjectable()
{
$this->assertIsInjectable(AlgoliaFactory::class);
}
public function testAlgoliaManagerIsInjectable()
{
$this->assertIsInjectable(AlgoliaManager::class);
}
public function testBindings()
{
$this->assertIsInjectable(Client::class);
$original = $this->app['algolia.connection'];
$this->app['algolia']->reconnect();
$new = $this->app['algolia.connection'];
$this->assertNotSame($original, $new);
$this->assertSame(get_class($original), get_class($new));
}
}
|
<?php
/*
* This file is part of Laravel Algolia.
*
* (c) Vincent Klaiber <hello@vinkla.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Vinkla\Tests\Algolia;
use AlgoliaSearch\Client;
use GrahamCampbell\TestBenchCore\ServiceProviderTrait;
use Vinkla\Algolia\AlgoliaFactory;
use Vinkla\Algolia\AlgoliaManager;
/**
* This is the service provider test class.
*
* @author Vincent Klaiber <hello@vinkla.com>
*/
class ServiceProviderTest extends AbstractTestCase
{
use ServiceProviderTrait;
public function testAlgoliaFactoryIsInjectable()
{
$this->assertIsInjectable(AlgoliaFactory::class);
}
public function testAlgoliaManagerIsInjectable()
{
$this->assertIsInjectable(AlgoliaManager::class);
}
public function testBindings()
{
$this->assertIsInjectable(Client::class);
$original = $this->app['algolia.connection'];
$this->app['algolia']->reconnect();
$new = $this->app['algolia.connection'];
$this->assertNotSame($original, $new);
$this->assertEquals($original, $new);
}
}
|
Fix version tests - don't sort, just reverse
|
# Tests
import os
from tests.base import BaseTestZSTD, log
class TestZSTD(BaseTestZSTD):
def setUp(self):
if os.getenv("ZSTD_EXTERNAL"):
self.ZSTD_EXTERNAL = True
self.VERSION = os.getenv("VERSION")
self.PKG_VERSION = os.getenv("PKG_VERSION")
log.info("VERSION=%r" % self.VERSION)
log.info("PKG_VERSION=%r" % self.PKG_VERSION)
v = [int(n) for n in reversed(self.VERSION.split("."))]
log.info("v=%r" % (v,))
self.VERSION_INT = 0
i = 0
for n in v:
self.VERSION_INT += n * 100**i
i += 1
log.info("VERSION_INT=%r" % self.VERSION_INT)
def test_module_version(self):
BaseTestZSTD.helper_version(self)
def test_library_version(self):
BaseTestZSTD.helper_zstd_version(self)
def test_library_version_number(self):
BaseTestZSTD.helper_zstd_version_number(self)
if __name__ == '__main__':
unittest.main()
|
# Tests
import os
from tests.base import BaseTestZSTD
class TestZSTD(BaseTestZSTD):
def setUp(self):
if os.getenv("ZSTD_EXTERNAL"):
self.ZSTD_EXTERNAL = True
self.VERSION = os.getenv("VERSION")
self.PKG_VERSION = os.getenv("PKG_VERSION")
v = [int(n) for n in self.VERSION.split(".")]
v = sorted(v, reverse=True)
self.VERSION_INT = 0
i = 0
for n in v:
self.VERSION_INT += n * 100**i
i += 1
def test_module_version(self):
BaseTestZSTD.helper_version(self)
def test_library_version(self):
BaseTestZSTD.helper_zstd_version(self)
def test_library_version_number(self):
BaseTestZSTD.helper_zstd_version_number(self)
if __name__ == '__main__':
unittest.main()
|
Fix line length for code style check
|
<?php
use Symfony\Component\Dotenv\Dotenv;
require dirname(__DIR__).'/vendor/autoload.php';
// Load cached env vars if the .env.local.php file exists
// Run "composer dump-env prod" to create it (requires symfony/flex >=1.2)
if (is_array($env = @include dirname(__DIR__).'/.env.local.php')) {
$_SERVER += $env;
$_ENV += $env;
} elseif (!class_exists(Dotenv::class)) {
throw new RuntimeException(
'Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.'
);
} else {
// load all the .env files
(new Dotenv())->loadEnv(dirname(__DIR__).'/.env');
}
$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) ?: 'dev';
$_SERVER['APP_DEBUG'] = $_SERVER['APP_DEBUG'] ?? $_ENV['APP_DEBUG'] ?? 'prod' !== $_SERVER['APP_ENV'];
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = (int) $_SERVER['APP_DEBUG'] ||
filter_var($_SERVER['APP_DEBUG'], FILTER_VALIDATE_BOOLEAN) ? '1' : '0';
|
<?php
use Symfony\Component\Dotenv\Dotenv;
require dirname(__DIR__).'/vendor/autoload.php';
// Load cached env vars if the .env.local.php file exists
// Run "composer dump-env prod" to create it (requires symfony/flex >=1.2)
if (is_array($env = @include dirname(__DIR__).'/.env.local.php')) {
$_SERVER += $env;
$_ENV += $env;
} elseif (!class_exists(Dotenv::class)) {
throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
} else {
// load all the .env files
(new Dotenv())->loadEnv(dirname(__DIR__).'/.env');
}
$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) ?: 'dev';
$_SERVER['APP_DEBUG'] = $_SERVER['APP_DEBUG'] ?? $_ENV['APP_DEBUG'] ?? 'prod' !== $_SERVER['APP_ENV'];
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = (int) $_SERVER['APP_DEBUG'] || filter_var($_SERVER['APP_DEBUG'], FILTER_VALIDATE_BOOLEAN) ? '1' : '0';
|
Fix codacy: Fields should be declared at the top of the class
|
package cgeo.geocaching.models;
import cgeo.geocaching.connector.trackable.TrackableBrand;
import cgeo.geocaching.enumerations.LogTypeTrackable;
import org.apache.commons.lang3.StringUtils;
public final class TrackableLog {
public final int ctl;
public final int id;
public final String geocode;
public final String trackCode;
public final String name;
public final TrackableBrand brand;
public LogTypeTrackable action = LogTypeTrackable.DO_NOTHING; // base.logTrackablesAction - no action
public TrackableLog(final String geocode, final String trackCode, final String name, final int id, final int ctl, final TrackableBrand brand) {
this.geocode = geocode;
this.trackCode = trackCode;
this.name = name;
this.id = id;
this.ctl = ctl;
this.brand = brand;
}
public void setAction(final LogTypeTrackable logTypeTrackable) {
action = logTypeTrackable;
}
@Override
public int hashCode() {
return StringUtils.defaultString(trackCode).hashCode();
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof TrackableLog)) {
return false;
}
final TrackableLog tb = (TrackableLog) obj;
return StringUtils.defaultString(tb.trackCode).equals(trackCode);
}
}
|
package cgeo.geocaching.models;
import cgeo.geocaching.connector.trackable.TrackableBrand;
import cgeo.geocaching.enumerations.LogTypeTrackable;
import org.apache.commons.lang3.StringUtils;
public final class TrackableLog {
public TrackableLog(final String geocode, final String trackCode, final String name, final int id, final int ctl, final TrackableBrand brand) {
this.geocode = geocode;
this.trackCode = trackCode;
this.name = name;
this.id = id;
this.ctl = ctl;
this.brand = brand;
}
public final int ctl;
public final int id;
public final String geocode;
public final String trackCode;
public final String name;
public final TrackableBrand brand;
public LogTypeTrackable action = LogTypeTrackable.DO_NOTHING; // base.logTrackablesAction - no action
public void setAction(final LogTypeTrackable logTypeTrackable) {
action = logTypeTrackable;
}
@Override
public int hashCode() {
return StringUtils.defaultString(trackCode).hashCode();
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof TrackableLog)) {
return false;
}
final TrackableLog tb = (TrackableLog) obj;
return StringUtils.defaultString(tb.trackCode).equals(trackCode);
}
}
|
Replace deprecated global function wfGetCache()
wfGetCache() is deprecated since 1.32
Bug: T293928
Change-Id: I61197c46e8d036ada703083c571504acb95f1ebb
|
<?php
use GoogleLogin\AllowedDomains\ArrayAllowedDomainsStore;
use GoogleLogin\AllowedDomains\CachedAllowedDomainsStore;
use GoogleLogin\AllowedDomains\DBAllowedDomainsStore;
use GoogleLogin\Constants;
use GoogleLogin\GoogleIdProvider;
use GoogleLogin\GoogleLogin;
use GoogleLogin\GoogleUserMatching;
use MediaWiki\MediaWikiServices;
return [
Constants::SERVICE_ALLOWED_DOMAINS_STORE => static function ( MediaWikiServices $services ) {
$glConfig = GoogleLogin::getGLConfig();
if (
is_array( $glConfig->get( 'GLAllowedDomains' ) ) &&
!$glConfig->get( 'GLAllowedDomainsDB' )
) {
return new ArrayAllowedDomainsStore( $glConfig->get( 'GLAllowedDomains' ) );
} elseif ( $glConfig->get( 'GLAllowedDomainsDB' ) ) {
$dbBackedStore = new DBAllowedDomainsStore( $services->getDBLoadBalancer() );
$cache = ObjectCache::getInstance( CACHE_ACCEL );
return new CachedAllowedDomainsStore( $dbBackedStore, $cache );
}
return null;
},
Constants::SERVICE_GOOGLE_USER_MATCHING => static function ( MediaWikiServices $services ) {
return new GoogleUserMatching( $services->getDBLoadBalancer() );
},
Constants::SERVICE_GOOGLE_ID_PROVIDER => static function ( MediaWikiServices $services ) {
return new GoogleIdProvider( $services->getDBLoadBalancer() );
}
];
|
<?php
use GoogleLogin\AllowedDomains\ArrayAllowedDomainsStore;
use GoogleLogin\AllowedDomains\CachedAllowedDomainsStore;
use GoogleLogin\AllowedDomains\DBAllowedDomainsStore;
use GoogleLogin\Constants;
use GoogleLogin\GoogleIdProvider;
use GoogleLogin\GoogleLogin;
use GoogleLogin\GoogleUserMatching;
use MediaWiki\MediaWikiServices;
return [
Constants::SERVICE_ALLOWED_DOMAINS_STORE => static function ( MediaWikiServices $services ) {
$glConfig = GoogleLogin::getGLConfig();
if (
is_array( $glConfig->get( 'GLAllowedDomains' ) ) &&
!$glConfig->get( 'GLAllowedDomainsDB' )
) {
return new ArrayAllowedDomainsStore( $glConfig->get( 'GLAllowedDomains' ) );
} elseif ( $glConfig->get( 'GLAllowedDomainsDB' ) ) {
$dbBackedStore = new DBAllowedDomainsStore( $services->getDBLoadBalancer() );
$cache = wfGetCache( CACHE_ACCEL );
return new CachedAllowedDomainsStore( $dbBackedStore, $cache );
}
return null;
},
Constants::SERVICE_GOOGLE_USER_MATCHING => static function ( MediaWikiServices $services ) {
return new GoogleUserMatching( $services->getDBLoadBalancer() );
},
Constants::SERVICE_GOOGLE_ID_PROVIDER => static function ( MediaWikiServices $services ) {
return new GoogleIdProvider( $services->getDBLoadBalancer() );
}
];
|
Add !images as Bing !image alias.
|
from aiohttp import BasicAuth
from plumeria import config
from plumeria.command import commands, CommandError
from plumeria.message import Response
from plumeria.util import http
from plumeria.util.ratelimit import rate_limit
SEARCH_URL = "https://api.datamarket.azure.com/Bing/Search/v1/Image"
api_key = config.create("bing", "key",
fallback="unset",
comment="An API key from Bing")
@commands.register("image", "images", ""i", category="Search")
@rate_limit()
async def image(message):
"""
Search Bing for an image.
"""
q = message.content.strip()
if not q:
raise CommandError("Search term required!")
r = await http.get(SEARCH_URL, params=[
('$format', 'json'),
('$top', '10'),
('Query', "'{}'".format(q)),
], auth=BasicAuth("", password=api_key()))
data = r.json()['d']
if len(data['results']):
return Response(data['results'][0]['MediaUrl'])
else:
raise CommandError("no results found")
|
from aiohttp import BasicAuth
from plumeria import config
from plumeria.command import commands, CommandError
from plumeria.message import Response
from plumeria.util import http
from plumeria.util.ratelimit import rate_limit
SEARCH_URL = "https://api.datamarket.azure.com/Bing/Search/v1/Image"
api_key = config.create("bing", "key",
fallback="unset",
comment="An API key from Bing")
@commands.register("image", "i", category="Search")
@rate_limit()
async def image(message):
"""
Search Bing for an image.
"""
q = message.content.strip()
if not q:
raise CommandError("Search term required!")
r = await http.get(SEARCH_URL, params=[
('$format', 'json'),
('$top', '10'),
('Query', "'{}'".format(q)),
], auth=BasicAuth("", password=api_key()))
data = r.json()['d']
if len(data['results']):
return Response(data['results'][0]['MediaUrl'])
else:
raise CommandError("no results found")
|
Test without killing to see what's going wrong on windows
|
package main
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func killBrowserHandler(c *gin.Context) {
var data struct {
Action string `json:"action"`
Process string `json:"process"`
URL string `json:"url"`
}
c.BindJSON(&data)
command, err := findBrowser(data.Process)
log.Println(command)
if err != nil {
c.JSON(http.StatusInternalServerError, err)
}
if data.Action == "kill" || data.Action == "restart" {
// _, err := killBrowser(data.Process)
// if err != nil {
// c.JSON(http.StatusInternalServerError, err)
// }
}
if data.Action == "restart" {
_, err := startBrowser(command, data.URL)
if err != nil {
c.JSON(http.StatusInternalServerError, err)
}
}
}
|
package main
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func killBrowserHandler(c *gin.Context) {
var data struct {
Action string `json:"action"`
Process string `json:"process"`
URL string `json:"url"`
}
c.BindJSON(&data)
command, err := findBrowser(data.Process)
log.Println(command)
if err != nil {
c.JSON(http.StatusInternalServerError, err)
}
if data.Action == "kill" || data.Action == "restart" {
_, err := killBrowser(data.Process)
if err != nil {
c.JSON(http.StatusInternalServerError, err)
}
}
if data.Action == "restart" {
_, err := startBrowser(command, data.URL)
if err != nil {
c.JSON(http.StatusInternalServerError, err)
}
}
}
|
Terminate instances is not proper tag
|
"""
this program terminate instances if proper tag is not used
"""
import time
import boto3
start_time = time.time()
ec2 = boto3.resource('ec2')
ec2_client = boto3.client('ec2')
tag_deparment = ['Finance', 'Marketing', 'HumanResources', 'Research'] # Your departments
shutdown_instance = False
for instance in ec2.instances.all():
instance_state = instance.state['Name']
if instance_state == ('running' or 'pending'):
for tags in instance.tags:
for department in tag_deparment:
if tags['Value'] == department:
shutdown_instance = False
break
else:
shutdown_instance = True
print('The following instance will be shutdown', instance.id, 'Shutdown = ', shutdown_instance)
if shutdown_instance is True:
ec2_client.stop_instances(
InstanceIds = [instance.id],
Force = True
)
|
s program terminate instances if proper tag is not used
"""
import time
import boto3
start_time = time.time()
ec2 = boto3.resource('ec2')
ec2_client = boto3.client('ec2')
tag_deparment = ['Finance', 'Marketing', 'HumanResources', 'Research'] # Your departments
shutdown_instance = False
for instance in ec2.instances.all():
instance_state = instance.state['Name']
if instance_state == ('running' or 'pending'):
for tags in instance.tags:
for department in tag_deparment:
if tags['Value'] == department:
shutdown_instance = False
break
else:
shutdown_instance = True
print('The following instance will be shutdown', instance.id, 'Shutdown = ', shutdown_instance)
if shutdown_instance is True:
ec2_client.stop_instances(
InstanceIds = [instance.id],
Force = True
)
|
Fix import error due to wrong import line
|
# Copyright (c) 2016, Daniele Venzano
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from zoe_lib.predefined_apps.copier import copier_app
from zoe_lib.predefined_apps.spark_interactive import spark_jupyter_notebook_app
from zoe_lib.predefined_apps.eurecom_aml_lab import spark_jupyter_notebook_lab_app
from zoe_lib.predefined_apps.hdfs import hdfs_app
from zoe_lib.predefined_apps.openmpi import openmpi_app
from zoe_lib.predefined_apps.spark_submit import spark_submit_app
from zoe_lib.predefined_apps.test_sleep import sleeper_app
PREDEFINED_APPS = [
copier_app,
spark_jupyter_notebook_app,
spark_jupyter_notebook_lab_app,
hdfs_app,
openmpi_app,
spark_submit_app,
sleeper_app
]
|
# Copyright (c) 2016, Daniele Venzano
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from zoe_lib.predefined_apps.copier import copier_app
from zoe_lib.predefined_frameworks.jupyter_spark import spark_jupyter_notebook_app
from zoe_lib.predefined_apps.eurecom_aml_lab import spark_jupyter_notebook_lab_app
from zoe_lib.predefined_apps.hdfs import hdfs_app
from zoe_lib.predefined_apps.openmpi import openmpi_app
from zoe_lib.predefined_apps.spark_submit import spark_submit_app
from zoe_lib.predefined_apps.test_sleep import sleeper_app
PREDEFINED_APPS = [
copier_app,
spark_jupyter_notebook_app,
spark_jupyter_notebook_lab_app,
hdfs_app,
openmpi_app,
spark_submit_app,
sleeper_app
]
|
Revert "Didn't run tests before"
This reverts commit b8abc805f0adb18ceb2aac0ee498551c5f3e9cff.
|
package main
import (
"fmt"
"log"
"net/http"
"net/http/httputil"
"strings"
)
type proxii struct {
config *Config
etcd *etcdConnector
}
func (p *proxii) handler(w http.ResponseWriter, r *http.Request) {
host := strings.Split(r.Host, ":")[0]
uri, err := p.etcd.resolve(host)
if err != nil {
log.Println("Error while looking up host: ", err)
return
}
proxy := newReverseProxy(uri)
proxy.ServeHTTP(w, r)
}
func main() {
p := newProxii(parseFlags())
http.HandleFunc("/", p.handler)
err := http.ListenAndServe(fmt.Sprintf(":%d", p.config.port), nil)
if err != nil {
log.Fatal(err)
}
}
func newProxii(config *Config) *proxii {
etcd, err := newEtcdConnector(config)
if err != nil {
panic(err)
}
etcd.init()
return &proxii{config, etcd}
}
|
package main
import (
"fmt"
"log"
"net/http"
"strings"
)
type proxii struct {
config *Config
etcd *etcdConnector
}
func (p *proxii) handler(w http.ResponseWriter, r *http.Request) {
host := strings.Split(r.Host, ":")[0]
uri, err := p.etcd.resolve(host)
if err != nil {
log.Println("Error while looking up host: ", err)
return
}
proxy := newReverseProxy(uri)
proxy.ServeHTTP(w, r)
}
func main() {
p := newProxii(parseFlags())
http.HandleFunc("/", p.handler)
err := http.ListenAndServe(fmt.Sprintf(":%d", p.config.port), nil)
if err != nil {
log.Fatal(err)
}
}
func newProxii(config *Config) *proxii {
etcd, err := newEtcdConnector(config)
if err != nil {
panic(err)
}
etcd.init()
return &proxii{config, etcd}
}
|
Add greeting when logged into the account
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
function retrieveAccountInfo() {
fetch("/account").then(response => {
if (response.redirected) return;
else return response.json();
}).then(account => {
// Filling out the form with the account information.
document.getElementById("logout").href = account.logoutUrl;
if (account.isUserBusinessOwner) {
document.getElementById("businessName").value = account.nickname;
} else {
document.getElementById("nickname").value = account.nickname;
}
document.getElementById("street").value = account.street;
document.getElementById("city").value = account.city;
document.getElementById("state").value = account.state;
document.getElementById("zipCode").value = account.zipCode;
document.getElementById("userGreeting").innerText = "Hello, " + account.nickname;
});
}
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
function retrieveAccountInfo() {
fetch("/account").then(response => {
if (response.redirected) return;
else return response.json();
}).then(account => {
// Filling out the form with the account information.
document.getElementById("logout").href = account.logoutUrl;
if (account.isUserBusinessOwner) {
document.getElementById("businessName").value = account.nickname;
} else {
document.getElementById("nickname").value = account.nickname;
}
document.getElementById("street").value = account.street;
document.getElementById("city").value = account.city;
document.getElementById("state").value = account.state;
document.getElementById("zipCode").value = account.zipCode;
document.getElementById("userGreeting").value = account.nickname;
});
}
|
Simplify the sanity test check
App doesn't need to listen in the test script as supertest accepts the
app variable and handles the listening and un-listening itself.
This also removes the needs for the after block to stop the server.
|
/* eslint-env mocha */
var request = require('supertest')
var app = require('../../server.js')
var path = require('path')
var fs = require('fs')
var assert = require('assert')
/**
* Basic sanity checks on the dev server
*/
describe('The prototype kit', function () {
it('should generate assets into the /public folder', function () {
assert.doesNotThrow(function () {
fs.accessSync(path.resolve(__dirname, '../../public/javascripts/application.js'))
fs.accessSync(path.resolve(__dirname, '../../public/images/favicon.ico'))
fs.accessSync(path.resolve(__dirname, '../../public/stylesheets/application.css'))
})
})
it('should send with a well formed response for the index page', function (done) {
request(app)
.get('/')
.expect('Content-Type', /text\/html/)
.expect(200)
.end(function (err, res) {
if (err) {
done(err)
} else {
done()
}
})
})
})
|
/* global describe, it, before */
var request = require('supertest')
var assert = require('assert')
var path = require('path')
var fs = require('fs')
/**
* Basic sanity checks on the dev server
*/
describe('The prototype kit', function () {
var app
before(function (done) {
app = require('../../server')
done()
})
it('should generate assets into the /public folder', function () {
assert.doesNotThrow(function () {
fs.accessSync(path.resolve(__dirname, '../../public/javascripts/application.js'))
fs.accessSync(path.resolve(__dirname, '../../public/images/favicon.ico'))
fs.accessSync(path.resolve(__dirname, '../../public/stylesheets/application.css'))
})
})
it('should send with a well formed response for the index page', function (done) {
request(app)
.get('/')
.expect('Content-Type', /text\/html/)
.expect(200, done)
})
})
|
Destroy Vue component when Backbone view is destroyed
|
import Vue from 'vue';
import View from './view';
import store from './vue/store';
// Backbone view that wraps a Vue component
const VueComponentView = View.extend({
initialize: function (settings) {
this.component = settings.component;
this.props = settings.props;
this.render();
},
render: function () {
const vueContainer = $('<div></div>').get(0);
this.$el.append(vueContainer);
this.vue = new Vue({
el: vueContainer,
store,
render: (createElement) => {
return createElement(this.component, {
props: this.props
});
}
});
return this;
},
destroy: function () {
if (this.vue) {
this.vue.$destroy();
}
View.prototype.destroy.call(this);
}
});
export default VueComponentView;
|
import Vue from 'vue';
import View from './view';
import store from './vue/store';
// Backbone view that wraps a Vue component
const VueComponentView = View.extend({
initialize: function (settings) {
this.component = settings.component;
this.props = settings.props;
this.render();
},
render: function () {
const vueContainer = $('<div></div>').get(0);
this.$el.append(vueContainer);
new Vue({ // eslint-disable-line no-new
el: vueContainer,
store,
render: (createElement) => {
return createElement(this.component, {
props: this.props
});
}
});
return this;
}
});
export default VueComponentView;
|
Add API doc to NullObject
|
package vm
var (
nullClass *RNull
// NULL represents Goby's null objects.
NULL *NullObject
)
// RNull is the built in class of Goby's null objects.
type RNull struct {
*BaseClass
}
// NullObject (`nil`) represents the null value in Goby.
// `nil` is convert into `null` when exported to JSON format.
// Cannot perform `Null.new`.
type NullObject struct {
Class *RNull
}
// toString returns the name of NullObject
func (n *NullObject) toString() string {
return "nil"
}
func (n *NullObject) toJSON() string {
return "null"
}
func (n *NullObject) returnClass() Class {
return n.Class
}
func initNullClass() {
baseClass := &BaseClass{Name: "Null", Methods: newEnvironment(), ClassMethods: newEnvironment(), Class: classClass, pseudoSuperClass: objectClass}
nc := &RNull{BaseClass: baseClass}
nc.setBuiltInMethods(builtInNullInstanceMethods, false)
nullClass = nc
NULL = &NullObject{Class: nullClass}
}
var builtInNullInstanceMethods = []*BuiltInMethodObject{
{
// Returns true: the flipped boolean value of nil object.
//
// ```ruby
// a = nil
// !a
// # => true
// ```
Name: "!",
Fn: func(receiver Object) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *callFrame) Object {
return TRUE
}
},
},
}
|
package vm
var (
nullClass *RNull
// NULL represents Goby's null objects.
NULL *NullObject
)
// RNull is the built in class of Goby's null objects.
type RNull struct {
*BaseClass
}
// NullObject represnts the null value in Goby.
type NullObject struct {
Class *RNull
}
// toString returns the name of NullObject
func (n *NullObject) toString() string {
return "nil"
}
func (n *NullObject) toJSON() string {
return "null"
}
func (n *NullObject) returnClass() Class {
return n.Class
}
func initNullClass() {
baseClass := &BaseClass{Name: "Null", Methods: newEnvironment(), ClassMethods: newEnvironment(), Class: classClass, pseudoSuperClass: objectClass}
nc := &RNull{BaseClass: baseClass}
nc.setBuiltInMethods(builtInNullInstanceMethods, false)
nullClass = nc
NULL = &NullObject{Class: nullClass}
}
var builtInNullInstanceMethods = []*BuiltInMethodObject{
{
Name: "!",
Fn: func(receiver Object) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *callFrame) Object {
return TRUE
}
},
},
}
|
Change chest recipe to make 2 chests
|
package ethanjones.cubes.block;
import ethanjones.cubes.core.IDManager;
import ethanjones.cubes.core.IDManager.GetBlock;
import ethanjones.cubes.item.ItemStack;
import ethanjones.cubes.item.crafting.CraftingManager;
import ethanjones.cubes.item.crafting.CraftingRecipe;
public class Blocks {
@GetBlock("core:bedrock")
public static Block bedrock;
@GetBlock("core:stone")
public static Block stone;
@GetBlock("core:dirt")
public static Block dirt;
@GetBlock("core:grass")
public static Block grass;
@GetBlock("core:log")
public static Block log;
@GetBlock("core:leaves")
public static Block leaves;
@GetBlock("core:glow")
public static Block glow;
@GetBlock("core:glass")
public static Block glass;
public static Block chest;
public static void init() {
chest = new BlockChest();
IDManager.register(chest);
ItemStack c = new ItemStack(chest.getItemBlock(), 2);
ItemStack l = new ItemStack(log.getItemBlock());
CraftingManager.addRecipe(new CraftingRecipe(c, l, l, l, l, null, l, l, l, l));
}
}
|
package ethanjones.cubes.block;
import ethanjones.cubes.core.IDManager;
import ethanjones.cubes.core.IDManager.GetBlock;
import ethanjones.cubes.item.ItemStack;
import ethanjones.cubes.item.crafting.CraftingManager;
import ethanjones.cubes.item.crafting.CraftingRecipe;
public class Blocks {
@GetBlock("core:bedrock")
public static Block bedrock;
@GetBlock("core:stone")
public static Block stone;
@GetBlock("core:dirt")
public static Block dirt;
@GetBlock("core:grass")
public static Block grass;
@GetBlock("core:log")
public static Block log;
@GetBlock("core:leaves")
public static Block leaves;
@GetBlock("core:glow")
public static Block glow;
@GetBlock("core:glass")
public static Block glass;
public static Block chest;
public static void init() {
chest = new BlockChest();
IDManager.register(chest);
ItemStack c = new ItemStack(chest.getItemBlock());
ItemStack l = new ItemStack(log.getItemBlock());
CraftingManager.addRecipe(new CraftingRecipe(c, l, l, l, l, null, l, l, l, l));
}
}
|
Improve Django field conversion real-life tests
|
from __future__ import absolute_import
from django.db import models
class Pet(models.Model):
name = models.CharField(max_length=30)
class Film(models.Model):
reporters = models.ManyToManyField('Reporter',
related_name='films')
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
pets = models.ManyToManyField('self')
def __str__(self): # __unicode__ on Python 2
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, related_name='articles')
lang = models.CharField(max_length=2, help_text='Language', choices=[
('es', 'Spanish'),
('en', 'English')
], default='es')
def __str__(self): # __unicode__ on Python 2
return self.headline
class Meta:
ordering = ('headline',)
|
from __future__ import absolute_import
from django.db import models
class Pet(models.Model):
name = models.CharField(max_length=30)
class Film(models.Model):
reporters = models.ManyToManyField('Reporter',
related_name='films')
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
pets = models.ManyToManyField('self')
def __str__(self): # __unicode__ on Python 2
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, related_name='articles')
def __str__(self): # __unicode__ on Python 2
return self.headline
class Meta:
ordering = ('headline',)
|
Disable the error-prone Discourse synchronization test to fix Travis.
|
// Copyright © 2017 Michael Howell. All rights reserved.
// The following code is covered by the AGPL-3.0 license.
const selfapi = require('selfapi');
const blog = require('../lib/blog');
const log = require('../lib/log');
// API resource to manage Janitor's Discourse-backed news section.
const blogAPI = module.exports = selfapi({
title: 'Blog'
});
blogAPI.post('/synchronize', {
title: 'Synchronize Blog',
description: 'Pull the blog section from Discourse.',
handler: async (_request, response) => {
try {
const { count } = await blog.synchronize();
log('synchronized blog', { count });
response.json({ count }, null, 2);
} catch (error) {
log('[fail] synchronized blog', error);
response.statusCode = 500; // Internal Server Error
response.json({ error: 'Could not synchronize' }, null, 2);
}
},
// FIXME: Re-enable this test once syncing with Discourse doesn't cause frequent errors.
// This can be achieved by rate-limiting our own sync requests, and/or by using a Discourse token.
// See https://github.com/JanitorTechnology/janitor/issues/219
examples: [/* {
response: {
body: JSON.stringify({ count: 13 }, null, 2)
}
} */]
});
|
// Copyright © 2017 Michael Howell. All rights reserved.
// The following code is covered by the AGPL-3.0 license.
const selfapi = require('selfapi');
const blog = require('../lib/blog');
const log = require('../lib/log');
// API resource to manage Janitor's Discourse-backed news section.
const blogAPI = module.exports = selfapi({
title: 'Blog'
});
blogAPI.post('/synchronize', {
title: 'Synchronize Blog',
description: 'Pull the blog section from Discourse.',
handler: async (_request, response) => {
try {
const { count } = await blog.synchronize();
log('synchronized blog', { count });
response.json({ count }, null, 2);
} catch (error) {
log('[fail] synchronized blog', error);
response.statusCode = 500; // Internal Server Error
response.json({ error: 'Could not synchronize' }, null, 2);
}
},
examples: [{
response: {
body: JSON.stringify({ count: 13 }, null, 2)
}
}]
});
|
Swap $...$ENV_EXPRESS_PORT and $PORT precedence
|
module.exports = (function() {
const environment = process.env.NODE_ENV || 'production';
const prefixGet = function(body) {
let id = `VOLONTARIO_${environment}_${body}`;
let upperCaseId = id.toUpperCase();
if (process.env[upperCaseId] === undefined) {
throw new Error(`Missing envvar: ${upperCaseId}`);
}
return process.env[upperCaseId];
};
const expressPort = (function() {
if (process.env.PORT) {
return process.env.PORT;
} else if (prefixGet('EXPRESS_PORT')) {
return prefixGet('EXPRESS_PORT');
}
throw new Error('Neither $VOLONTARIO_$ENV_EXPRESS_PORT nor $PORT is set');
})();
return {
ENVIRONMENT: environment,
EXPRESS_PORT: expressPort,
MONGO_URL: prefixGet('MONGO_URL'),
MONGO_USERNAME: prefixGet('MONGO_USERNAME'),
MONGO_PASSWORD: prefixGet('MONGO_PASSWORD')
};
})();
|
module.exports = (function() {
const environment = process.env.NODE_ENV || 'production';
const prefixGet = function(body) {
let id = `VOLONTARIO_${environment}_${body}`;
let upperCaseId = id.toUpperCase();
if (process.env[upperCaseId] === undefined) {
throw new Error(`Missing envvar: ${upperCaseId}`);
}
return process.env[upperCaseId];
};
const expressPort = (function() {
if (prefixGet('EXPRESS_PORT')) {
return prefixGet('EXPRESS_PORT');
} else if (process.env.PORT) {
return process.env.PORT;
}
throw new Error('Neither $VOLONTARIO_$ENV_EXPRESS_PORT nor $PORT is set');
})();
return {
ENVIRONMENT: environment,
EXPRESS_PORT: expressPort,
MONGO_URL: prefixGet('MONGO_URL'),
MONGO_USERNAME: prefixGet('MONGO_USERNAME'),
MONGO_PASSWORD: prefixGet('MONGO_PASSWORD')
};
})();
|
Remove pytest-runner and bump version to 3.0.2
|
from setuptools import setup
DESCRIPTION = open('README.md').read()
setup(
name="ordered-set",
version='3.0.2',
maintainer='Luminoso Technologies, Inc.',
maintainer_email='rspeer@luminoso.com',
license="MIT-LICENSE",
url='http://github.com/LuminosoInsight/ordered-set',
platforms=["any"],
description="A MutableSet that remembers its order, so that every entry has an index.",
long_description=DESCRIPTION,
long_description_content_type='text/markdown',
py_modules=['ordered_set'],
package_data={'': ['MIT-LICENSE']},
include_package_data=True,
tests_require=['pytest'],
python_requires='>=2.7',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
]
)
|
from setuptools import setup
DESCRIPTION = open('README.md').read()
setup(
name="ordered-set",
version='3.0.1',
maintainer='Luminoso Technologies, Inc.',
maintainer_email='rspeer@luminoso.com',
license="MIT-LICENSE",
url='http://github.com/LuminosoInsight/ordered-set',
platforms=["any"],
description="A MutableSet that remembers its order, so that every entry has an index.",
long_description=DESCRIPTION,
long_description_content_type='text/markdown',
py_modules=['ordered_set'],
package_data={'': ['MIT-LICENSE']},
include_package_data=True,
setup_requires=['pytest-runner'],
tests_require=['pytest'],
python_requires='>=2.7',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
]
)
|
Remove requirement for lxml (it's compiled/installed as a system package)
|
from setuptools import setup, find_packages
import os
version = '1.0'
setup(name='rhaptos.cnxmlutils',
version=version,
description="",
long_description=open("README.txt").read() + "\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
# Get more strings from
# http://pypi.python.org/pypi?:action=list_classifiers
classifiers=[
"Programming Language :: Python",
],
keywords='',
author='',
author_email='',
url='http://svn.plone.org/svn/collective/',
license='GPL',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['rhaptos'],
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
#'lxml',
#'argparse',
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
from setuptools import setup, find_packages
import os
version = '1.0'
setup(name='rhaptos.cnxmlutils',
version=version,
description="",
long_description=open("README.txt").read() + "\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
# Get more strings from
# http://pypi.python.org/pypi?:action=list_classifiers
classifiers=[
"Programming Language :: Python",
],
keywords='',
author='',
author_email='',
url='http://svn.plone.org/svn/collective/',
license='GPL',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['rhaptos'],
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'lxml',
#'argparse',
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
Allow eslint to use node and es6
|
module.exports = {
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"rules": {
"indent": [
"error",
4
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"double"
],
"semi": [
"error",
"always"
]
},
"globals": {
"$": true,
"it": true,
"describe": true,
"beforeEach": true,
"chai": true,
"jQuery": true,
"chrome": true,
"modal": true,
"modalTimeout": true,
"modalHTML": true,
"Modal": true,
"flashInterval": true,
"currentScript": true
}
};
|
module.exports = {
"env": {
"browser": true
},
"extends": "eslint:recommended",
"rules": {
"indent": [
"error",
4
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"double"
],
"semi": [
"error",
"always"
]
},
"globals": {
"$": true,
"it": true,
"describe": true,
"beforeEach": true,
"chai": true,
"jQuery": true,
"chrome": true,
"modal": true,
"modalTimeout": true,
"modalHTML": true,
"Modal": true,
"flashInterval": true,
"currentScript": true
}
};
|
Use passed url argument in get_best_match
|
from __future__ import absolute_import
__all__ = ['app']
from ConfigParser import SafeConfigParser as ConfigParser
from urlparse import urlparse, urlunparse
from flask import Flask, request, redirect
from fuzzywuzzy import process
from tldextract import extract
config = ConfigParser()
config.read(['config.ini', 'config.ini.tpl'])
BASE = config.get('typo', 'base')
CUTOFF = config.getint('typo', 'cutoff')
DEFAULT_SITE = config.get('typo', 'default_site')
MATCH_SITES = dict(config.items('match_sites'))
app = Flask(__name__)
@app.route('/', defaults={'path': ''})
@app.route(r'/<path:path>')
def catch_all(path):
redirect_to = get_best_match(request.url)
new_url = replace_host(request.url, redirect_to)
return redirect(new_url)
def replace_host(url, host):
parsed = urlparse(url)
netloc = u'%s.%s' % (host, BASE)
return urlunparse(parsed[:1] + (netloc,) + parsed[2:])
def get_best_match(url):
original_url = extract(url)
sub = original_url.subdomain
closest, score = process.extractOne(sub, MATCH_SITES.keys(),
score_cutoff=CUTOFF) or (None, 0)
return MATCH_SITES.get(closest, DEFAULT_SITE)
|
from __future__ import absolute_import
__all__ = ['app']
from ConfigParser import SafeConfigParser as ConfigParser
from urlparse import urlparse, urlunparse
from flask import Flask, request, redirect
from fuzzywuzzy import process
from tldextract import extract
config = ConfigParser()
config.read(['config.ini', 'config.ini.tpl'])
BASE = config.get('typo', 'base')
CUTOFF = config.getint('typo', 'cutoff')
DEFAULT_SITE = config.get('typo', 'default_site')
MATCH_SITES = dict(config.items('match_sites'))
app = Flask(__name__)
@app.route('/', defaults={'path': ''})
@app.route(r'/<path:path>')
def catch_all(path):
redirect_to = get_best_match(request.url)
new_url = replace_host(request.url, redirect_to)
return redirect(new_url)
def replace_host(url, host):
parsed = urlparse(url)
netloc = u'%s.%s' % (host, BASE)
return urlunparse(parsed[:1] + (netloc,) + parsed[2:])
def get_best_match(url):
original_url = extract(request.url)
sub = original_url.subdomain
closest, score = process.extractOne(sub, MATCH_SITES.keys(),
score_cutoff=CUTOFF) or (None, 0)
return MATCH_SITES.get(closest, DEFAULT_SITE)
|
Fix case on phone brick label
|
module.exports = {
className: 'phone',
template: require('./index.html'),
data: {
name: 'Phone',
icon: '/images/blocks_phone.png',
attributes: {
number: {
label: 'Phone #',
type: 'string',
value: '+18005555555'
},
innerHTML: {
label: 'Label',
type: 'string',
value: 'Place call'
}
}
},
};
|
module.exports = {
className: 'phone',
template: require('./index.html'),
data: {
name: 'phone',
icon: '/images/blocks_phone.png',
attributes: {
number: {
label: 'Phone #',
type: 'string',
value: '+18005555555'
},
innerHTML: {
label: 'Label',
type: 'string',
value: 'Place call'
}
}
},
};
|
Allow .env to overwrite NODE_ENV
|
'use strict'
var env = process.env.NODE_ENV || 'development'
if (env === 'development') {
require('dotenv').config()
env = process.env.NODE_ENV || env // in case dotenv changes NODE_ENV
}
var conf = module.exports = {
env: env,
server: {
protocol: process.env.OPBEANS_SERVER_PROTOCOL || 'http:',
auth: process.env.OPBEANS_SERVER_AUTH || '',
hostname: process.env.OPBEANS_SERVER_HOSTNAME || 'localhost',
port: process.env.OPBEANS_SERVER_PORT || process.env.PORT || 3001
},
pg: {
database: process.env.PGDATABASE || 'opbeans'
},
redis: process.env.REDIS_URL || null,
apm: {
active: env === 'production'
}
}
conf.server.url = conf.server.protocol + '//' +
(conf.server.auth ? conf.server.auth + '@' : '') +
conf.server.hostname +
(conf.server.port ? ':' + conf.server.port : '')
|
'use strict'
var env = process.env.NODE_ENV || 'development'
if (env === 'development') require('dotenv').config()
var conf = module.exports = {
env: env,
server: {
protocol: process.env.OPBEANS_SERVER_PROTOCOL || 'http:',
auth: process.env.OPBEANS_SERVER_AUTH || '',
hostname: process.env.OPBEANS_SERVER_HOSTNAME || 'localhost',
port: process.env.OPBEANS_SERVER_PORT || process.env.PORT || 3001
},
pg: {
database: process.env.PGDATABASE || 'opbeans'
},
redis: process.env.REDIS_URL || null,
apm: {
active: env === 'production'
}
}
conf.server.url = conf.server.protocol + '//' +
(conf.server.auth ? conf.server.auth + '@' : '') +
conf.server.hostname +
(conf.server.port ? ':' + conf.server.port : '')
|
Use more proper curses package.'
|
package curses
// Handles all output.
import (
"github.com/discoviking/roguemike/io"
"github.com/rthornton128/goncurses"
)
var screen *goncurses.Window
var Input chan *io.UpdateBundle
func Init() error {
s, err := goncurses.Init()
screen = s
if err != nil {
return err
}
goncurses.Raw(true)
goncurses.Echo(false)
goncurses.Cursor(0)
go func() {
for s := range Input {
output(s)
}
}()
return nil
}
func Term() {
goncurses.End()
}
func output(u *io.UpdateBundle) {
clearscreen()
for _, e := range u.Entities {
draw(e)
}
refresh()
}
func clearscreen() {
screen.Erase()
}
func refresh() {
screen.Refresh()
}
func draw(e *io.EntityData) {
screen.MoveAddChar(e.Y, e.X, 'X')
}
|
package curses
// Handles all output.
import (
"code.google.com/p/goncurses"
"github.com/discoviking/roguemike/io"
)
var screen *goncurses.Window
var Input chan *io.UpdateBundle
func Init() error {
s, err := goncurses.Init()
screen = s
if err != nil {
return err
}
goncurses.Raw(true)
goncurses.Echo(false)
goncurses.Cursor(0)
go func() {
for s := range Input {
output(s)
}
}()
return nil
}
func Term() {
goncurses.End()
}
func output(u *io.UpdateBundle) {
clearscreen()
for _, e := range u.Entities {
draw(e)
}
refresh()
}
func clearscreen() {
screen.Erase()
}
func refresh() {
screen.Refresh()
}
func draw(e *io.EntityData) {
screen.MoveAddChar(e.Y, e.X, 'X')
}
|
Use del instead of gulp-rimraf
|
var babel = require('gulp-babel');
var del = require('del');
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var plumber = require('gulp-plumber');
gulp.task('clean', function(cb) {
return del([
'dist/*',
'lib/*',
'spec/**/*.js'
], cb)
});
gulp.task('build', function() {
return gulp.src('src/**/*.js')
.pipe(plumber())
.pipe(babel())
.pipe(gulp.dest('.'));
});
gulp.task('spec', function() {
return gulp.src('spec/**/*.js', {read: false})
.pipe(plumber())
.pipe(mocha({bail: true}));
});
gulp.task('rebuild', gulp.series(
'clean', 'build'
));
gulp.task('watch', function() {
return gulp.watch('src/**/*.js', gulp.series(
'build', 'spec'
));
});
gulp.task('default', gulp.series(
'rebuild', 'spec', 'watch'
));
|
var babel = require('gulp-babel');
var clean = require('gulp-rimraf');
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var plumber = require('gulp-plumber');
gulp.task('clean', function() {
return gulp.src([
'dist/*',
'lib/*',
'spec/**/*.js'
]).pipe(clean());
});
gulp.task('build', function() {
return gulp.src('src/**/*.js')
.pipe(plumber())
.pipe(babel())
.pipe(gulp.dest('.'));
});
gulp.task('spec', function() {
return gulp.src('spec/**/*.js', {read: false})
.pipe(plumber())
.pipe(mocha({bail: true}));
});
gulp.task('rebuild', gulp.series(
'clean', 'build'
));
gulp.task('watch', function() {
return gulp.watch('src/**/*.js', gulp.series(
'build', 'spec'
));
});
gulp.task('default', gulp.series(
'rebuild', 'spec', 'watch'
));
|
Fix typing of readFile function
|
// @flow
/**
* This module exists to promisify all the fs functionality
*/
import fs from 'fs';
// Polyfill for Node 8's util.promisify
import promisify from 'util.promisify';
import type { Stats } from 'fs';
type ReadFileFn = (filename: string, enc?: string) => Promise<Buffer | string>;
type WriteFileFn = (
filename: string,
data: Buffer | string,
options?: Object | string,
) => Promise<void>;
type UnlinkFn = (filename: string) => Promise<void>;
export const readFile: ReadFileFn = promisify(fs.readFile);
export const writeFile: WriteFileFn = promisify(fs.writeFile);
export const unlink: UnlinkFn = promisify(fs.unlink);
// TODO: @ryyppy Can we use something simpler like promisify(fs.access)?
export async function fileExists(file: string): Promise<boolean> {
try {
const stats: Stats = await promisify(fs.lstat)(file);
if (stats.isFile()) {
return true;
}
return false;
} catch (err) {
return false;
}
}
export const statSync = fs.statSync;
|
// @flow
/**
* This module exists to promisify all the fs functionality
*/
import fs from 'fs';
// Polyfill for Node 8's util.promisify
import promisify from 'util.promisify';
import type { Stats } from 'fs';
type ReadFileFn = (filename: string, enc?: string) => Promise<string>;
type WriteFileFn = (
filename: string,
data: Buffer | string,
options?: Object | string,
) => Promise<void>;
type UnlinkFn = (filename: string) => Promise<void>;
export const readFile: ReadFileFn = promisify(fs.readFile);
export const writeFile: WriteFileFn = promisify(fs.writeFile);
export const unlink: UnlinkFn = promisify(fs.unlink);
// TODO: @ryyppy Can we use something simpler like promisify(fs.access)?
export async function fileExists(file: string): Promise<boolean> {
try {
const stats: Stats = await promisify(fs.lstat)(file);
if (stats.isFile()) {
return true;
}
return false;
} catch (err) {
return false;
}
}
export const statSync = fs.statSync;
|
Rename this test to testIndexContainer
|
<?php
namespace Sitemap;
class IndexTest extends \PHPUnit_Framework_TestCase
{
public function testIndexContainer()
{
$sitemap1 = new Sitemap;
$sitemap1->setLocation('http://example.com/sitemap.xml');
$sitemap1->setLastMod(time());
$sitemap2 = new Sitemap;
$sitemap2->setLocation('http://example.com/blog.xml');
$sitemap2->setLastMod(time());
$index = new Index;
$index->addSitemap($sitemap1);
$index->addSitemap($sitemap2);
$this->assertCount(2, $index->getSitemaps());
$index->addSitemap($sitemap1);
$this->assertCount(2, $index->getSitemaps());
}
}
|
<?php
namespace Sitemap;
class IndexTest extends \PHPUnit_Framework_TestCase
{
public function testIndex()
{
$sitemap1 = new Sitemap;
$sitemap1->setLocation('http://example.com/sitemap.xml');
$sitemap1->setLastMod(time());
$sitemap2 = new Sitemap;
$sitemap2->setLocation('http://example.com/blog.xml');
$sitemap2->setLastMod(time());
$index = new Index;
$index->addSitemap($sitemap1);
$index->addSitemap($sitemap2);
$this->assertCount(2, $index->getSitemaps());
$index->addSitemap($sitemap1);
$this->assertCount(2, $index->getSitemaps());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.