text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix opening context menu was leaving rightMouseDown stuck on true. |
var mousePosition = [140, 20];
$(document).on("mousemove", function (event) {
mousePosition = [event.pageX - $('.js-mouseContainer').offset().left,
event.pageY - $(".js-mouseContainer").offset().top];
});
var mouseDown = false;
var rightMouseDown = false;
$(document).on('mousedown', function (event) {
if (event.which == 1) mouseDown = true;
else if (event.which == 3) rightMouseDown = true;
});
$(document).on('mouseup', function (event) {
if (event.which == 1) mouseDown = false;
else if (event.which == 3) rightMouseDown = false;
});
$(document).on('contextmenu', function (event) {
mouseDown = rightMouseDown = false;
});
function relativeMousePosition(element) {
var elementOffset = $(element).offset();
var containerOffset = $('.js-mouseContainer').offset();
return [mousePosition[0] - (elementOffset.left - containerOffset.left),
mousePosition[1] - (elementOffset.top - containerOffset.top)];
}
function isMouseOverElement(element) {
var relativePosition = relativeMousePosition(element);
return relativePosition[0] >= 0 && relativePosition[0] <= $(element).outerWidth()
&& relativePosition[1] >= 0 && relativePosition[1] <= $(element).outerHeight();
} |
var mousePosition = [140, 20];
$(document).on("mousemove", function (event) {
mousePosition = [event.pageX - $('.js-mouseContainer').offset().left,
event.pageY - $(".js-mouseContainer").offset().top];
});
var mouseDown = false;
var rightMouseDown = false;
$(document).on('mousedown', function (event) {
if (event.which == 1) mouseDown = true;
else if (event.which == 3) rightMouseDown = true;
});
$(document).on('mouseup', function (event) {
if (event.which == 1) mouseDown = false;
else if (event.which == 3) rightMouseDown = false;
});
function relativeMousePosition(element) {
var elementOffset = $(element).offset();
var containerOffset = $('.js-mouseContainer').offset();
return [mousePosition[0] - (elementOffset.left - containerOffset.left),
mousePosition[1] - (elementOffset.top - containerOffset.top)];
}
function isMouseOverElement(element) {
var relativePosition = relativeMousePosition(element);
return relativePosition[0] >= 0 && relativePosition[0] <= $(element).outerWidth()
&& relativePosition[1] >= 0 && relativePosition[1] <= $(element).outerHeight();
} |
Fix parsing of related concepts responses. [rev: matthew.gordon] | /*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'backbone'
], function(Backbone) {
return Backbone.Collection.extend({
url: '../api/search/find-related-concepts',
fetch: function(options) {
return Backbone.Collection.prototype.fetch.call(this, _.defaults(options, {
reset: true
}));
},
sync: function(method, model, options) {
options = options || {};
options.traditional = true; // Force "traditional" serialization of query parameters, e.g. index=foo&index=bar, for IOD multi-index support.
return Backbone.Collection.prototype.sync.call(this, method, model, options);
}
})
});
| /*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'backbone'
], function(Backbone) {
return Backbone.Collection.extend({
url: '../api/search/find-related-concepts',
fetch: function(options) {
return Backbone.Collection.prototype.fetch.call(this, _.defaults(options, {
reset: true
}));
},
sync: function(method, model, options) {
options = options || {};
options.traditional = true; // Force "traditional" serialization of query parameters, e.g. index=foo&index=bar, for IOD multi-index support.
return Backbone.Collection.prototype.sync.call(this, method, model, options);
},
parse: function(response) {
return response.entities;
}
})
});
|
Add both points and envelope polygon to rpl | var extent = require('turf-extent');
var bboxPolygon = require('turf-bbox-polygon');
/**
* Takes a {@link Feature} or {@link FeatureCollection} and returns a rectangular {@link Polygon} feature that encompasses all vertices.
*
* @module turf/envelope
* @param {FeatureCollection} fc a FeatureCollection of any type
* @return {Polygon} a rectangular Polygon feature that encompasses all vertices
* @example
* var pt1 = turf.point(-75.343, 39.984, {name: 'Location A'});
* var pt2 = turf.point(-75.833, 39.284, {name: 'Location B'});
* var pt3 = turf.point(-75.534, 39.123, {name: 'Location C'});
* var fc = turf.featurecollection([pt1, pt2, pt3]);
*
* var enveloped = turf.envelope(fc);
*
* var result = turf.featurecollection(
* fc.features.concat(enveloped));
*
* //=result
*/
module.exports = function(features, done){
var bbox = extent(features);
var poly = bboxPolygon(bbox);
return poly;
}
| var extent = require('turf-extent');
var bboxPolygon = require('turf-bbox-polygon');
/**
* Takes a {@link Feature} or {@link FeatureCollection} and returns a rectangular {@link Polygon} feature that encompasses all vertices.
*
* @module turf/envelope
* @param {FeatureCollection} fc a FeatureCollection of any type
* @return {Polygon} a rectangular Polygon feature that encompasses all vertices
* @example
* var pt1 = turf.point(-75.343, 39.984, {name: 'Location A'});
* var pt2 = turf.point(-75.833, 39.284, {name: 'Location B'});
* var pt3 = turf.point(-75.534, 39.123, {name: 'Location C'});
* var fc = turf.featurecollection([pt1, pt2, pt3]);
*
* var enveloped = turf.envelope(fc);
*
* //=enveloped
*/
module.exports = function(features, done){
var bbox = extent(features);
var poly = bboxPolygon(bbox);
return poly;
}
|
Disable redirects when using Live Preview | <?php
namespace Craft;
class RedirectmanagerPlugin extends BasePlugin
{
public function getName()
{
return Craft::t('Redirect Manager');
}
public function getVersion()
{
return 'Beta';
}
public function getDeveloper()
{
return 'Roi Kingon';
}
public function getDeveloperUrl()
{
return 'http://www.roikingon.com';
}
public function hasCpSection()
{
return true;
}
public function init()
{
// redirects only take place out of the CP (and should not happen in live preview)
if(craft()->request->isSiteRequest() && !craft()->request->isLivePreview()){
$path = craft()->request->getPath();
if( $location = craft()->redirectmanager->processRedirect($path) )
{
header("Location: ".$location['url'], true, $location['type']);
exit();
}
}
}
public function registerCpRoutes()
{
return array(
'redirectmanager\/new' => 'redirectmanager/_edit',
'redirectmanager\/(?P<redirectId>\d+)' => 'redirectmanager/_edit'
);
}
public function onAfterInstall()
{
$redirects = array(
array('uri' => '#^bad(.*)$#', 'location' => 'good$1', 'type' => "302")
);
foreach ($redirects as $redirect) {
craft()->db->createCommand()->insert('redirectmanager', $redirect);
}
}
}
| <?php
namespace Craft;
class RedirectmanagerPlugin extends BasePlugin
{
public function getName()
{
return Craft::t('Redirect Manager');
}
public function getVersion()
{
return 'Beta';
}
public function getDeveloper()
{
return 'Roi Kingon';
}
public function getDeveloperUrl()
{
return 'http://www.roikingon.com';
}
public function hasCpSection()
{
return true;
}
public function init()
{
// redirects only take place out of the CP
if(craft()->request->isSiteRequest()){
$path = craft()->request->getPath();
if( $location = craft()->redirectmanager->processRedirect($path) )
{
header("Location: ".$location['url'], true, $location['type']);
exit();
}
}
}
public function registerCpRoutes()
{
return array(
'redirectmanager\/new' => 'redirectmanager/_edit',
'redirectmanager\/(?P<redirectId>\d+)' => 'redirectmanager/_edit'
);
}
public function onAfterInstall()
{
$redirects = array(
array('uri' => '#^bad(.*)$#', 'location' => 'good$1', 'type' => "302")
);
foreach ($redirects as $redirect) {
craft()->db->createCommand()->insert('redirectmanager', $redirect);
}
}
}
|
Remove "polar" category from smith trace | 'use strict';
module.exports = {
moduleType: 'trace',
name: 'scattersmith',
basePlotModule: require('../../plots/smith'),
categories: ['symbols', 'showLegend', 'scatter-like'],
attributes: require('./attributes'),
supplyDefaults: require('./defaults').supplyDefaults,
colorbar: require('../scatter/marker_colorbar'),
formatLabels: require('./format_labels'),
calc: require('./calc'),
plot: require('./plot'),
style: require('../scatter/style').style,
styleOnSelect: require('../scatter/style').styleOnSelect,
hoverPoints: require('./hover').hoverPoints,
selectPoints: require('../scatter/select'),
meta: {
hrName: 'scatter_smith',
description: [
'The scattersmith trace type encompasses line charts, scatter charts, text charts, and bubble charts',
'in smith chart coordinates.',
'The data visualized as scatter point or lines is set in',
'`re` (real) and `im` (imaginary) coordinates',
'Text (appearing either on the chart or on hover only) is via `text`.',
'Bubble charts are achieved by setting `marker.size` and/or `marker.color`',
'to numerical arrays.'
].join(' ')
}
};
| 'use strict';
module.exports = {
moduleType: 'trace',
name: 'scattersmith',
basePlotModule: require('../../plots/smith'),
categories: ['polar', 'symbols', 'showLegend', 'scatter-like'],
attributes: require('./attributes'),
supplyDefaults: require('./defaults').supplyDefaults,
colorbar: require('../scatter/marker_colorbar'),
formatLabels: require('./format_labels'),
calc: require('./calc'),
plot: require('./plot'),
style: require('../scatter/style').style,
styleOnSelect: require('../scatter/style').styleOnSelect,
hoverPoints: require('./hover').hoverPoints,
selectPoints: require('../scatter/select'),
meta: {
hrName: 'scatter_smith',
description: [
'The scattersmith trace type encompasses line charts, scatter charts, text charts, and bubble charts',
'in smith chart coordinates.',
'The data visualized as scatter point or lines is set in',
'`re` (real) and `im` (imaginary) coordinates',
'Text (appearing either on the chart or on hover only) is via `text`.',
'Bubble charts are achieved by setting `marker.size` and/or `marker.color`',
'to numerical arrays.'
].join(' ')
}
};
|
Return the address from the marker. | from django.db import models
from model_utils import Choices
MARKER_COLOURS = Choices(
('blue', 'Blue'),
('red', 'Red')
)
class Marker(models.Model):
name = models.CharField(max_length=255)
address = models.TextField(blank=True)
lat = models.CharField(max_length=255, blank=True)
long = models.CharField(max_length=255, blank=True)
marker_colour = models.CharField(max_length=10, choices=MARKER_COLOURS, default=MARKER_COLOURS.blue)
def to_dict(self):
return {
'name': self.name,
'lat': self.lat,
'long': self.long,
'address': self.address,
'marker_colour': self.marker_colour
} | from django.db import models
from model_utils import Choices
MARKER_COLOURS = Choices(
('blue', 'Blue'),
('red', 'Red')
)
class Marker(models.Model):
name = models.CharField(max_length=255)
address = models.TextField(blank=True)
lat = models.CharField(max_length=255, blank=True)
long = models.CharField(max_length=255, blank=True)
marker_colour = models.CharField(max_length=10, choices=MARKER_COLOURS, default=MARKER_COLOURS.blue)
def to_dict(self):
return {
'name': self.name,
'lat': self.lat,
'long': self.long,
'marker_colour': self.marker_colour
} |
Add train config to audio train | #%% Setup.
import numpy as np
import scipy.io.wavfile
from keras.utils.visualize_util import plot
from keras.callbacks import TensorBoard, ModelCheckpoint
from keras.utils import np_utils
from eva.models.wavenet import Wavenet, compute_receptive_field
from eva.util.mutil import sparse_labels
#%% Data
RATE, DATA = scipy.io.wavfile.read('./data/undertale/undertale_001_once_upon_a_time.comp.wav')
#%% Model Config.
MODEL = Wavenet
FILTERS = 256
DEPTH = 7
STACKS = 4
LENGTH = DATA.shape[0]
BINS = 256
LOAD = False
#%% Train Config.
BATCH_SIZE = 5
EPOCHS = 2000
#%% Model.
INPUT = (LENGTH, BINS)
ARGS = (INPUT, FILTERS, DEPTH, STACKS)
M = MODEL(*ARGS)
if LOAD:
M.load_weights('model.h5')
M.summary()
plot(M)
#%% Train.
TRAIN = np_utils.to_categorical(DATA, BINS)
TRAIN = TRAIN.reshape(BATCH_SIZE, TRAIN.shape[0]//BATCH_SIZE, TRAIN.shape[1])
M.fit(TRAIN, sparse_labels(TRAIN), nb_epoch=EPOCHS, batch_size=BATCH_SIZE,
callbacks=[TensorBoard(), ModelCheckpoint('model.h5')]) | #%% Setup.
import numpy as np
import scipy.io.wavfile
from keras.utils.visualize_util import plot
from keras.callbacks import TensorBoard, ModelCheckpoint
from keras.utils import np_utils
from eva.models.wavenet import Wavenet, compute_receptive_field
from eva.util.mutil import sparse_labels
#%% Data
RATE, DATA = scipy.io.wavfile.read('./data/undertale/undertale_001_once_upon_a_time.comp.wav')
#%% Model Config.
MODEL = Wavenet
FILTERS = 256
DEPTH = 7
STACKS = 4
LENGTH = 1 + compute_receptive_field(RATE, DEPTH, STACKS)[0]
BINS = 256
LOAD = False
#%% Model.
INPUT = (LENGTH, BINS)
ARGS = (INPUT, FILTERS, DEPTH, STACKS)
M = MODEL(*ARGS)
if LOAD:
M.load_weights('model.h5')
M.summary()
plot(M)
#%% Train.
TRAIN = np_utils.to_categorical(DATA, BINS)
TRAIN = TRAIN[:TRAIN.shape[0]//LENGTH*LENGTH].reshape(TRAIN.shape[0]//LENGTH, LENGTH, BINS)
M.fit(TRAIN, sparse_labels(TRAIN), nb_epoch=2000, batch_size=8,
callbacks=[TensorBoard(), ModelCheckpoint('model.h5')]) |
Add Nova UI for class standing rank order | <?php
declare(strict_types=1);
namespace App\Nova;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\BelongsToMany;
use Laravel\Nova\Fields\Number;
use Laravel\Nova\Fields\Text;
class ClassStanding extends Resource
{
/**
* The model the resource corresponds to.
*
* @var string
*/
public static $model = \App\Models\ClassStanding::class;
/**
* The single value that should be used to represent the resource when being displayed.
*
* @var string
*/
public static $title = 'name';
/**
* The logical group associated with the resource.
*
* @var string
*/
public static $group = 'Demographics';
/**
* The columns that should be searched.
*
* @var array<string>
*/
public static $search = [
'name',
];
/**
* Get the fields displayed by the resource.
*/
public function fields(Request $request): array
{
return [
Text::make('Name')->sortable(),
Number::make('Rank Order')->sortable(),
BelongsToMany::make('Members', 'members', User::class),
self::metadataPanel(),
];
}
}
| <?php
declare(strict_types=1);
namespace App\Nova;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\BelongsToMany;
use Laravel\Nova\Fields\Text;
class ClassStanding extends Resource
{
/**
* The model the resource corresponds to.
*
* @var string
*/
public static $model = \App\Models\ClassStanding::class;
/**
* The single value that should be used to represent the resource when being displayed.
*
* @var string
*/
public static $title = 'name';
/**
* The logical group associated with the resource.
*
* @var string
*/
public static $group = 'Demographics';
/**
* The columns that should be searched.
*
* @var array<string>
*/
public static $search = [
'name',
];
/**
* Get the fields displayed by the resource.
*/
public function fields(Request $request): array
{
return [
Text::make('Name')->sortable(),
BelongsToMany::make('Members', 'members', User::class),
self::metadataPanel(),
];
}
}
|
Use only fixtures we need | const path = require('path');
const expect = require('chai').expect;
const findAssets = require('../src/config/findAssets');
const mockFs = require('mock-fs');
const dependencies = require('./fixtures/dependencies');
describe('findAssets', () => {
before(() => {
mockFs({ testDir: dependencies.withAssets });
});
it('should return an array of all files in given folders', () => {
const assets = findAssets('testDir', ['fonts', 'images']);
expect(assets).to.be.an('array');
expect(assets.length).to.equal(3);
});
it('should return absoulte paths to assets', () => {
const assets = findAssets('testDir', ['fonts', 'images']);
assets.forEach(assetPath => expect(assetPath).to.contain('testDir'));
});
after(() => {
mockFs.restore();
});
});
| const path = require('path');
const expect = require('chai').expect;
const findAssets = require('../src/config/findAssets');
const mockFs = require('mock-fs');
const dependencies = require('./fixtures/dependencies');
describe('findAssets', () => {
before(() => {
mockFs({ testDir: dependencies });
});
it('should return an array of all files in given folders', () => {
const assets = findAssets(
path.join('testDir', 'withAssets'),
['fonts', 'images']
);
expect(assets).to.be.an('array');
expect(assets.length).to.equal(3);
});
it('should return absoulte paths to assets', () => {
const folder = path.join('testDir', 'withAssets');
const assets = findAssets(
path.join('testDir', 'withAssets'),
['fonts', 'images']
);
assets.forEach(assetPath => expect(assetPath).to.contain(folder));
});
after(() => {
mockFs.restore();
});
});
|
Remove extra quoting of Atom path | /** @babel */
import fs from 'fs-plus'
import Opener from '../opener'
import { isPdfFile } from '../werkzeug'
export default class SumatraOpener extends Opener {
async open (filePath, texPath, lineNumber) {
const sumatraPath = `"${atom.config.get('latex.sumatraPath')}"`
const atomPath = process.argv[0]
const args = [
'-reuse-instance',
'-forward-search',
`"${texPath}"`,
lineNumber,
'-inverse-search',
`"\\"${atomPath}\\" \\"%f:%l\\""`,
`"${filePath}"`
]
const command = `${sumatraPath} ${args.join(' ')}`
await latex.process.executeChildProcess(command)
}
canOpen (filePath) {
return process.platform === 'win32' && isPdfFile(filePath) &&
fs.existsSync(atom.config.get('latex.sumatraPath'))
}
hasSynctex () {
return true
}
}
| /** @babel */
import fs from 'fs-plus'
import Opener from '../opener'
import { isPdfFile } from '../werkzeug'
export default class SumatraOpener extends Opener {
async open (filePath, texPath, lineNumber) {
const sumatraPath = `"${atom.config.get('latex.sumatraPath')}"`
const atomPath = `"${process.argv[0]}"`
const args = [
'-reuse-instance',
'-forward-search',
`"${texPath}"`,
lineNumber,
'-inverse-search',
`"\\"${atomPath}\\" \\"%f:%l\\""`,
`"${filePath}"`
]
const command = `${sumatraPath} ${args.join(' ')}`
console.log(command)
await latex.process.executeChildProcess(command)
}
canOpen (filePath) {
return process.platform === 'win32' && isPdfFile(filePath) &&
fs.existsSync(atom.config.get('latex.sumatraPath'))
}
hasSynctex () {
return true
}
}
|
Fix priority handling that prevents it to work | <?php
namespace Knp\JsonSchemaBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class RegisterPropertyHandlerCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('json_schema.builder')) {
return;
}
$definition = $container->getDefinition(
'json_schema.builder'
);
$taggedServices = $container->findTaggedServiceIds(
'json_schema.builder.handler'
);
foreach ($taggedServices as $id => $attributes) {
$definition->addMethodCall(
'registerPropertyHandler',
array(new Reference($id), $this->getPriority($attributes))
);
}
}
private function getPriority(array $attributes = array())
{
if (isset($attributes[0]['priority'])) {
return $attributes[0]['priority'];
}
return 0;
}
}
| <?php
namespace Knp\JsonSchemaBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class RegisterPropertyHandlerCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('json_schema.builder')) {
return;
}
$definition = $container->getDefinition(
'json_schema.builder'
);
$taggedServices = $container->findTaggedServiceIds(
'json_schema.builder.handler'
);
foreach ($taggedServices as $id => $attributes) {
$definition->addMethodCall(
'registerPropertyHandler',
array(new Reference($id), $this->getPriority($attributes))
);
}
}
private function getPriority(array $attributes = array())
{
if (isset($attributes['priority'])) {
return $attributes['priority'];
}
return 0;
}
}
|
Fix bug in watch task | 'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var paths = {
js: ['./gulpfile.js', './test/**/*.js'],
scss: ['./stylesheets/_sass-lib.scss'],
test: './test/**/*.js'
};
var plumberOpts = {};
gulp.task('js-lint', function() {
return gulp.src(paths.js)
.pipe($.jshint('.jshintrc'))
.pipe($.plumber(plumberOpts))
.pipe($.jscs())
.pipe($.jshint.reporter('jshint-stylish'));
});
gulp.task('scss-lint', function() {
gulp.src(paths.scss)
.pipe($.scssLint())
.pipe($.plumber(plumberOpts));
});
gulp.task('test', function() {
return gulp.src(paths.test, {read: false})
.pipe($.mocha({reporter: 'min'}));
});
gulp.task('lint', ['scss-lint', 'js-lint']);
gulp.task('watch', ['test'], function() {
gulp.watch(paths.js, 'js-lint');
gulp.watch(paths.scss, 'scss-lint');
gulp.watch(paths.test, 'test');
});
gulp.task('default', ['scss-lint', 'js-lint', 'test']);
| 'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var paths = {
js: ['./gulpfile.js', './test/**/*.js'],
scss: ['./stylesheets/_sass-lib.scss'],
test: './test/**/*.js'
};
var plumberOpts = {};
gulp.task('js-lint', function() {
return gulp.src(paths.js)
.pipe($.jshint('.jshintrc'))
.pipe($.plumber(plumberOpts))
.pipe($.jscs())
.pipe($.jshint.reporter('jshint-stylish'));
});
gulp.task('scss-lint', function() {
gulp.src(paths.scss)
.pipe($.scssLint())
.pipe($.plumber(plumberOpts));
});
gulp.task('test', function() {
return gulp.src(paths.test, {read: false})
.pipe($.mocha({reporter: 'min'}));
});
gulp.task('lint', ['scss-lint', 'js-lint']);
gulp.task('watch', 'test', function() {
gulp.watch(paths.js, 'js-lint');
gulp.watch(paths.scss, 'scss-lint');
gulp.watch(paths.test, 'test');
});
gulp.task('default', ['scss-lint', 'js-lint', 'test']);
|
Update pyyaml requirement from <5.3,>=5.1 to >=5.1,<5.4
Updates the requirements on [pyyaml](https://github.com/yaml/pyyaml) to permit the latest version.
- [Release notes](https://github.com/yaml/pyyaml/releases)
- [Changelog](https://github.com/yaml/pyyaml/blob/master/CHANGES)
- [Commits](https://github.com/yaml/pyyaml/compare/5.1...5.3)
Signed-off-by: dependabot-preview[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com> | from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.1.1',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click>=6.7,<7.1',
'PyYAML>=5.1,<5.4',
'panoptes-client>=1.0,<2.0',
'humanize>=0.5.1,<0.6',
'pathvalidate>=0.29.0,<0.30',
],
entry_points='''
[console_scripts]
panoptes=panoptes_cli.scripts.panoptes:cli
''',
)
| from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.1.1',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click>=6.7,<7.1',
'PyYAML>=5.1,<5.3',
'panoptes-client>=1.0,<2.0',
'humanize>=0.5.1,<0.6',
'pathvalidate>=0.29.0,<0.30',
],
entry_points='''
[console_scripts]
panoptes=panoptes_cli.scripts.panoptes:cli
''',
)
|
Add default MIME type for JSON files | package server
import (
"mime"
"net/http"
"path"
"path/filepath"
"github.com/facette/facette/pkg/logger"
)
func (server *Server) serveError(writer http.ResponseWriter, status int) {
err := server.execTemplate(
writer,
status,
struct {
URLPrefix string
ReadOnly bool
Status int
}{
URLPrefix: server.Config.URLPrefix,
ReadOnly: server.Config.ReadOnly,
Status: status,
},
path.Join(server.Config.BaseDir, "template", "layout.html"),
path.Join(server.Config.BaseDir, "template", "error.html"),
)
if err != nil {
logger.Log(logger.LevelError, "server", "%s", err)
server.serveResponse(writer, nil, status)
}
}
func (server *Server) serveStatic(writer http.ResponseWriter, request *http.Request) {
mimeType := mime.TypeByExtension(filepath.Ext(request.URL.Path))
if mimeType == "" {
mimeType = "application/octet-stream"
}
writer.Header().Set("Content-Type", mimeType)
// Handle static files
http.ServeFile(writer, request, path.Join(server.Config.BaseDir, request.URL.Path))
}
func init() {
// Register default MIME types
mime.AddExtensionType(".json", "application/json")
}
| package server
import (
"mime"
"net/http"
"path"
"path/filepath"
"github.com/facette/facette/pkg/logger"
)
func (server *Server) serveError(writer http.ResponseWriter, status int) {
err := server.execTemplate(
writer,
status,
struct {
URLPrefix string
ReadOnly bool
Status int
}{
URLPrefix: server.Config.URLPrefix,
ReadOnly: server.Config.ReadOnly,
Status: status,
},
path.Join(server.Config.BaseDir, "template", "layout.html"),
path.Join(server.Config.BaseDir, "template", "error.html"),
)
if err != nil {
logger.Log(logger.LevelError, "server", "%s", err)
server.serveResponse(writer, nil, status)
}
}
func (server *Server) serveStatic(writer http.ResponseWriter, request *http.Request) {
mimeType := mime.TypeByExtension(filepath.Ext(request.URL.Path))
if mimeType == "" {
mimeType = "application/octet-stream"
}
writer.Header().Set("Content-Type", mimeType)
// Handle static files
http.ServeFile(writer, request, path.Join(server.Config.BaseDir, request.URL.Path))
}
|
STYLE: Comment only change to test dashboard svn update step. | <?php
// kwtest library
require_once('kwtest/kw_web_tester.php');
// comment only change to test dashboard svn update step...
class TestEnvTestCase extends KWWebTestCase
{
function __construct()
{
parent::__construct();
}
function testTestEnv()
{
$s = '';
global $cdashpath;
$s = $s . "cdashpath=[".print_r($cdashpath, true)."]\n";
global $configure;
$s = $s . "configure=[".print_r($configure, true)."]\n";
global $db;
$s = $s . "db=[".print_r($db, true)."]\n";
global $inBrowser;
$s = $s . "inBrowser=[".print_r($inBrowser, true)."]\n";
global $web_report;
$s = $s . "web_report=[".print_r($web_report, true)."]\n";
global $isWindows;
$s = $s . "isWindows=[".print_r($isWindows, true)."]\n";
global $isMacOSX;
$s = $s . "isMacOSX=[".print_r($isMacOSX, true)."]\n";
$s = $s . "\n";
$this->assertTrue(true, $s);
}
}
?>
| <?php
// kwtest library
require_once('kwtest/kw_web_tester.php');
class TestEnvTestCase extends KWWebTestCase
{
function __construct()
{
parent::__construct();
}
function testTestEnv()
{
$s = '';
global $cdashpath;
$s = $s . "cdashpath=[".print_r($cdashpath, true)."]\n";
global $configure;
$s = $s . "configure=[".print_r($configure, true)."]\n";
global $db;
$s = $s . "db=[".print_r($db, true)."]\n";
global $inBrowser;
$s = $s . "inBrowser=[".print_r($inBrowser, true)."]\n";
global $web_report;
$s = $s . "web_report=[".print_r($web_report, true)."]\n";
global $isWindows;
$s = $s . "isWindows=[".print_r($isWindows, true)."]\n";
global $isMacOSX;
$s = $s . "isMacOSX=[".print_r($isMacOSX, true)."]\n";
$s = $s . "\n";
$this->assertTrue(true, $s);
}
}
?>
|
Move afterModel hook to after the model in user-quickfiles | import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import Analytics from 'ember-osf/mixins/analytics';
export default Route.extend(Analytics, {
currentUser: service(),
model(params) {
return this.store.findRecord('user', params.user_id);
},
afterModel(model, transition) {
if (model.id !== this.get('currentUser.currentUserId')) {
transition.send('track', 'view', 'track', 'Quick Files - Main page view');
}
},
actions: {
didTransition() {
window.addEventListener('dragover', e => this._preventDrop(e));
window.addEventListener('drop', e => this._preventDrop(e));
},
},
_preventDrop(e) {
if (e.target.id !== 'quickfiles-dropzone') {
e.preventDefault();
e.dataTransfer.effectAllowed = 'none';
e.dataTransfer.dropEffect = 'none';
}
},
});
| import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import Analytics from 'ember-osf/mixins/analytics';
export default Route.extend(Analytics, {
currentUser: service(),
model(params) {
return this.store.findRecord('user', params.user_id);
},
actions: {
didTransition() {
window.addEventListener('dragover', e => this._preventDrop(e));
window.addEventListener('drop', e => this._preventDrop(e));
},
},
_preventDrop(e) {
if (e.target.id !== 'quickfiles-dropzone') {
e.preventDefault();
e.dataTransfer.effectAllowed = 'none';
e.dataTransfer.dropEffect = 'none';
}
},
afterModel(model, transition) {
if (model.id !== this.get('currentUser.currentUserId')) {
transition.send('track', 'view', 'track', 'Quick Files - Main page view');
}
},
});
|
Move images preloading and background cycling start to the "window.load"
Also trigger initial "window.hashchange" event immediately. | $(function() {
// menu initialization
var $menu = $('#menu');
var $menuEntries = $menu.children('div');
$(window).on('hashchange', function() {
$menuEntries.hide();
var clickedMenuEntry =
$menuEntries.filter(window.location.hash).size() ?
window.location.hash :
'#index';
$(clickedMenuEntry).show();
}).trigger('hashchange'); // initial
});
$(window).load(function() {
var curBackground = 1;
var backgroundsCount = 10;
var backgroundsExt = '.jpg';
var backgroundsUrlPrefix = 'css/img/backgrounds/';
// simple images preloading
for (var i = curBackground; i <= backgroundsCount; i++) {
$('<img src="' + backgroundsUrlPrefix + i + backgroundsExt + '">');
}
var $backgroundContainer = $('#background');
// background images cycling
setInterval(function() {
$backgroundContainer.fadeOut('slow', function() {
$backgroundContainer.css(
'background-image',
'url(' + backgroundsUrlPrefix + curBackground + backgroundsExt + ')'
).fadeIn('slow');
});
curBackground = (curBackground === backgroundsCount) ? 1 : ++curBackground;
}, 5000);
});
| $(function() {
// menu initialization
var $menu = $('#menu');
var $menuEntries = $menu.children('div');
$(window).on('hashchange load', function() {
$menuEntries.hide();
var clickedMenuEntry =
$menuEntries.filter(window.location.hash).size() ?
window.location.hash :
'#index';
$(clickedMenuEntry).show();
});
var curBackground = 1;
var backgroundsCount = 10;
var backgroundsExt = '.jpg';
var backgroundsUrlPrefix = 'css/img/backgrounds/';
// simple images preloading
for (var i = curBackground; i <= backgroundsCount; i++) {
$('<img src="' + backgroundsUrlPrefix + i + backgroundsExt + '">');
}
var $backgroundContainer = $('#background');
setInterval(function() {
$backgroundContainer.fadeOut('slow', function() {
$backgroundContainer.css(
'background-image',
'url(' + backgroundsUrlPrefix + curBackground + backgroundsExt + ')'
).fadeIn('slow');
});
curBackground = (curBackground === backgroundsCount) ? 1 : ++curBackground;
}, 5000);
});
|
Fix (JWT Service): token for anonymous user | <?php
namespace AppBundle\Service;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
/**
* Class JwtService
* @package AppBundle\Service
*/
class JwtService{
private $ts;
/**
* JwtService constructor.
* @param TokenStorage $ts
*/
public function __construct(TokenStorage $ts, $jwtManager){
$this->ts = $ts;
$this->jwtManager = $jwtManager;
}
/**
* Create token acces
* @return mixed
*/
public function getToken(){
$user = $this->ts->getToken()->getUser();
if (is_object($user) && $user instanceof User) {
return $this->jwtManager->create($user);
}
return null;
}
}
| <?php
namespace AppBundle\Service;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
/**
* Class JwtService
* @package AppBundle\Service
*/
class JwtService{
private $ts;
/**
* JwtService constructor.
* @param TokenStorage $ts
*/
public function __construct(TokenStorage $ts, $jwtManager){
$this->ts = $ts;
$this->jwtManager = $jwtManager;
}
/**
* Create token acces
* @return mixed
*/
public function getToken(){
$client = $this->ts->getToken()->getUser();
return $this->jwtManager->create($client);
}
}
|
Use `_method=DELETE` instead for deletion | /*
* Copyright 2020 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.
*/
/**
* External dependencies
*/
import queryString from 'query-string';
/**
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';
const get = (path, options = {}) => apiFetch({ path, ...options });
const post = (path, options = {}) =>
apiFetch({
path,
...options,
method: 'POST',
});
// `apiFetch` by default turns `DELETE` requests into `POST` requests
// with `X-HTTP-Method-Override: DELETE` headers.
// However, some Web Application Firewall (WAF) solutions prevent this.
// `?_method=DELETE` is an alternative solution to override the request method.
// See https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/#_method-or-x-http-method-override-header
const deleteRequest = (path, options = {}) =>
apiFetch({
path: queryString.stringifyUrl({
url: path,
query: {
_method: 'DELETE',
},
}),
...options,
method: 'POST',
});
export default {
get,
post,
deleteRequest,
};
| /*
* Copyright 2020 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.
*/
/**
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';
const get = (path, options = {}) => apiFetch({ path, ...options });
const post = (path, options = {}) =>
apiFetch({
path,
...options,
method: 'POST',
});
const deleteRequest = (path, options = {}) =>
apiFetch({
path,
...options,
method: 'DELETE',
});
export default {
get,
post,
deleteRequest,
};
|
Add ability to delete multiple string familes at once | package com.airbnb.aerosolve.core.transforms;
import com.airbnb.aerosolve.core.FeatureVector;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.typesafe.config.Config;
/**
* "field1" specifies the string column to be deleted
*/
public class DeleteStringFeatureFamilyTransform implements Transform {
private String fieldName1;
private List<String> fieldNames;
@Override
public void configure(Config config, String key) {
if (config.hasPath(key + ".field1")) {
fieldName1 = config.getString(key + ".field1");
}
if (config.hasPath(key + ".fields")) {
fieldNames = config.getStringList(key + ".fields");
}
}
@Override
public void doTransform(FeatureVector featureVector) {
Map<String, Set<String>> stringFeatures = featureVector.getStringFeatures();
if (stringFeatures == null) {
return ;
}
HashSet<String> fieldNamesSet = new HashSet<>();
if (fieldName1 != null) {
fieldNamesSet.add(fieldName1);
}
if (fieldNames != null) {
fieldNamesSet.addAll(fieldNames);
}
for (String fieldName: fieldNamesSet) {
Set<String> feature1 = stringFeatures.get(fieldName1);
if (feature1 != null) {
stringFeatures.remove(fieldName);
}
}
}
}
| package com.airbnb.aerosolve.core.transforms;
import com.airbnb.aerosolve.core.FeatureVector;
import java.util.Map;
import java.util.Set;
import com.typesafe.config.Config;
/**
* "field1" specifies the string column to be deleted
*/
public class DeleteStringFeatureFamilyTransform implements Transform {
private String fieldName1;
@Override
public void configure(Config config, String key) {
fieldName1 = config.getString(key + ".field1");
}
@Override
public void doTransform(FeatureVector featureVector) {
Map<String, Set<String>> stringFeatures = featureVector.getStringFeatures();
if (stringFeatures == null) {
return ;
}
Set<String> feature1 = stringFeatures.get(fieldName1);
if (feature1 == null) {
return;
}
stringFeatures.remove(fieldName1);
}
}
|
Revert "Revert "debugging the ios directory issue""
This reverts commit 7842f28f4f2209b9a9ccaf8be1b00170109a2fec. | #!/usr/bin/env node
const yargs = require('yargs');
yargs
.usage('$0 command')
.command('all', 'run all bundled commands', yargs => {
const operations = require('./src');
console.log("yargs", yargs)
for (const key of Object.keys(operations)) {
operations[key]();
}
})
.command('fix-libraries', 'add any missing build configurations to all xcode projects in node_modules', yargs => {
require('./src/fix-libraries')();
})
.command('fix-script', 'replace the react native ios bundler with our scheme aware one', yargs => {
require('./src/fix-script')();
})
.command('hide-library-schemes', `hide any schemes that come from your node modules directory so they don't clutter up the menu.`, yargs => {
require('./src/hide-library-schemes')();
})
.command('verify-config', `check the configuration and ensure we have both a postinstall script and xcodeSchemes configurations.`, yargs => {
require('./src/verify-config')();
})
.demand(1, 'must provide a valid command')
.help('h')
.alias('h', 'help')
.argv;
| #!/usr/bin/env node
const yargs = require('yargs');
yargs
.usage('$0 command')
.command('all', 'run all bundled commands', yargs => {
const operations = require('./src');
console.log("yargs" yargs)
for (const key of Object.keys(operations)) {
operations[key]();
}
})
.command('fix-libraries', 'add any missing build configurations to all xcode projects in node_modules', yargs => {
require('./src/fix-libraries')();
})
.command('fix-script', 'replace the react native ios bundler with our scheme aware one', yargs => {
require('./src/fix-script')();
})
.command('hide-library-schemes', `hide any schemes that come from your node modules directory so they don't clutter up the menu.`, yargs => {
require('./src/hide-library-schemes')();
})
.command('verify-config', `check the configuration and ensure we have both a postinstall script and xcodeSchemes configurations.`, yargs => {
require('./src/verify-config')();
})
.demand(1, 'must provide a valid command')
.help('h')
.alias('h', 'help')
.argv;
|
Use check response for import update tests | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from integration.ggrc.converters import TestCase
from ggrc import models
class TestImportUpdates(TestCase):
""" Test importing of already existing objects """
def setUp(self):
TestCase.setUp(self)
self.client.get("/login")
def test_policy_basic_update(self):
""" Test simple policy title update """
filename = "policy_basic_import.csv"
response = self.import_file(filename)
self._check_response(response, {})
policy = models.Policy.query.filter_by(slug="p1").first()
self.assertEqual(policy.title, "some weird policy")
filename = "policy_basic_import_update.csv"
response = self.import_file(filename)
self._check_response(response, {})
policy = models.Policy.query.filter_by(slug="p1").first()
self.assertEqual(policy.title, "Edited policy")
| # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from integration.ggrc.converters import TestCase
from ggrc import models
class TestImportUpdates(TestCase):
""" Test importing of already existing objects """
def setUp(self):
TestCase.setUp(self)
self.client.get("/login")
def test_policy_basic_update(self):
""" Test simple policy title update """
messages = ("block_errors", "block_warnings", "row_errors", "row_warnings")
filename = "policy_basic_import.csv"
response = self.import_file(filename)
for block in response:
for message in messages:
self.assertEqual(set(), set(block[message]))
policy = models.Policy.query.filter_by(slug="p1").first()
self.assertEqual(policy.title, "some weird policy")
filename = "policy_basic_import_update.csv"
response = self.import_file(filename)
for block in response:
for message in messages:
self.assertEqual(set(), set(block[message]))
policy = models.Policy.query.filter_by(slug="p1").first()
self.assertEqual(policy.title, "Edited policy")
|
Bump dev version to 1.6 after releasing 1.5 | __version_info__ = (1, 6, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environment
def context_extras(request):
socialauth_providers = []
# generate a list of social auth providers associated with this account,
# for use in displaying available backends
if not request.user.is_anonymous():
socialauth_providers = [auth.provider for auth in request.user.social_auth.all()]
return {
# software version
'SW_VERSION': __version__,
# Alternate names for social-auth backends,
# to be used for display and font-awesome icon (lowercased)
# If not entered here, backend name will be used as-is for
# icon and title-cased for display (i.e., twitter / Twitter).
'backend_names': {
'github': 'GitHub',
'google-oauth2': 'Google',
},
'user_socialauth_providers': socialauth_providers
}
| __version_info__ = (1, 5, 1, None)
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environment
def context_extras(request):
socialauth_providers = []
# generate a list of social auth providers associated with this account,
# for use in displaying available backends
if not request.user.is_anonymous():
socialauth_providers = [auth.provider for auth in request.user.social_auth.all()]
return {
# software version
'SW_VERSION': __version__,
# Alternate names for social-auth backends,
# to be used for display and font-awesome icon (lowercased)
# If not entered here, backend name will be used as-is for
# icon and title-cased for display (i.e., twitter / Twitter).
'backend_names': {
'github': 'GitHub',
'google-oauth2': 'Google',
},
'user_socialauth_providers': socialauth_providers
}
|
Add placeholder text and suggest Last Name, First Name | (function() {
window.shared || (window.shared = {});
var dom = window.shared.ReactHelpers.dom;
var ProvidedByEducatorDropdown = window.shared.ProvidedByEducatorDropdown = React.createClass({
displayName: 'ProvidedByEducatorDropdown',
propTypes: {
educatorsForServicesDropdown: React.PropTypes.array.isRequired,
onChange: React.PropTypes.func.isRequired,
},
render: function () {
return dom.input({
className: 'ProvidedByEducatorDropdown',
onChange: this.props.onChange,
placeholder: 'Last Name, First Name...',
style: {
marginTop: 2,
fontSize: 14,
padding: 4,
width: '50%'
}
});
},
componentDidMount: function() {
$(ReactDOM.findDOMNode(this)).autocomplete({ source: this.props.educatorsForServicesDropdown });
},
componentWillUnmount: function() {
$(ReactDOM.findDOMNode(this)).autocomplete('destroy');
}
});
})();
| (function() {
window.shared || (window.shared = {});
var dom = window.shared.ReactHelpers.dom;
var ProvidedByEducatorDropdown = window.shared.ProvidedByEducatorDropdown = React.createClass({
displayName: 'ProvidedByEducatorDropdown',
propTypes: {
educatorsForServicesDropdown: React.PropTypes.array.isRequired,
onChange: React.PropTypes.func.isRequired,
},
render: function () {
return dom.input({
className: 'ProvidedByEducatorDropdown',
onChange: this.props.onChange,
style: {
marginTop: 2,
fontSize: 14,
padding: 4,
width: '50%'
}
});
},
componentDidMount: function() {
$(ReactDOM.findDOMNode(this)).autocomplete({ source: this.props.educatorsForServicesDropdown });
},
componentWillUnmount: function() {
$(ReactDOM.findDOMNode(this)).autocomplete('destroy');
}
});
})();
|
Fix copy/paste error in saga function name | import { takeLatest, put, select } from 'redux-saga/effects';
import {
MODIFY_PASSWORD1,
MODIFY_PASSWORD2,
MODIFY_PASSWORDS_NOT_IDENTICAL,
} from '../actiontypes';
function* comparePasswords() {
const password1 = yield select(state => state.password1);
const password2 = yield select(state => state.password2);
if (!password2) {
// if second password is empty we don't compare because it probably hasn't been typed into yet
yield put(MODIFY_PASSWORDS_NOT_IDENTICAL(false));
} else {
yield put(MODIFY_PASSWORDS_NOT_IDENTICAL(password1 !== password2));
}
}
export default function* passwordSaga() {
yield takeLatest(MODIFY_PASSWORD1, comparePasswords);
yield takeLatest(MODIFY_PASSWORD2, comparePasswords);
}
| import { takeLatest, put, select } from 'redux-saga/effects';
import {
MODIFY_PASSWORD1,
MODIFY_PASSWORD2,
MODIFY_PASSWORDS_NOT_IDENTICAL,
} from '../actiontypes';
function* comparePasswords() {
const password1 = yield select(state => state.password1);
const password2 = yield select(state => state.password2);
if (!password2) {
// if second password is empty we don't compare because it probably hasn't been typed into yet
yield put(MODIFY_PASSWORDS_NOT_IDENTICAL(false));
} else {
yield put(MODIFY_PASSWORDS_NOT_IDENTICAL(password1 !== password2));
}
}
export default function* userSaga() {
yield takeLatest(MODIFY_PASSWORD1, comparePasswords);
yield takeLatest(MODIFY_PASSWORD2, comparePasswords);
}
|
Change the background thread to daemon thread so that a script closes
all other threads closes as well | package detective.common.httpclient;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.HttpClientConnectionManager;
public class IdleConnectionMonitorThread extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
this.setDaemon(true);
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 30 sec
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
} | package detective.common.httpclient;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.HttpClientConnectionManager;
public class IdleConnectionMonitorThread extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 30 sec
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
} |
Handle IPv6 in REST API | """
Whip's REST API
"""
# pylint: disable=missing-docstring
from flask import Flask, make_response, request
from .db import Database
app = Flask(__name__)
app.config.from_envvar('WHIP_SETTINGS', silent=True)
db = None
@app.before_first_request
def _open_db():
global db # pylint: disable=global-statement
db = Database(app.config['DATABASE_DIR'])
@app.route('/ip/<ip>')
def lookup(ip):
datetime = request.args.get('datetime')
info_as_json = db.lookup(ip, datetime)
if info_as_json is None:
info_as_json = b'{}' # empty dict, JSON-encoded
response = make_response(info_as_json)
response.headers['Content-type'] = 'application/json'
return response
| """
Whip's REST API
"""
# pylint: disable=missing-docstring
from socket import inet_aton
from flask import Flask, abort, make_response, request
from .db import Database
app = Flask(__name__)
app.config.from_envvar('WHIP_SETTINGS', silent=True)
db = None
@app.before_first_request
def _open_db():
global db # pylint: disable=global-statement
db = Database(app.config['DATABASE_DIR'])
@app.route('/ip/<ip>')
def lookup(ip):
try:
key = inet_aton(ip)
except OSError:
abort(400)
datetime = request.args.get('datetime')
info_as_json = db.lookup(key, datetime)
if info_as_json is None:
info_as_json = b'{}' # empty dict, JSON-encoded
response = make_response(info_as_json)
response.headers['Content-type'] = 'application/json'
return response
|
Revert "Remove redirect to avoid Chrome privacy error"
This reverts commit e5322958f14b2428b74de726476fd98adae8c454. | from flask import Flask, render_template, request, redirect
import requests
import pandas as pd
from datetime import datetime
from bokeh.plotting import figure, output_notebook, output_file, save
app = Flask(__name__)
@app.route('/')
def main():
return redirect('/index')
@app.route('/index', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('index.html')
else:
pitcher = request.form['pitcher']
image_file = pitcher.lower()
image_file = image_file.split()
image_file = '_'.join(image_file) + '.png'
return render_template('results.html', image_file = image_file)
if __name__ == '__main__':
app.run(port=33508) | from flask import Flask, render_template, request, redirect
import requests
import pandas as pd
from datetime import datetime
from bokeh.plotting import figure, output_notebook, output_file, save
app = Flask(__name__)
# @app.route('/')
# def main():
# return redirect('/index')
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('index.html')
else:
pitcher = request.form['pitcher']
image_file = pitcher.lower()
image_file = image_file.split()
image_file = '_'.join(image_file) + '.png'
return render_template('results.html', image_file = image_file)
if __name__ == '__main__':
app.run(port=33508) |
KCIAC-332: Implement COI event type of "IACUC Protocol" | /*
* Copyright 2005-2010 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.kuali.kra.iacuc.personnel;
import org.kuali.kra.iacuc.IacucProtocol;
import org.kuali.kra.protocol.personnel.ProtocolPerson;
public class IacucProtocolPerson extends ProtocolPerson {
private static final long serialVersionUID = 6676849646094141708L;
public IacucProtocol getIacucProtocol() {
return (IacucProtocol) getProtocol();
}
}
| /*
* Copyright 2005-2010 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.kuali.kra.iacuc.personnel;
import org.kuali.kra.protocol.personnel.ProtocolPerson;
public class IacucProtocolPerson extends ProtocolPerson {
/**
* Comment for <code>serialVersionUID</code>
*/
private static final long serialVersionUID = 6676849646094141708L;
}
|
:arrow_up: Upgrade specs to latest API | 'use babel'
import * as _ from 'lodash'
import * as path from 'path'
describe('The Ispell provider for Atom Linter', () => {
const lint = require('../lib/providers').provideLinter().lint
beforeEach(() => {
waitsForPromise(() => {
return atom.packages.activatePackage('linter-spell')
})
})
it('finds a spelling in "foo.txt"', () => {
waitsForPromise(() => {
return atom.workspace.open(path.join(__dirname, 'files', 'foo.txt')).then(editor => {
return lint(editor).then(messages => {
expect(_.some(messages, (message) => { return message.excerpt.match(/^armour( ->|$)/) })).toBe(true)
})
})
})
})
})
| 'use babel'
import * as _ from 'lodash'
import * as path from 'path'
describe('The Ispell provider for Atom Linter', () => {
const lint = require('../lib/providers').provideLinter().lint
beforeEach(() => {
waitsForPromise(() => {
return atom.packages.activatePackage('linter-spell')
})
})
it('finds a spelling in "foo.txt"', () => {
waitsForPromise(() => {
return atom.workspace.open(path.join(__dirname, 'files', 'foo.txt')).then(editor => {
return lint(editor).then(messages => {
expect(_.some(messages, (message) => { return message.text.match(/^armour( ->|$)/) })).toBe(true)
})
})
})
})
})
|
Fix path to the executable to work in most of the cases. | var path = require('path'),
cmd = require('./lib/utils/cmd'),
fs = require('fs'),
Q = require('q'),
osenv = require('osenv'),
extractUser = require('./lib/utils/extractUser'),
extractPassword = require('./lib/utils/extractPassword'),
parseString = require('xml2js').parseString;
var fetch = exports.fetch = function() {
var deferred = Q.defer();
var m2Path = path.join(osenv.home(), '.m2');
var settingsXmlPath = path.join(m2Path, 'settings.xml');
var settingsSecurityXmlPath = path.join(m2Path, 'settings-security.xml');
cmd(__dirname + '/lib/settings-decoder/bin/settings-decoder', ['-f', settingsXmlPath, '-s', settingsSecurityXmlPath])
.then(function (stdout){
var username = extractUser(stdout[0]);
var password = extractPassword(stdout[0]);
deferred.resolve({
username: username,
password: password
});
})
.fail(deferred.reject);
return deferred.promise;
};
| var path = require('path'),
cmd = require('./lib/utils/cmd'),
fs = require('fs'),
Q = require('q'),
osenv = require('osenv'),
extractUser = require('./lib/utils/extractUser'),
extractPassword = require('./lib/utils/extractPassword'),
parseString = require('xml2js').parseString;
var fetch = exports.fetch = function() {
var deferred = Q.defer();
var m2Path = path.join(osenv.home(), '.m2');
var settingsXmlPath = path.join(m2Path, 'settings.xml');
var settingsSecurityXmlPath = path.join(m2Path, 'settings-security.xml');
cmd('./lib/settings-decoder/bin/settings-decoder', ['-f', settingsXmlPath, '-s', settingsSecurityXmlPath])
.then(function (stdout){
var username = extractUser(stdout[0]);
var password = extractPassword(stdout[0]);
deferred.resolve({
username: username,
password: password
});
})
.fail(deferred.reject);
return deferred.promise;
};
|
Enable hardware acceleration for all WebView
- LEARNER-7224 | package org.edx.mobile.view.custom;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebSettings;
import android.webkit.WebView;
import org.edx.mobile.BuildConfig;
import org.edx.mobile.R;
public class EdxWebView extends WebView {
@SuppressLint("SetJavaScriptEnabled")
public EdxWebView(Context context, AttributeSet attrs) {
super(context, attrs);
final WebSettings settings = getSettings();
settings.setJavaScriptEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setBuiltInZoomControls(false);
settings.setSupportZoom(true);
settings.setLoadsImagesAutomatically(true);
settings.setDomStorageEnabled(true);
settings.setUserAgentString(
settings.getUserAgentString() + " " +
context.getString(R.string.app_name) + "/" +
BuildConfig.APPLICATION_ID + "/" +
BuildConfig.VERSION_NAME
);
setLayerType(LAYER_TYPE_HARDWARE, null);
}
}
| package org.edx.mobile.view.custom;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebSettings;
import android.webkit.WebView;
import org.edx.mobile.BuildConfig;
import org.edx.mobile.R;
public class EdxWebView extends WebView {
@SuppressLint("SetJavaScriptEnabled")
public EdxWebView(Context context, AttributeSet attrs) {
super(context, attrs);
final WebSettings settings = getSettings();
settings.setJavaScriptEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setBuiltInZoomControls(false);
settings.setSupportZoom(true);
settings.setLoadsImagesAutomatically(true);
settings.setDomStorageEnabled(true);
settings.setUserAgentString(
settings.getUserAgentString() + " " +
context.getString(R.string.app_name) + "/" +
BuildConfig.APPLICATION_ID + "/" +
BuildConfig.VERSION_NAME
);
}
}
|
Fix bug where role change logged on nickname change. | exports.func = (client, oldMember, newMember) => {
if(oldMember.nickname != newMember.nickname) {
oldFormatted = oldMember.nickname ? `\`${oldMember.nickname}\`` : "_(none)_";
newFormatted = newMember.nickname ? `\`${newMember.nickname}\`` : "_(none)_";
client.logToGuild(newMember.guild, `:name_badge: ${client.formatUser(newMember.user)} nickname was changed from ${oldFormatted} to ${newFormatted}`);
}
if(!oldMember.roles.equals(newMember.roles)) {
oldArray = [];
newArray = [];
oldMember.roles.reduce((snowflake, role) => {
if(role.id == role.guild.id) return; // filters out @everyone
oldArray.push(role.name);
}, []);
newMember.roles.reduce((snowflake, role) => {
if(role.id == role.guild.id) return;
newArray.push(role.name);
}, []);
oldRoles = oldArray.join(', ') || "_(none)_";
newRoles = newArray.join(', ') || "_(none)_";
client.logToGuild(newMember.guild, `:lock_with_ink_pen: ${client.formatUser(newMember.user)} roles were changed:\n:b: ${oldRoles}\n:a: ${newRoles}`);
}
}; | exports.func = (client, oldMember, newMember) => {
if(oldMember.nickname != newMember.nickname) {
oldFormatted = oldMember.nickname ? `\`${oldMember.nickname}\`` : "_(none)_";
newFormatted = newMember.nickname ? `\`${newMember.nickname}\`` : "_(none)_";
client.logToGuild(newMember.guild, `:name_badge: ${client.formatUser(newMember.user)} nickname was changed from ${oldFormatted} to ${newFormatted}`);
}
if(oldMember.roles != newMember.roles) {
oldArray = [];
newArray = [];
oldMember.roles.reduce((snowflake, role) => {
if(role.id == role.guild.id) return; // filters out @everyone
oldArray.push(role.name);
}, []);
newMember.roles.reduce((snowflake, role) => {
if(role.id == role.guild.id) return;
newArray.push(role.name);
}, []);
oldRoles = oldArray.join(', ') || "_(none)_";
newRoles = newArray.join(', ') || "_(none)_";
client.logToGuild(newMember.guild, `:lock_with_ink_pen: ${client.formatUser(newMember.user)} roles were changed:\n:b: ${oldRoles}\n:a: ${newRoles}`);
}
}; |
Replace function for arrow function | import del from 'del';
import gulp from 'gulp';
import babel from 'gulp-babel';
import gls from 'gulp-live-server';
const port = 12345;
const dirs = {
src: 'src',
dist: 'dist', // Not being used for now. To be used in prodution
dev: 'dev'
};
const files = {
indexJS: 'bootstrap.js',
indexSASS: 'index.sass'
}
gulp.task('serve', () => {
var server = gls.static(`/`, port);
server.start();
gulp.watch([`${dirs.dev}/${files.indexJS}`], (file) => {
server.notify.apply(server, [file]);
});
});
gulp.task('copy', () => {
return gulp.src(`${dirs.src}/**/*.html`)
.pipe(gulp.dest(`${dirs.dev}`));
});
gulp.task('build', () => {
return gulp.src(`${dirs.src}/**/*.js`)
.pipe(babel())
.pipe(gulp.dest(`${dirs.dev}`));
});
gulp.task('clean', () => {
return del(dirs.dev);
});
gulp.task('default', ['copy', 'build']);
| import del from 'del';
import gulp from 'gulp';
import babel from 'gulp-babel';
import gls from 'gulp-live-server';
const port = 12345;
const dirs = {
src: 'src',
dist: 'dist', // Not being used for now. To be used in prodution
dev: 'dev'
};
const files = {
indexJS: 'bootstrap.js',
indexSASS: 'index.sass'
}
gulp.task('serve', () => {
var server = gls.static(`/`, port);
server.start();
gulp.watch([`${dirs.dev}/${files.indexJS}`], function (file) {
server.notify.apply(server, [file]);
});
});
gulp.task('copy', () => {
return gulp.src(`${dirs.src}/**/*.html`)
.pipe(gulp.dest(`${dirs.dev}`));
});
gulp.task('build', () => {
return gulp.src(`${dirs.src}/**/*.js`)
.pipe(babel())
.pipe(gulp.dest(`${dirs.dev}`));
});
gulp.task('clean', () => {
return del(dirs.dev);
});
gulp.task('default', ['copy', 'build']);
|
Mark notification as all read when closing popup | function NotificationDirective() {
var directive = {
restrict: 'EA',
templateUrl: 'notifications/notificationsDirective.tpl.html',
controller: NotificationDirectiveCtrl,
controllerAs: 'vm',
bindToController: true,
link: link,
};
return directive;
function link(scope, element, attrs) {
//console.log('linked');
}
}
// @ngInject
function NotificationDirectiveCtrl($scope, NotificationService) {
var vm = this;
vm.notifications = NotificationService.items;
init();
function init() {
NotificationService.getNotifications();
$scope.$on('$destroy', function() {
NotificationService.markAsAllRead();
});
}
}
function NotificationCountDirective() {
var directive = {
restrict: 'EA',
controller: NotificationCountDirectiveCtrl,
controllerAs: 'vm',
bindToController: true,
link: link,
};
return directive;
function link(scope, element, attrs) {
//console.log('linked');
}
}
// @ngInject
function NotificationCountDirectiveCtrl(NotificationService) {
var vm = this;
vm.getUnreadNotificationsCount = NotificationService.getUnreadNotificationsCount;
init();
function init() {
console.log('fetching unread notifs');
NotificationService.getUnreadNotifications();
}
}
angular
.module('portal.notifications')
.directive('notificationsCount', NotificationCountDirective)
.directive('notifications', NotificationDirective);
| function NotificationDirective() {
var directive = {
restrict: 'EA',
templateUrl: 'notifications/notificationsDirective.tpl.html',
controller: NotificationDirectiveCtrl,
controllerAs: 'vm',
bindToController: true,
link: link,
};
return directive;
function link(scope, element, attrs) {
//console.log('linked');
}
}
// @ngInject
function NotificationDirectiveCtrl(NotificationService) {
var vm = this;
vm.notifications = NotificationService.items;
init();
function init() {
NotificationService.getNotifications().then(function() {
NotificationService.markAsAllRead();
});
}
}
function NotificationCountDirective() {
var directive = {
restrict: 'EA',
controller: NotificationCountDirectiveCtrl,
controllerAs: 'vm',
bindToController: true,
link: link,
};
return directive;
function link(scope, element, attrs) {
//console.log('linked');
}
}
// @ngInject
function NotificationCountDirectiveCtrl(NotificationService) {
var vm = this;
vm.getUnreadNotificationsCount = NotificationService.getUnreadNotificationsCount;
init();
function init() {
console.log('fetching unread notifs');
NotificationService.getUnreadNotifications();
}
}
angular
.module('portal.notifications')
.directive('notificationsCount', NotificationCountDirective)
.directive('notifications', NotificationDirective);
|
Remove default value & make published_at nullable | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateArticlesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('articles', function (Blueprint $table)
{
$table->increments('id');
$table->string('type')->default('post'); // post, page
$table->integer('user_id');
$table->integer('category_id')->default(0);
$table->string('title');
$table->string('slug');
$table->text('body');
$table->string('image')->nullable();
$table->string('published_at')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('articles');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateArticlesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('articles', function (Blueprint $table)
{
$table->increments('id');
$table->string('type')->default('post'); // post, page
$table->integer('user_id');
$table->integer('category_id')->default(0);
$table->string('title');
$table->string('slug');
$table->text('body');
$table->string('image')->nullable();
$table->string('published_at')->default('NOW()');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('articles');
}
}
|
Enable DI when create the preset providers | <?php
namespace Concrete\Core\Area\Layout\Preset\Provider;
use Concrete\Core\Foundation\Service\Provider as ServiceProvider;
use Concrete\Core\Application\Application;
class ManagerServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(
Manager::class,
static function(Application $app): Manager {
$manager = new Manager($app);
$manager->register($app->make(UserProvider::class));
$manager->register($app->make(ActiveThemeProvider::class));
return $manager;
}
);
$this->app->alias(Manager::class, 'manager/area_layout_preset_provider');
}
}
| <?php
namespace Concrete\Core\Area\Layout\Preset\Provider;
use Concrete\Core\Foundation\Service\Provider as ServiceProvider;
use Concrete\Core\Application\Application;
class ManagerServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(
Manager::class,
static function(Application $app): Manager {
$manager = new Manager($app);
$manager->register(new UserProvider());
$manager->register(new ActiveThemeProvider());
return $manager;
}
);
$this->app->alias(Manager::class, 'manager/area_layout_preset_provider');
}
}
|
Use correct test data path | """
Tests of neo.rawio.examplerawio
Note for dev:
if you write a new RawIO class your need to put some file
to be tested at g-node portal, Ask neuralensemble list for that.
The file need to be small.
Then you have to copy/paste/renamed the TestExampleRawIO
class and a full test will be done to test if the new coded IO
is compliant with the RawIO API.
If you have problems, do not hesitate to ask help github (prefered)
of neuralensemble list.
Note that same mechanism is used a neo.io API so files are tested
several time with neo.rawio (numpy buffer) and neo.io (neo object tree).
See neo.test.iotest.*
Author: Samuel Garcia
"""
import logging
import unittest
from neo.rawio.alphaomegarawio import AlphaOmegaRawIO
from neo.test.rawiotest.common_rawio_test import BaseTestRawIO
logging.getLogger().setLevel(logging.INFO)
class TestAlphaOmegaRawIO(BaseTestRawIO, unittest.TestCase):
rawioclass = AlphaOmegaRawIO
entities_to_download = [
"alphaomega",
]
entities_to_test = [
"alphaomega/mpx_map_version4",
]
if __name__ == "__main__":
unittest.main()
| """
Tests of neo.rawio.examplerawio
Note for dev:
if you write a new RawIO class your need to put some file
to be tested at g-node portal, Ask neuralensemble list for that.
The file need to be small.
Then you have to copy/paste/renamed the TestExampleRawIO
class and a full test will be done to test if the new coded IO
is compliant with the RawIO API.
If you have problems, do not hesitate to ask help github (prefered)
of neuralensemble list.
Note that same mechanism is used a neo.io API so files are tested
several time with neo.rawio (numpy buffer) and neo.io (neo object tree).
See neo.test.iotest.*
Author: Samuel Garcia
"""
import logging
import unittest
from neo.rawio.alphaomegarawio import AlphaOmegaRawIO
from neo.test.rawiotest.common_rawio_test import BaseTestRawIO
logging.getLogger().setLevel(logging.INFO)
class TestAlphaOmegaRawIO(BaseTestRawIO, unittest.TestCase):
rawioclass = AlphaOmegaRawIO
entities_to_download = [
"alphaomega",
]
entities_to_test = [
"alphaomega/",
]
if __name__ == "__main__":
unittest.main()
|
Use sha256 algorithm from pycrypto. | #
# Copyright (c) 2004-2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"Compatibility module for python 2.4 - 2.6"
try:
import hashlib
sha1 = hashlib.sha1
md5 = hashlib.md5
except ImportError:
import sha
import md5
sha1 = sha.new
md5 = md5.new
from Crypto.Hash import SHA256
sha256 = SHA256.new
| #
# Copyright (c) 2004-2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"Compatibility module for python 2.4 - 2.6"
try:
import hashlib
sha1 = hashlib.sha1
md5 = hashlib.md5
sha256 = hashlib.sha256
except ImportError:
import sha
import md5
from Crypto.Hash import SHA256
sha1 = sha.new
md5 = md5.new
sha256 = SHA256.new
|
Remove unused imports from AppConfig module. | """Django DDP app config."""
from __future__ import print_function
from django.apps import AppConfig
from django.conf import settings, ImproperlyConfigured
from dddp import autodiscover
class DjangoDDPConfig(AppConfig):
"""Django app config for django-ddp."""
api = None
name = 'dddp'
verbose_name = 'Django DDP'
_in_migration = False
def ready(self):
"""Initialisation for django-ddp (setup lookups and signal handlers)."""
if not settings.DATABASES:
raise ImproperlyConfigured('No databases configured.')
for (alias, conf) in settings.DATABASES.items():
if conf['ENGINE'] != 'django.db.backends.postgresql_psycopg2':
raise ImproperlyConfigured(
'%r uses %r: django-ddp only works with PostgreSQL.' % (
alias, conf['backend'],
)
)
self.api = autodiscover()
self.api.ready()
| """Django DDP app config."""
from __future__ import print_function
from django.apps import AppConfig
from django.conf import settings, ImproperlyConfigured
from django.db import DatabaseError
from django.db.models import signals
from dddp import autodiscover
from dddp.models import Connection
class DjangoDDPConfig(AppConfig):
"""Django app config for django-ddp."""
api = None
name = 'dddp'
verbose_name = 'Django DDP'
_in_migration = False
def ready(self):
"""Initialisation for django-ddp (setup lookups and signal handlers)."""
if not settings.DATABASES:
raise ImproperlyConfigured('No databases configured.')
for (alias, conf) in settings.DATABASES.items():
if conf['ENGINE'] != 'django.db.backends.postgresql_psycopg2':
raise ImproperlyConfigured(
'%r uses %r: django-ddp only works with PostgreSQL.' % (
alias, conf['backend'],
)
)
self.api = autodiscover()
self.api.ready()
|
Add panic method for panicking a context from either side | <?php
namespace Icicle\Concurrent;
/**
* Interface for all types of execution contexts.
*/
interface ContextInterface extends SynchronizableInterface
{
/**
* Creates a new context with a given function to run.
*
* @return ContextInterface A context instance.
*/
//public static function create(callable $function);
/**
* Checks if the context is running.
*
* @return bool True if the context is running, otherwise false.
*/
public function isRunning();
/**
* Starts the context execution.
*/
public function start();
/**
* Stops context execution.
*/
public function stop();
/**
* Immediately kills the context without invoking any handlers.
*/
public function kill();
/**
* Causes the context to immediately panic.
*
* @param string $message A panic message.
* @param int $code A panic code.
*/
public function panic($message = '', $code = 0);
/**
* Gets a promise that resolves when the context ends and joins with the
* parent context.
*
* @return \Icicle\Promise\PromiseInterface Promise that is resolved when the context finishes.
*/
public function join();
}
| <?php
namespace Icicle\Concurrent;
/**
* Interface for all types of execution contexts.
*/
interface ContextInterface extends SynchronizableInterface
{
/**
* Creates a new context with a given function to run.
*
* @return ContextInterface A context instance.
*/
//public static function create(callable $function);
/**
* Checks if the context is running.
*
* @return bool True if the context is running, otherwise false.
*/
public function isRunning();
/**
* Starts the context execution.
*/
public function start();
/**
* Stops context execution.
*/
public function stop();
/**
* Immediately kills the context without invoking any handlers.
*/
public function kill();
/**
* Gets a promise that resolves when the context ends and joins with the
* parent context.
*
* @return \Icicle\Promise\PromiseInterface Promise that is resolved when the context finishes.
*/
public function join();
}
|
Revert "Update version inside constant.php"
This reverts commit ad751383f50b96b48a915e1d022c912f1114d166. | <?php
/**
* CheckoutApi_Client_Constant
* A final class that manage constant value for all CheckoutApi_Client_Client instance
* @package CheckoutApi_Client
* @category Api
* @author Dhiraj Gangoosirdar <dhiraj.gangoosirdar@checkout.com>
* @copyright 2014 Integration team (http://www.checkout.com)
*/
final class CheckoutApi_Client_Constant
{
const APIGW3_URI_PREFIX_PREPOD = 'http://preprod.checkout.com/api2/';
const APIGW3_URI_PREFIX_DEV= 'http://dev.checkout.com/api2/';
const APIGW3_URI_PREFIX_SANDBOX= 'http://sandbox.checkout.com/api2/';
const APIGW3_URI_PREFIX_LIVE = 'https://api2.checkout.com/';
const ADAPTER_CLASS_GROUP = 'CheckoutApi_Client_Adapter_';
const PARSER_CLASS_GROUP = 'CheckoutApi_Parser_';
const CHARGE_TYPE = 'card';
const LOCALPAYMENT_CHARGE_TYPE = 'localPayment';
const TOKEN_CARD_TYPE = 'cardToken';
const TOKEN_SESSION_TYPE = 'sessionToken';
const AUTOCAPUTURE_CAPTURE = 'y';
const AUTOCAPUTURE_AUTH = 'n';
const VERSION = 'v2';
const STATUS_CAPTURE = 'Captured';
const LIB_VERSION = 'v1.2.4';
} | <?php
/**
* CheckoutApi_Client_Constant
* A final class that manage constant value for all CheckoutApi_Client_Client instance
* @package CheckoutApi_Client
* @category Api
* @author Dhiraj Gangoosirdar <dhiraj.gangoosirdar@checkout.com>
* @copyright 2014 Integration team (http://www.checkout.com)
*/
final class CheckoutApi_Client_Constant
{
const APIGW3_URI_PREFIX_PREPOD = 'http://preprod.checkout.com/api2/';
const APIGW3_URI_PREFIX_DEV= 'http://dev.checkout.com/api2/';
const APIGW3_URI_PREFIX_SANDBOX= 'http://sandbox.checkout.com/api2/';
const APIGW3_URI_PREFIX_LIVE = 'https://api2.checkout.com/';
const ADAPTER_CLASS_GROUP = 'CheckoutApi_Client_Adapter_';
const PARSER_CLASS_GROUP = 'CheckoutApi_Parser_';
const CHARGE_TYPE = 'card';
const LOCALPAYMENT_CHARGE_TYPE = 'localPayment';
const TOKEN_CARD_TYPE = 'cardToken';
const TOKEN_SESSION_TYPE = 'sessionToken';
const AUTOCAPUTURE_CAPTURE = 'y';
const AUTOCAPUTURE_AUTH = 'n';
const VERSION = 'v2';
const STATUS_CAPTURE = 'Captured';
const LIB_VERSION = 'v1.2.5';
} |
Add theme templates and static as package_data. | from setuptools import setup, find_packages
setup(
name="153957-theme",
version="1.0.0",
packages=find_packages(),
url="http://github.com/153957/153957-theme/",
bugtrack_url='http://github.com/153957/153957-theme/issues',
license='MIT',
author="Arne de Laat",
author_email="arne@delaat.net",
description="Theme for sigal generated photo albums",
long_description=open('README.rst').read(),
keywords=['photo album', 'theme', 'sigal', 'galleria'],
classifiers=[
'Environment :: Plugins',
'Environment :: Web Environment',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Text Processing :: Markup :: HTML',
],
install_requires=['sigal'],
package_data={
'153957_theme': [
'templates/*.html',
'static/*/*',
]
},
)
| from setuptools import setup, find_packages
setup(name="153957-theme",
version="1.0.0",
packages=find_packages(),
url="http://github.com/153957/153957-theme/",
bugtrack_url='http://github.com/153957/153957-theme/issues',
license='MIT',
author="Arne de Laat",
author_email="arne@delaat.net",
description="Theme for sigal generated photo albums",
long_description=open('README.rst').read(),
keywords=['photo album', 'theme', 'sigal', 'galleria'],
classifiers=['Environment :: Plugins',
'Environment :: Web Environment',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Text Processing :: Markup :: HTML'],
install_requires=['sigal'],
)
|
Change test function as existing method deprecated | import pytest
@pytest.mark.parametrize("name, linked_to", [
("/home/wicksy/vagrant/Vagrantfile", "/git/wicksy/configfiles/vagrant/Vagrantfile"),
("/home/wicksy/.vimrc", "/git/wicksy/configfiles/dotfiles/.vimrc"),
("/home/wicksy/.bashrc", "/git/wicksy/configfiles/dotfiles/.bashrc"),
("/home/wicksy/.aws", "/git/wicksy/configfiles/dotfiles/.aws"),
("/home/wicksy/.config", "/git/wicksy/configfiles/dotfiles/.config"),
("/home/wicksy/.gitconfig", "/git/wicksy/configfiles/dotfiles/.gitconfig"),
("/home/wicksy/.ssh/config", "/git/wicksy/configfiles/dotfiles/.ssh/config"),
])
def test_links(host, name, linked_to):
file = host.file(name)
assert file.exists
assert file.is_symlink
assert file.linked_to == str(linked_to) | import pytest
@pytest.mark.parametrize("name, linked_to", [
("/home/wicksy/vagrant/Vagrantfile", "/git/wicksy/configfiles/vagrant/Vagrantfile"),
("/home/wicksy/.vimrc", "/git/wicksy/configfiles/dotfiles/.vimrc"),
("/home/wicksy/.bashrc", "/git/wicksy/configfiles/dotfiles/.bashrc"),
("/home/wicksy/.aws", "/git/wicksy/configfiles/dotfiles/.aws"),
("/home/wicksy/.config", "/git/wicksy/configfiles/dotfiles/.config"),
("/home/wicksy/.gitconfig", "/git/wicksy/configfiles/dotfiles/.gitconfig"),
("/home/wicksy/.ssh/config", "/git/wicksy/configfiles/dotfiles/.ssh/config"),
])
def test_links(File, name, linked_to):
assert File(name).exists
assert File(name).is_symlink
assert File(name).linked_to == str(linked_to) |
Enable filtering OpenStack package by tenant. | import django_filters
from nodeconductor.core.filters import UUIDFilter
from . import models
class PackageTemplateFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_type='icontains')
settings_uuid = UUIDFilter(name='service_settings__uuid')
class Meta(object):
model = models.PackageTemplate
fields = ('name', 'settings_uuid',)
class OpenStackPackageFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_type='icontains')
customer = UUIDFilter(name='tenant__service_project_link__project__customer__uuid')
project = UUIDFilter(name='tenant__service_project_link__project__uuid')
tenant = UUIDFilter(name='tenant__uuid')
class Meta(object):
model = models.OpenStackPackage
fields = ('name', 'customer', 'project', 'tenant')
| import django_filters
from nodeconductor.core.filters import UUIDFilter
from . import models
class PackageTemplateFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_type='icontains')
settings_uuid = UUIDFilter(name='service_settings__uuid')
class Meta(object):
model = models.PackageTemplate
fields = ('name', 'settings_uuid',)
class OpenStackPackageFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_type='icontains')
customer = UUIDFilter(name='tenant__service_project_link__project__customer')
project = UUIDFilter(name='tenant__service_project_link__project')
class Meta(object):
model = models.OpenStackPackage
fields = ('name', 'customer', 'project')
|
Add sleep to flaky headless test | var assert = require('chai').assert;
var Context = require('../headless-context');
var context;
describe('Core window events', function() {
beforeEach(function() {
context = new Context();
});
afterEach(function() {
context.close();
})
it('should not fire move event without scroll', function() {
return context.evaluate(function() {
ventana.on('move', function() {
window.STATE.moved = true;
});
})
.getExecution()
.evaluate(function() {
return window.STATE.moved;
}).then(function(result) {
assert(!result, 'Move event not fired');
});
});
it('should fire move event after scroll', function() {
return context.evaluate(function() {
ventana.on('move', function() {
window.STATE.moved = true;
});
})
.scrollTo(100)
.wait(10)
.getExecution()
.evaluate(function() {
return window.STATE.moved;
}).then(function(result) {
assert(result, 'Move event fired');
});
});
});
| var assert = require('chai').assert;
var Context = require('../headless-context');
var context;
describe('Core window events', function() {
beforeEach(function() {
context = new Context();
});
afterEach(function() {
context.close();
})
it('should not fire move event without scroll', function() {
return context.evaluate(function() {
ventana.on('move', function() {
window.STATE.moved = true;
});
})
.getExecution()
.evaluate(function() {
return window.STATE.moved;
}).then(function(result) {
assert(!result, 'Move event not fired');
});
});
it('should fire move event after scroll', function() {
return context.evaluate(function() {
ventana.on('move', function() {
window.STATE.moved = true;
});
})
.scrollTo(100)
.getExecution()
.evaluate(function() {
return window.STATE.moved;
}).then(function(result) {
assert(result, 'Move event fired');
});
});
});
|
Add the delete and the edit functionality | function NotesApplication(author) {
this.author = author;
this.notesList = [];
}
NotesApplication.prototype.create(note_content){
this.notesList.push(note_content)
}
NotesApplication.prototype.listNotes(){
if(this.notesList.length>0){
for(i = 0; i<this.notesList.length; i++){
console.log("Note ID: " +i)
console.log(this.notesList[i])
console.log("By Author " + this.author );
}
}
}
NotesApplication.prototype.get(note_id){
console.log(this.notesList[note_id]);
}
NotesApplication.prototype.search(search_text){
var result = "Showing results for search"
for(i=0; i<this.notesList.length; i++){
if(this.notesList.indexOf(search_text) !== -1){
}
}
}
NotesApplication.prototype.delete(note_id){
if(this.notesList.length> note_id)
this.notesList.splice(note_id, 1)
}
NotesApplication.prototype.edit(note_id, new_content){
if(this.notesList.length > note_id){
this.notesList[note_id] = new_content;
}
} | function NotesApplication(author) {
this.author = author;
this.notesList = [];
}
NotesApplication.prototype.create(note_content){
this.notesList.push(note_content)
}
NotesApplication.prototype.listNotes(){
if(this.notesList.length>0){
for(i = 0; i<this.notesList.length; i++){
console.log("Note ID: " +i)
console.log(this.notesList[i])
console.log("By Author " + this.author );
}
}
}
NotesApplication.prototype.get(note_id){
return this.notesList[note_id];
}
NotesApplication.prototype.search(search_text){
var result = "Showing results for search"
for(i=0; i<this.notesList.length; i++){
if(this.notesList.indexOf(search_text) !== -1){
}
}
} |
Update text bounding box calculation method | /**
* Returns the bounding box of the specified text
* @param {string} text - specifies the text
* @returns {Array<number>}
*/
export const textBoundingBox = (text) => {
return [text.length * 9.6, 18]; // OxygenSans font prediction
};
/**
* Returns the area covered by the specified render nodes
* @param {Array<RenderNode>} renderNodes - specifies the render nodes
* @returns {Array<Array<number>>|null}
*/
export const renderNodesBoundingBox = (renderNodes) => {
if (renderNodes.length === 0) {
return null;
}
return renderNodes.reduce((a, rn) => [
[Math.min(a[0][0], rn.position[0]), Math.min(a[0][1], rn.position[1])],
[Math.max(a[1][0], rn.position[0] + rn.size[0]), Math.max(a[1][1], rn.position[1] + rn.size[1])]
], [[Infinity, Infinity], [-Infinity, -Infinity]]);
};
/**
* @param {Array<RenderPoint>} renderPoints - lol
* @returns {Array<number>|null}
*/
export const renderPointsBoundingBox = (renderPoints) => {
if (renderPoints.length === 0) {
return null;
}
return renderPoints.reduce((a, rp) => [Math.max(a[0], rp.size[0]), Math.max(a[1], rp.size[1])], [0, 0]);
};
| /**
* Returns the bounding box of the specified text
* @param {string} text - specifies the text
* @returns {Array<number>}
*/
export const textBoundingBox = (text) => {
return [text.length * 8, 17]; // Inconsolata font prediction
};
/**
* Returns the area covered by the specified render nodes
* @param {Array<RenderNode>} renderNodes - specifies the render nodes
* @returns {Array<Array<number>>|null}
*/
export const renderNodesBoundingBox = (renderNodes) => {
if (renderNodes.length === 0) {
return null;
}
return renderNodes.reduce((a, rn) => [
[Math.min(a[0][0], rn.position[0]), Math.min(a[0][1], rn.position[1])],
[Math.max(a[1][0], rn.position[0] + rn.size[0]), Math.max(a[1][1], rn.position[1] + rn.size[1])]
], [[Infinity, Infinity], [-Infinity, -Infinity]]);
};
/**
* @param {Array<RenderPoint>} renderPoints - lol
* @returns {Array<number>|null}
*/
export const renderPointsBoundingBox = (renderPoints) => {
if (renderPoints.length === 0) {
return null;
}
return renderPoints.reduce((a, rp) => [Math.max(a[0], rp.size[0]), Math.max(a[1], rp.size[1])], [0, 0]);
};
|
Change from email address in Contact | <?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
// Create the email and send the message
$to = 'c.woodside@thedifferenceengine.io'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@thedifferenceengine.io\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
| <?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
// Create the email and send the message
$to = 'c.woodside@thedifferenceengine.io'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: c.woodside@thedifferenceengine.io\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
|
Return early when catching CiviCRM API call exception in local connector. | <?php
/**
* TODO
*
* @author BjΓΆrn Endres, SYSTOPIA (endres@systopia.de)
*/
namespace CMRF\Connection;
use CMRF\Core\Call as Call;
use CMRF\Core\Connection as Connection;
class Local extends Connection {
public function getType() {
return 'local';
}
public function isReady() {
return function_exists('civicrm_api3');
}
/**
* execute the given call synchroneously
*
* return call status
*/
public function executeCall(Call $call) {
try {
$reply = civicrm_api3(
$call->getEntity(),
$call->getAction(),
$this->getAPI3Params($call));
} catch (\Exception $e) {
$call->setStatus(Call::STATUS_FAILED, $e->getMessage());
return $call->getReply();
}
// Hack from CiviCRM core to make the reply behave similar as the remote API.
// Meaning that a scalar value (a number, string etc.) should be wrapped in an array by the key result.
if (is_scalar($reply)) {
if (!$reply) {
$reply = 0;
}
$reply = array(
'is_error' => 0,
'result' => $reply
);
}
$call->setReply($reply);
return $reply;
}
}
| <?php
/**
* TODO
*
* @author BjΓΆrn Endres, SYSTOPIA (endres@systopia.de)
*/
namespace CMRF\Connection;
use CMRF\Core\Call as Call;
use CMRF\Core\Connection as Connection;
class Local extends Connection {
public function getType() {
return 'local';
}
public function isReady() {
return function_exists('civicrm_api3');
}
/**
* execute the given call synchroneously
*
* return call status
*/
public function executeCall(Call $call) {
try {
$reply = civicrm_api3(
$call->getEntity(),
$call->getAction(),
$this->getAPI3Params($call));
} catch (\Exception $e) {
$call->setStatus(Call::STATUS_FAILED, $e->getMessage());
}
// Hack from CiviCRM core to make the reply behave similar as the remote API.
// Meaning that a scalar value (a number, string etc.) should be wrapped in an array by the key result.
if (is_scalar($reply)) {
if (!$reply) {
$reply = 0;
}
$reply = array(
'is_error' => 0,
'result' => $reply
);
}
$call->setReply($reply);
return $reply;
}
}
|
Fix DB call in user:list command | <?php
namespace Criterion\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class UserListCommand extends Command
{
protected function configure()
{
$this
->setName('user:list')
->setDescription('List all users')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// Check for users
$users = $this->getApplication()->app->db->selectCollection('users')->find();
if ($users->count() < 1) {
$output->writeln('<error>Could not find any users</error>');
return false;
}
$i = 0;
foreach ($users as $user) {
echo '[' . (++$i) . '] ' . $user['username'] . ':' . (isset($user['role']) ? $user['role'] : 'user') . "\n";
}
}
}
| <?php
namespace Criterion\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class UserListCommand extends Command
{
protected function configure()
{
$this
->setName('user:list')
->setDescription('List all users')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// Check for users
$users = $this->getApplication()->db->selectCollection('users')->find();
if ($users->count() < 1) {
$output->writeln('<error>Could not find any users</error>');
return false;
}
$i = 0;
foreach ($users as $user) {
echo '[' . (++$i) . '] ' . $user['username'] . ':' . (isset($user['role']) ? $user['role'] : 'user') . "\n";
}
}
}
|
Fix bug where previous instances would populate the new OutputPipe | import sys
import re
from xc_exception import TestFailureError
from colors import Colors
from meta_line import MetaLine
from line import Line
class OutputPipe:
meta_lines = []
verbose = True
pretty = True
unacceptable_output = []
# unacceptable_output is usful for failing based on command output, rather than
# exitcode
def __init__(self, verbose = True, pretty = True, unacceptable_output=[]):
self.verbose = verbose
self.pretty = pretty
self.unacceptable_output = unacceptable_output
self.meta_lines = []
def put_line(self, line):
m_line = MetaLine(line)
self.meta_lines.append(m_line)
if self.verbose:
if self.pretty:
output = m_line.str()
else:
output = line
sys.stdout.write(output)
for uo in self.unacceptable_output:
if re.compile(uo).match(line):
raise TestFailureError(line)
| import sys
import re
from xc_exception import TestFailureError
from colors import Colors
from meta_line import MetaLine
from line import Line
class OutputPipe:
meta_lines = []
verbose = True
pretty = True
unacceptable_output = []
# unacceptable_output is usful for failing based on command output, rather than
# exitcode
def __init__(self, verbose = True, pretty = True, unacceptable_output=[]):
self.verbose = verbose
self.pretty = pretty
self.unacceptable_output = unacceptable_output
def put_line(self, line):
m_line = MetaLine(line)
self.meta_lines.append(m_line)
if self.verbose:
if self.pretty:
output = m_line.str()
else:
output = line
sys.stdout.write(output)
for uo in self.unacceptable_output:
if re.compile(uo).match(line):
raise TestFailureError(line)
|
Add dictionaries for channels and usermodes | from twisted.words.protocols import irc
class HeufyBotConnection(irc.IRC):
def __init__(self, protocol):
self.protocol = protocol
self.nick = "PyHeufyBot" # TODO This will be set by a configuration at some point
self.ident = "PyHeufyBot" # TODO This will be set by a configuration at some point
self.gecos = "PyHeufyBot IRC Bot" # TODO This will be set by a configuration at some point
self.channels = {}
self.usermodes = {}
def connectionMade(self):
self.cmdNICK(self.nick)
self.cmdUSER(self.ident, self.gecos)
def connectionLost(self, reason=""):
print reason
def dataReceived(self, data):
print data
def sendMessage(self, command, *parameter_list, **prefix):
print command, " ".join(parameter_list)
irc.IRC.sendMessage(self, command, *parameter_list, **prefix)
def cmdNICK(self, nick):
self.sendMessage("NICK", nick)
def cmdUSER(self, ident, gecos):
# RFC2812 allows usermodes to be set, but this isn't implemented much in IRCds at all.
# Pass 0 for usermodes instead.
self.sendMessage("USER", ident, "0", "*", ":{}".format(gecos))
| from twisted.words.protocols import irc
class HeufyBotConnection(irc.IRC):
def __init__(self, protocol):
self.protocol = protocol
self.nick = "PyHeufyBot" # TODO This will be set by a configuration at some point
self.ident = "PyHeufyBot" # TODO This will be set by a configuration at some point
self.gecos = "PyHeufyBot IRC Bot" # TODO This will be set by a configuration at some point
def connectionMade(self):
self.cmdNICK(self.nick)
self.cmdUSER(self.ident, self.gecos)
def connectionLost(self, reason=""):
print reason
def dataReceived(self, data):
print data
def sendMessage(self, command, *parameter_list, **prefix):
print command, " ".join(parameter_list)
irc.IRC.sendMessage(self, command, *parameter_list, **prefix)
def cmdNICK(self, nick):
self.sendMessage("NICK", nick)
def cmdUSER(self, ident, gecos):
# RFC2812 allows usermodes to be set, but this isn't implemented much in IRCds at all.
# Pass 0 for usermodes instead.
self.sendMessage("USER", ident, "0", "*", ":{}".format(gecos))
|
Fix for byte literals compatibility. | from django import http
from django.contrib import auth
from django.core import exceptions
class TokenMiddleware(object):
"""
Middleware that authenticates against a token in the http authorization
header.
"""
get_response = None
def __init__(self, get_response=None):
self.get_response = get_response
def __call__(self, request):
if not self.get_response:
return exceptions.ImproperlyConfigured(
'Middleware called without proper initialization')
self.process_request(request)
return self.get_response(request)
def process_request(self, request):
auth_header = str(request.META.get('HTTP_AUTHORIZATION', '')).partition(' ')
if auth_header[0].lower() != 'token':
return None
# If they specified an invalid token, let them know.
if not auth_header[2]:
return http.HttpResponseBadRequest("Improperly formatted token")
user = auth.authenticate(token=auth_header[2])
if user:
request.user = user
| from django import http
from django.contrib import auth
from django.core import exceptions
class TokenMiddleware(object):
"""
Middleware that authenticates against a token in the http authorization
header.
"""
get_response = None
def __init__(self, get_response=None):
self.get_response = get_response
def __call__(self, request):
if not self.get_response:
return exceptions.ImproperlyConfigured(
'Middleware called without proper initialization')
self.process_request(request)
return self.get_response(request)
def process_request(self, request):
auth_header = request.META.get('HTTP_AUTHORIZATION', b'')
auth_header = auth_header.partition(b' ')
if auth_header[0].lower() != b'token':
return None
# If they specified an invalid token, let them know.
if not auth_header[2]:
return http.HttpResponseBadRequest("Improperly formatted token")
user = auth.authenticate(token=auth_header[2])
if user:
request.user = user
|
Add chaining for clear method | import Ember from 'ember';
const {
$
} = Ember;
const log = [];
let isEnabled = false;
const addItem = (event, xhr, settings)=> Boolean(isEnabled) && log.push({ event, xhr, settings });
let getItemForSerializer = ()=> 'item';
let filterFunction = ()=> true;
const LoggerObject = {
clear: ()=> {
log.length = 0;
return LoggerObject;
},
getSerialized: ()=> JSON.stringify(log.filter(filterFunction).map(getItemForSerializer)),
setFilterFunction(func) {
if (typeof func === 'function') {
filterFunction = func;
}
return LoggerObject;
},
setGetItemForSerializer(func) {
if (typeof func === 'function') {
getItemForSerializer = func;
}
return LoggerObject;
},
register(name) {
window[name] = LoggerObject;
return LoggerObject;
},
subscribe() {
$(document).ajaxComplete(addItem);
return LoggerObject;
},
enableLogging() {
isEnabled = true;
return LoggerObject;
},
disableLogging() {
isEnabled = false;
return LoggerObject;
}
};
export function initLogger(options) {
LoggerObject
.setGetItemForSerializer(options.getItemForSerializer)
.setFilterFunction(options.filter)
.register(options.globalName)
.subscribe()
.enableLogging();
}
| import Ember from 'ember';
const {
$
} = Ember;
const log = [];
let isEnabled = false;
const addItem = (event, xhr, settings)=> Boolean(isEnabled) && log.push({ event, xhr, settings });
let getItemForSerializer = ()=> 'item';
let filterFunction = ()=> true;
const LoggerObject = {
clear: ()=> (log.length = 0),
getSerialized: ()=> JSON.stringify(log.filter(filterFunction).map(getItemForSerializer)),
setFilterFunction(func) {
if (typeof func === 'function') {
filterFunction = func;
}
return LoggerObject;
},
setGetItemForSerializer(func) {
if (typeof func === 'function') {
getItemForSerializer = func;
}
return LoggerObject;
},
register(name) {
window[name] = LoggerObject;
return LoggerObject;
},
subscribe() {
$(document).ajaxComplete(addItem);
return LoggerObject;
},
enableLogging() {
isEnabled = true;
return LoggerObject;
},
disableLogging() {
isEnabled = false;
return LoggerObject;
}
};
export function initLogger(options) {
LoggerObject
.setGetItemForSerializer(options.getItemForSerializer)
.setFilterFunction(options.filter)
.register(options.globalName)
.subscribe()
.enableLogging();
}
|
Update log format to parse logs with upstream and cache fields by default | package main
import (
"flag"
"log"
"net/http"
"github.com/jvrplmlmn/nginx-requests-stats/handlers"
"github.com/satyrius/gonx"
)
const version = "0.1.0"
var format string
var logFile string
func init() {
flag.StringVar(&format, "format", `$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $upstream_addr $upstream_cache_status`, "Log format")
flag.StringVar(&logFile, "log", "/var/log/nginx/access.log", "Log file name to read.")
}
func main() {
// Parse the command-line flags
flag.Parse()
// Always log when the application starts
log.Println("Starting 'nginx-requests-stats' app...")
// Create a parser based on a given format
parser := gonx.NewParser(format)
// This endpoint returns a JSON with the version of the application
http.Handle("/version", handlers.VersionHandler(version))
// This endpoint returns a JSON with the number of requests in the last 24h
http.Handle("/count", handlers.CountHandler(parser, logFile))
// Serve the endpoints
log.Fatal(http.ListenAndServe("localhost:8080", nil))
}
| package main
import (
"flag"
"log"
"net/http"
"github.com/jvrplmlmn/nginx-requests-stats/handlers"
"github.com/satyrius/gonx"
)
const version = "0.1.0"
var format string
var logFile string
func init() {
flag.StringVar(&format, "format", `$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"`, "Log format")
flag.StringVar(&logFile, "log", "/var/log/nginx/access.log", "Log file name to read.")
}
func main() {
// Parse the command-line flags
flag.Parse()
// Always log when the application starts
log.Println("Starting 'nginx-requests-stats' app...")
// Create a parser based on a given format
parser := gonx.NewParser(format)
// This endpoint returns a JSON with the version of the application
http.Handle("/version", handlers.VersionHandler(version))
// This endpoint returns a JSON with the number of requests in the last 24h
http.Handle("/count", handlers.CountHandler(parser, logFile))
// Serve the endpoints
log.Fatal(http.ListenAndServe("localhost:8080", nil))
}
|
Add onChange handle to call back when a field has been changed. | angular.module('materialscommons').component('mcEditableHeader', {
template: `
<div layout="column" layout-align="start stretch">
<span ng-if="!$ctrl.editField"
ng-click="$ctrl.editField = true"
ng-class="$ctrl.headerClasses"
style="cursor: pointer">
{{$ctrl.header}}
</span>
<input ng-if="$ctrl.editField"
type="text" class="mc-input-as-line"
on-enter="$ctrl.editField = false"
ng-model="$ctrl.header"
ng-model-options="{debounce: 250}"
ng-change="$ctrl.onChange && $ctrl.onChange()"
ng-class="$ctrl.inputClasses"
ng-mouseleave="$ctrl.editField = false">
</div>
`,
bindings: {
header: '=',
headerClasses: '@',
inputClasses: '@',
onChange: '&'
}
});
| angular.module('materialscommons').component('mcEditableHeader', {
template: `
<div layout="column" layout-align="start stretch">
<span ng-if="!$ctrl.editField"
ng-click="$ctrl.editField = true"
ng-class="$ctrl.headerClasses"
style="cursor: pointer">
{{$ctrl.header}}
</span>
<input ng-if="$ctrl.editField"
type="text" class="mc-input-as-line"
on-enter="$ctrl.editField = false"
ng-model="$ctrl.header"
ng-class="$ctrl.inputClasses"
ng-mouseleave="$ctrl.editField = false">
</div>
`,
bindings: {
header: '=',
headerClasses: '@',
inputClasses: '@'
}
});
|
Fix typo and convert TV season/ep to str | #!/usr/bin/python3
# scrapeOMDB.py - parses a movie and year from arguments and returns JSON
import json, requests
URL_BASE = 'http://www.omdbapi.com/?'
def OMDBmovie(mTitle, mYear):
# Craft the URL
url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json'
# Try to get the url
response = requests.get(url)
response.raise_for_status()
theJSON = json.loads(response.text)
return(theJSON)
def OMDBtv(tvTitle, tvSeason, tvEpisode):
# Craft the URL
url = URL_BASE + 't=' + tvTitle + '&Season=' + str(tvSeason) + '&Episode=' + str(tvEpisode) + '&plot=full&r=json'
# Try to get the url
response = requests.get(url)
response.raise_for_status()
theJSON = json.loads(response.text)
return(theJSON)
| #!/usr/bin/python3
# scrapeOMDB.py - parses a movie and year from arguments and returns JSON
import json, requests
URL_BASE = 'http://www.omdbapi.com/?'
def OMDBmovie(mTitle, mYear):
# Craft the URL
url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json'
# Try to get the url
response = requests.get(url)
response.raise_for_status()
theJSON = json.loads(response.text)
return(theJSON)
def OMDBtv(tvTitle, tvSeason, tvEpisode):
# Craft the URL
url = URL_BASE + 't=' + str(tvTitle) + '&Season=' + str(tvSeason) '&Episode=' + str(tvEpisode) + '&plot=full&r=json'
# Try to get the url
response = requests.get(url)
response.raise_for_status()
theJSON = json.loads(response.text)
return(theJSON)
|
Increase default maximum java heap size | """Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import logging
import jnius_config
logger = logging.getLogger('java_vm')
def _has_xmx(options):
for option in options:
if option.startswith('-Xmx'):
return True
return False
default_mem_limit = '8g'
if not _has_xmx(jnius_config.get_options()):
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx%s' % default_mem_limit)
else:
logger.warning("Couldn't set memory limit for Java VM because the VM "
"is already running.")
path_here = os.path.dirname(os.path.realpath(__file__))
cp = os.path.join(path_here, 'sources/biopax/jars/paxtools.jar')
cp_existing = os.environ.get('CLASSPATH')
if cp_existing is not None:
os.environ['CLASSPATH'] = cp + ':' + cp_existing
else:
os.environ['CLASSPATH'] = cp
from jnius import autoclass, JavaException, cast
| """Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import logging
import jnius_config
logger = logging.getLogger('java_vm')
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
logger.warning("Couldn't set memory limit for Java VM because the VM "
"is already running.")
path_here = os.path.dirname(os.path.realpath(__file__))
cp = os.path.join(path_here, 'sources/biopax/jars/paxtools.jar')
cp_existing = os.environ.get('CLASSPATH')
if cp_existing is not None:
os.environ['CLASSPATH'] = cp + ':' + cp_existing
else:
os.environ['CLASSPATH'] = cp
from jnius import autoclass, JavaException, cast
|
Add more details about what the class should do
And remove extra line.. | <?php
/**
* @title Import Class
* @desc Generic Importer Class to import data from other platforms (such as phpFox, SocialEngine, mooSocial, Skadate, DatingScript, DatingPro) to pH7CMS.
*
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / Install / Class
* @version 0.1
*/
namespace PH7;
defined('PH7') or exit('Restricted access');
abstract class Import
{
protected $db;
public function __construct()
{
$this->db = Db::getInstance();
}
}
| <?php
/**
* @title Import Class
* @desc Generic Importer Class for the pH7CMS.
*
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / Install / Class
* @version 0.1
*/
namespace PH7;
defined('PH7') or exit('Restricted access');
abstract class Import
{
protected $db;
public function __construct()
{
$this->db = Db::getInstance();
}
}
|
Make it work in IE10 | var HumanView = require('human-view');
var templates = require('../templates');
module.exports = HumanView.extend({
template: templates.pathway,
events: {
'dragstart .columns': 'drag',
'dragover .columns': 'over',
'dragenter .columns': 'enter',
'dragleave .columns': 'leave',
'drop .columns': 'drop'
},
render: function () {
this.renderAndBind({pathway: this.model});
this.model.once('move', this.render, this);
return this;
},
drag: function (e) {
var start = $(e.currentTarget).data('cell-coords');
e.originalEvent.dataTransfer.setData('Text', start);
},
over: function (e) {
e.originalEvent.dataTransfer.effectAllowed = 'move';
e.originalEvent.dataTransfer.dropEffect = 'move';
if (!$(e.currentTarget).find('.badge').length) {
e.preventDefault();
e.stopPropagation();
}
},
enter: function (e) {
if (!$(e.currentTarget).find('.badge').length) {
$(e.currentTarget).addClass('drop');
}
},
leave: function (e) {
$(e.currentTarget).removeClass('drop');
},
drop: function (e) {
var end = $(e.currentTarget).data('cell-coords');
var start = e.originalEvent.dataTransfer.getData('Text');
this.model.move(start, end);
e.preventDefault();
e.stopPropagation();
}
});
| var HumanView = require('human-view');
var templates = require('../templates');
module.exports = HumanView.extend({
template: templates.pathway,
events: {
'dragstart .columns': 'drag',
'dragover .columns': 'over',
'dragenter .columns': 'enter',
'dragleave .columns': 'leave',
'drop .columns': 'drop'
},
render: function () {
this.renderAndBind({pathway: this.model});
this.model.once('move', this.render, this);
return this;
},
drag: function (e) {
var start = $(e.currentTarget).data('cell-coords');
e.originalEvent.dataTransfer.setData('text/plain', start);
},
over: function (e) {
e.originalEvent.dataTransfer.effectAllowed = 'move';
e.originalEvent.dataTransfer.dropEffect = 'move';
if (!$(e.currentTarget).find('.badge').length) {
e.preventDefault();
return false;
}
},
enter: function (e) {
if (!$(e.currentTarget).find('.badge').length) {
$(e.currentTarget).addClass('drop');
}
},
leave: function (e) {
$(e.currentTarget).removeClass('drop');
},
drop: function (e) {
var end = $(e.currentTarget).data('cell-coords');
var start = e.originalEvent.dataTransfer.getData('text/plain');
this.model.move(start, end);
e.preventDefault();
}
});
|
Add right RNSentryPackage call in example project | package com.reactnativeexample;
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import java.util.Arrays;
import java.util.List;
import io.sentry.RNSentryPackage;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNSentryPackage(MainApplication.this)
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
| package com.reactnativeexample;
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import java.util.Arrays;
import java.util.List;
import io.sentry.RNSentryPackage;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
RNSentryPackage.useDeveloperSupport = this.getUseDeveloperSupport();
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNSentryPackage()
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
|
Use `String.prototype.startsWith` method instead of the regular expression | $(function () {
var setText = function (textarea, text) {
var range;
textarea.focus();
if (typeof textarea.selectionStart === 'number') {
textarea.value = text;
textarea.selectionStart = textarea.selectionEnd = 3;
return;
}
range = textarea.createTextRange();
range.text = text
range.select();
}
var startsWith = String.prototype.startsWith || function (str, position) {
position = position || 0;
return ('' + this).indexOf(str, position) === position;
};
var $textarea = $('textarea').textcomplete({
// emoji strategy
emoji: {
match: /(^|\s):([\-+\w]*)$/,
search: function (term, callback) {
callback($.map(emojies, function (emoji) {
return startsWith.call(emoji, term) ? emoji : null;
}));
},
template: function (value) {
return '<img src="media/images/emoji/' + value + '.png"></img>' + value;
},
replace: function (value) {
return '$1:' + value + ': ';
},
maxCount: 5
}
});
setText($textarea.get(0), ':a');
$textarea.keyup();
});
| $(function () {
var setText = function (textarea, text) {
var range;
textarea.focus();
if (typeof textarea.selectionStart === 'number') {
textarea.value = text;
textarea.selectionStart = textarea.selectionEnd = 3;
return;
}
range = textarea.createTextRange();
range.text = text
range.select();
}
var $textarea = $('textarea').textcomplete({
// emoji strategy
emoji: {
match: /(^|\s):([\-+\w]*)$/,
search: function (term, callback) {
var regexp = new RegExp('^' + term.replace(/\+/g, '\\+'));
callback($.map(emojies, function (emoji) {
return regexp.test(emoji) ? emoji : null;
}));
},
template: function (value) {
return '<img src="media/images/emoji/' + value + '.png"></img>' + value;
},
replace: function (value) {
return '$1:' + value + ': ';
},
maxCount: 5
}
});
setText($textarea.get(0), ':a');
$textarea.keyup();
});
|
Fix analytics template preflight check
Returning from _run_task didn't work, and using
```python
self.return_values = True
```
results in `return_values` being coerced to an empty dictionary that
evaluates as False. | import json
from cumulusci.tasks.salesforce import BaseSalesforceApiTask
class CheckPermSetLicenses(BaseSalesforceApiTask):
task_options = {
"permission_sets": {
"description": "List of permission set names to check for, (ex: EinsteinAnalyticsUser)",
"required": True,
}
}
def _run_task(self):
query = self._get_query()
result = self.tooling.query(query)
if result["size"] > 0:
self.return_values["has_einstein_perms"] = True
def _get_query(self):
where_targets = [f"'{name}'" for name in self.options["permission_sets"]]
return f"""
SELECT Name FROM PermissionSet WHERE Name IN ({','.join(where_targets)})
"""
| import json
from cumulusci.tasks.salesforce import BaseSalesforceApiTask
class CheckPermSetLicenses(BaseSalesforceApiTask):
task_options = {
"permission_sets": {
"description": "List of permission set names to check for, (ex: EinsteinAnalyticsUser)",
"required": True,
}
}
def _run_task(self):
query = self._get_query()
result = self.tooling.query(query)
return result["size"] > 0
def _get_query(self):
where_targets = [f"'{name}'" for name in self.options["permission_sets"]]
return f"""
SELECT Name FROM PermissionSet WHERE Name IN ({','.join(where_targets)})
"""
|
Add OCA as author of OCA addons
In order to get visibility on https://www.odoo.com/apps the OCA board has
decided to add the OCA as author of all the addons maintained as part of the
association. | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 ABF OSIELL (<http://osiell.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': "Audit Log",
'version': "1.0",
'author': "ABF OSIELL,Odoo Community Association (OCA)",
'website': "http://www.osiell.com",
'category': "Tools",
'depends': [
'base',
],
'data': [
'security/ir.model.access.csv',
'views/auditlog_view.xml',
],
'application': True,
'installable': True,
'pre_init_hook': 'pre_init_hook',
}
| # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 ABF OSIELL (<http://osiell.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': "Audit Log",
'version': "1.0",
'author': "ABF OSIELL",
'website': "http://www.osiell.com",
'category': "Tools",
'depends': [
'base',
],
'data': [
'security/ir.model.access.csv',
'views/auditlog_view.xml',
],
'application': True,
'installable': True,
'pre_init_hook': 'pre_init_hook',
}
|
Use version query string to cache bust instead of webpack hash | var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');
var version = require('../package.json').version;
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
module.exports = webpackMerge(commonConfig, {
devtool: 'source-map',
output: {
path: helpers.root('dist'),
publicPath: '/',
filename: `[name].js?${version}`,
chunkFilename: `[id].chunk.js?${version}`
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({ // https://github.com/angular/angular/issues/10618
mangle: {
keep_fnames: true
}
}),
new ExtractTextPlugin(`[name].css?${version}`),
new webpack.DefinePlugin({
'process.env': {
'ENV': JSON.stringify(ENV)
}
}),
new webpack.LoaderOptionsPlugin({
htmlLoader: {
minimize: false // workaround for ng2
}
})
]
});
| var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
module.exports = webpackMerge(commonConfig, {
devtool: 'source-map',
output: {
path: helpers.root('dist'),
publicPath: '/',
filename: '[name].[hash].js',
chunkFilename: '[id].[hash].chunk.js'
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({ // https://github.com/angular/angular/issues/10618
mangle: {
keep_fnames: true
}
}),
new ExtractTextPlugin('[name].[hash].css'),
new webpack.DefinePlugin({
'process.env': {
'ENV': JSON.stringify(ENV)
}
}),
new webpack.LoaderOptionsPlugin({
htmlLoader: {
minimize: false // workaround for ng2
}
})
]
});
|
Replace deprecated string view arguments to url | # -*- coding: utf-8 -*-
from django.conf.urls import url
from .views import stop_impersonate, list_users, search_users, impersonate
urlpatterns = [
url(r'^stop/$',
stop_impersonate,
name='impersonate-stop'),
url(r'^list/$',
list_users,
{'template': 'impersonate/list_users.html'},
name='impersonate-list'),
url(r'^search/$',
search_users,
{'template': 'impersonate/search_users.html'},
name='impersonate-search'),
url(r'^(?P<uid>.+)/$',
impersonate,
name='impersonate-start'),
]
| # -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
urlpatterns = patterns('impersonate.views',
url(r'^stop/$',
'stop_impersonate',
name='impersonate-stop'),
url(r'^list/$',
'list_users',
{'template': 'impersonate/list_users.html'},
name='impersonate-list'),
url(r'^search/$',
'search_users',
{'template': 'impersonate/search_users.html'},
name='impersonate-search'),
url(r'^(?P<uid>.+)/$',
'impersonate',
name='impersonate-start'),
)
|
Fix typo fetching config for node broker connection | var mqtt = require('mqtt'),
fs = require('fs'),
url = require('url'),
config = require('config');
module.exports.connect = function () {
var caCert,
mqttBroker = url.format( config.get('brokerNode') ),
instance;
if (config.get('brokerNode.caFile')) {
caCert = fs.readFileSync('./certs/' + config.get('brokerNode.caFile'));
}
console.log('Connecting to: ', mqttBroker);
instance = mqtt.connect(mqttBroker, { ca: caCert });
return instance;
}
/*
ciot/kit0/<device>/<action>/<type>
*/
module.exports.topicForParams = function topic(p) {
return [ 'ciot/kit0', p.device, p.action, p.type ].join('/')
}
| var mqtt = require('mqtt'),
fs = require('fs'),
url = require('url'),
config = require('config');
module.exports.connect = function () {
var caCert,
mqttBroker = url.format( config.get('brokerNode') ),
instance;
if (config.get('broker.caFile')) {
caCert = fs.readFileSync('./certs/' + config.get('broker.caFile'));
}
console.log('Connecting to: ', mqttBroker);
instance = mqtt.connect(mqttBroker, { ca: caCert });
return instance;
}
/*
ciot/kit0/<device>/<action>/<type>
*/
module.exports.topicForParams = function topic(p) {
return [ 'ciot/kit0', p.device, p.action, p.type ].join('/')
}
|
Create junction to an absolute path | // +build windows
package gps
import (
"os/exec"
"testing"
)
// setupUsingJunctions inflates fs onto the host file system, but uses Windows
// directory junctions for links.
func (fs filesystemState) setupUsingJunctions(t *testing.T) {
fs.setupDirs(t)
fs.setupFiles(t)
fs.setupJunctions(t)
}
func (fs filesystemState) setupJunctions(t *testing.T) {
for _, link := range fs.links {
from := link.path.prepend(fs.root)
to := fsPath{link.to}.prepend(fs.root)
// There is no way to make junctions in the standard library, so we'll just
// do what the stdlib's os tests do: run mklink.
//
// Also, all junctions must point to absolute paths.
output, err := exec.Command("cmd", "/c", "mklink", "/J", from.String(), to.String()).CombinedOutput()
if err != nil {
t.Fatalf("failed to run mklink %v %v: %v %q", from.String(), to.String(), err, output)
}
}
}
| // +build windows
package gps
import (
"os/exec"
"testing"
)
// setupUsingJunctions inflates fs onto the host file system, but uses Windows
// directory junctions for links.
func (fs filesystemState) setupUsingJunctions(t *testing.T) {
fs.setupDirs(t)
fs.setupFiles(t)
fs.setupJunctions(t)
}
func (fs filesystemState) setupJunctions(t *testing.T) {
for _, link := range fs.links {
p := link.path.prepend(fs.root)
// There is no way to make junctions in the standard library, so we'll just
// do what the stdlib's os tests do: run mklink.
output, err := exec.Command("cmd", "/c", "mklink", "/J", p.String(), link.to).CombinedOutput()
if err != nil {
t.Fatalf("failed to run mklink %v %v: %v %q", p.String(), link.to, err, output)
}
}
}
|
Check if a paragraph exists in post before getting excerpt. | "use strict";
var _ = require("underscore"),
cheerio = require("cheerio"),
check = require("check-types"),
multimatch = require("multimatch");
function plugin(options) {
options = normalize(options);
return function (files, metalsmith, done) {
var filesTbSanitized = multimatch(Object.keys(files), options.src);
_.each(filesTbSanitized, function(fileName) {
var data = files[fileName];
if (check.string(data.excerpt)) { return; }
var $ = cheerio.load(data.contents.toString());
var firstElement = $("p").first();
var html = firstElement.html();
if (html !== null) {
data.excerpt = html.trim();
} else {
data.excerpt = "";
}
});
done();
};
}
function normalize(options) {
var defaults = {
src: ["**/*.html"]
};
options = _.extend({}, defaults, options);
return options;
}
module.exports = plugin;
| "use strict";
var _ = require("underscore"),
cheerio = require("cheerio"),
check = require("check-types"),
multimatch = require("multimatch");
function plugin(options) {
options = normalize(options);
return function (files, metalsmith, done) {
var filesTbSanitized = multimatch(Object.keys(files), options.src);
_.each(filesTbSanitized, function(fileName) {
var data = files[fileName];
if (check.string(data.excerpt)) { return; }
var $ = cheerio.load(data.contents.toString());
var firstElement = $("p").first();
data.excerpt = firstElement.html().trim();
});
done();
};
}
function normalize(options) {
var defaults = {
src: ["**/*.html"]
};
options = _.extend({}, defaults, options);
return options;
}
module.exports = plugin;
|
Remove debug output and pycodestyle | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
def countTriplets(arr, r):
potential_triplets_with_middle = Counter()
potential_triplets_with_end = Counter()
total_triplets = 0
for num in arr:
# num completed potential_triplets_with_end[num] triplets
if potential_triplets_with_end[num]:
total_triplets += potential_triplets_with_end[num]
# num can be the middle number in
# potential_triplets_with_middle[num] triplets
if potential_triplets_with_middle[num]:
potential_triplets_with_end[num * r] += \
potential_triplets_with_middle[num]
# num can be the begining of a triplet
potential_triplets_with_middle[num * r] += 1
return total_triplets
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nr = input().rstrip().split()
n = int(nr[0])
r = int(nr[1])
arr = list(map(int, input().rstrip().split()))
ans = countTriplets(arr, r)
fptr.write(str(ans) + '\n')
fptr.close()
| #!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
def countTriplets(arr, r):
potential_triplets_with_middle = Counter()
potential_triplets_with_end = Counter()
total_triplets = 0
for num in arr:
# num completed potential_triplets_with_end[num] triplets
if potential_triplets_with_end[num]:
total_triplets += potential_triplets_with_end[num]
# num can be the middle number in potential_triplets_with_middle[num] triplets
if potential_triplets_with_middle[num]:
potential_triplets_with_end[num * r] += potential_triplets_with_middle[num]
# num can be the begining of a triplet
potential_triplets_with_middle[num * r] += 1
print("num", num, " middle", potential_triplets_with_middle, " end", potential_triplets_with_end, " total", total_triplets)
return total_triplets
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nr = input().rstrip().split()
n = int(nr[0])
r = int(nr[1])
arr = list(map(int, input().rstrip().split()))
ans = countTriplets(arr, r)
fptr.write(str(ans) + '\n')
fptr.close()
|
Fix noqa comments for new version of flake8 | from seed_stage_based_messaging.settings import * # noqa: F403
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'TESTSEKRET'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
CELERY_TASK_EAGER_PROPAGATES = True
CELERY_TASK_ALWAYS_EAGER = True
SCHEDULER_URL = "http://seed-scheduler/api/v1"
SCHEDULER_API_TOKEN = "REPLACEME"
IDENTITY_STORE_URL = "http://seed-identity-store/api/v1"
IDENTITY_STORE_TOKEN = "REPLACEME"
MESSAGE_SENDER_URL = "http://seed-message-sender/api/v1"
MESSAGE_SENDER_TOKEN = "REPLACEME"
METRICS_URL = "http://metrics-url"
METRICS_AUTH_TOKEN = "REPLACEME"
PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',)
# REST Framework conf defaults
REST_FRAMEWORK['PAGE_SIZE'] = 2 # noqa: F405
AUDIO_FTP_HOST = 'localhost'
AUDIO_FTP_PORT = '2222'
AUDIO_FTP_USER = 'test'
AUDIO_FTP_PASS = 'secret'
AUDIO_FTP_ROOT = 'test_directory'
| from seed_stage_based_messaging.settings import * # flake8: noqa
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'TESTSEKRET'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
CELERY_TASK_EAGER_PROPAGATES = True
CELERY_TASK_ALWAYS_EAGER = True
SCHEDULER_URL = "http://seed-scheduler/api/v1"
SCHEDULER_API_TOKEN = "REPLACEME"
IDENTITY_STORE_URL = "http://seed-identity-store/api/v1"
IDENTITY_STORE_TOKEN = "REPLACEME"
MESSAGE_SENDER_URL = "http://seed-message-sender/api/v1"
MESSAGE_SENDER_TOKEN = "REPLACEME"
METRICS_URL = "http://metrics-url"
METRICS_AUTH_TOKEN = "REPLACEME"
PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',)
# REST Framework conf defaults
REST_FRAMEWORK['PAGE_SIZE'] = 2
AUDIO_FTP_HOST = 'localhost'
AUDIO_FTP_PORT = '2222'
AUDIO_FTP_USER = 'test'
AUDIO_FTP_PASS = 'secret'
AUDIO_FTP_ROOT = 'test_directory'
|
Use new Function() rather than call() to improve performance even further. | var ArgumentError = require('./ArgumentError');
var topiarist = require('topiarist');
function verifierMethod() {
if(!this.skipVerification) {
if(this.argValue === undefined) throw new this.ArgumentError(this.argName + ' argument must be provided.');
this.METHOD_NAME(arg);
}
if(this.argsVerifier.argIndex < this.argsVerifier.arguments.length) {
this.argsVerifier.constructor.pendingVerifier = this.argsVerifier;
}
return this.argsVerifier;
}
var verifierMethodStr = verifierMethod.toString().substring(verifierMethod.toString().indexOf('{') + 1, verifierMethod.toString().lastIndexOf('}'));
function ArgVerifier(argsVerifier, argName, argValue) {
this.argsVerifier = argsVerifier;
this.argName = argName;
this.argValue = argValue;
}
ArgVerifier.addVerifier = function(verifier) {
for(var methodName in verifier) {
ArgVerifier.prototype['_' + methodName] = verifier[methodName];
ArgVerifier.prototype[methodName] = new Function('arg', verifierMethodStr.replace('METHOD_NAME', '_' + methodName));
}
};
Object.defineProperty(ArgVerifier.prototype, 'optionally', {
get: function optionally() {
if((this.argValue === undefined) || (this.argValue === null)) {
this.skipVerification = true;
}
return this;
}
});
ArgVerifier.prototype.ArgumentError = ArgumentError;
module.exports = ArgVerifier;
| var ArgumentError = require('./ArgumentError');
var topiarist = require('topiarist');
function verifierMethod(verifierMethod) {
return function(arg) {
if(!this.skipVerification) {
if(this.argValue === undefined) throw new ArgumentError(this.argName + ' argument must be provided.');
verifierMethod.call(this, arg);
}
if(this.argsVerifier.argIndex < this.argsVerifier.arguments.length) {
this.argsVerifier.constructor.pendingVerifier = this.argsVerifier;
}
return this.argsVerifier;
};
}
function ArgVerifier(argsVerifier, argName, argValue) {
this.argsVerifier = argsVerifier;
this.argName = argName;
this.argValue = argValue;
}
ArgVerifier.addVerifier = function(verifier) {
for(var methodName in verifier) {
ArgVerifier.prototype[methodName] = verifierMethod(verifier[methodName]);
}
};
Object.defineProperty(ArgVerifier.prototype, 'optionally', {
get: function optionally() {
if((this.argValue === undefined) || (this.argValue === null)) {
this.skipVerification = true;
}
return this;
}
});
module.exports = ArgVerifier;
|
Fix example for React 0.13 | var React = require('react');
var Gravatar = React.createFactory(require('../dist/index.js'));
React.render(
React.DOM.div(null,
[
React.DOM.h2(null, "<Gravatar email='mathews.kyle@gmail.com' />"),
Gravatar({email: 'mathews.kyle@gmail.com'}),
React.DOM.h2(null, "<Gravatar email='mathews.kyle@gmail.com' size=100 />"),
Gravatar({email: 'mathews.kyle@gmail.com', size: 100}),
React.DOM.h2(null, "For emails without a gravatar, use the retro default. You can override this by passing in a different 'default' prop. See https://en.gravatar.com/site/implement/images/ for options."),
Gravatar({email: 'blah@blah.com'}),
]), document.body);
| var Gravatar = require('../dist/index.js');
var React = require('react');
React.renderComponent(
React.DOM.div(null,
[
React.DOM.h2(null, "<Gravatar email='mathews.kyle@gmail.com' />"),
Gravatar({email: 'mathews.kyle@gmail.com'}),
React.DOM.h2(null, "<Gravatar email='mathews.kyle@gmail.com' size=100 />"),
Gravatar({email: 'mathews.kyle@gmail.com', size: 100}),
React.DOM.h2(null, "For emails without a gravatar, use the retro default. You can override this by passing in a different 'default' prop. See https://en.gravatar.com/site/implement/images/ for options."),
Gravatar({email: 'blah@blah.com'}),
]), document.body);
|
Fix error reporting in copy script | 'use strict'
const fs = require('fs')
const path = require('path')
const src = path.join(__dirname, '..', '.waiting.html')
const dir = path.join(__dirname, '..', 'coverage')
const dst = path.join(dir, 'index.html')
fs.stat(dst, (er, st) => {
if (er) {
if (er.code !== 'ENOENT') {
console.error(`Error on ${dst}: ${er.message}`)
process.exit(1)
}
} else {
if (!st.isFile()) {
console.error(`Error on ${dst}: not a file`)
process.exit(1)
}
if (st.size > 0) {
process.exit(0)
}
}
// Either the file didn't exist, or it got truncated
fs.mkdir(dir, (er) => {
if (er && (er.code !== 'EEXIST')) {
console.error(`Error creating ${dir}: ${er.message}`)
process.exit(1)
}
fs.copyFile(src, dst, (er) => {
if (er) {
console.error(`Error: ${er.message}`)
process.exit(1)
}
})
})
})
| 'use strict'
const fs = require('fs')
const path = require('path')
const src = path.join(__dirname, '..', '.waiting.html')
const dir = path.join(__dirname, '..', 'coverage')
const dst = path.join(dir, 'index.html')
fs.stat(dst, (er, st) => {
if (er) {
if (er.code !== 'ENOENT') {
console.error(`Error on ${dst}: ${er.message}`)
process.exit(1)
}
} else {
if (!st.isFile()) {
console.error(`Error on ${dst}: ${er.message}`)
process.exit(1)
}
if (st.size > 0) {
process.exit(0)
}
}
// Either the file didn't exist, or it got truncated
fs.mkdir(dir, (er) => {
if (er && (er.code !== 'EEXIST')) {
console.error(`Error creating ${dir}: ${er.message}`)
process.exit(1)
}
fs.copyFile(src, dst, (er) => {
if (er) {
console.error(`Error: ${er.message}`)
process.exit(1)
}
})
})
})
|
Add privacy parameter to User.find_videos | from datetime import datetime
import time
import json
from videolog.core import Videolog
class User(Videolog):
def find_videos(self, user, privacy=None):
path = '/usuario/%s/videos.json' % user
if privacy is not None:
path = "%s?privacidade=%s" % (path, privacy)
content = self._make_request('GET', path)
usuario = json.loads(content)
response = []
for video in usuario['usuario']['videos']:
video['criacao'] = datetime.strptime(video['criacao'], "%Y-%m-%dT%H:%M:%S")
video["duracao"] = time.strptime("00:00:05", "%H:%M:%S")
if video['mobile'].lower() == "s":
video['mobile'] = True
else:
video['mobile'] = False
response.append(video)
return response | from datetime import datetime
import time
import json
from videolog.core import Videolog
class User(Videolog):
def find_videos(self, user):
content = self._make_request('GET', '/usuario/%s/videos.json' % user)
usuario = json.loads(content)
response = []
for video in usuario['usuario']['videos']:
video['criacao'] = datetime.strptime(video['criacao'], "%Y-%m-%dT%H:%M:%S")
video["duracao"] = time.strptime("00:00:05", "%H:%M:%S")
if video['mobile'].lower() == "s":
video['mobile'] = True
else:
video['mobile'] = False
response.append(video)
return response |
Add prop classnames to the component | import classNames from 'classnames/dedupe';
import React from 'react';
import TabButtonList from './TabButtonList';
class Tabs extends React.Component {
getChildren() {
const {props} = this;
return React.Children.map(props.children, (tabElement) => {
const newTabProps = {activeTab: props.activeTab};
if (tabElement.type === TabButtonList) {
newTabProps.onChange = props.handleTabChange;
newTabProps.vertical = props.vertical;
}
return React.cloneElement(tabElement, newTabProps);
});
}
render() {
let classes = classNames('menu-tabbed-container', this.props.className, {
'menu-tabbed-container-vertical': this.props.vertical
});
return (
<div className={classes}>
{this.getChildren()}
</div>
);
}
}
Tabs.propTypes = {
// Optional variable to set active tab from owner component
activeTab: React.PropTypes.string,
children: React.PropTypes.node.isRequired,
className: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.object,
React.PropTypes.string
]),
handleTabChange: React.PropTypes.func.isRequired,
vertical: React.PropTypes.bool
};
module.exports = Tabs;
| import classNames from 'classnames/dedupe';
import React from 'react';
import TabButtonList from './TabButtonList';
class Tabs extends React.Component {
getChildren() {
const {props} = this;
return React.Children.map(props.children, (tabElement) => {
const newTabProps = {activeTab: props.activeTab};
if (tabElement.type === TabButtonList) {
newTabProps.onChange = props.handleTabChange;
newTabProps.vertical = props.vertical;
}
return React.cloneElement(tabElement, newTabProps);
});
}
render() {
let classes = classNames('menu-tabbed-container', {
'menu-tabbed-container-vertical': this.props.vertical
});
return (
<div className={classes}>
{this.getChildren()}
</div>
);
}
}
Tabs.propTypes = {
// Optional variable to set active tab from owner component
activeTab: React.PropTypes.string,
children: React.PropTypes.node.isRequired,
className: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.object,
React.PropTypes.string
]),
handleTabChange: React.PropTypes.func.isRequired,
vertical: React.PropTypes.bool
};
module.exports = Tabs;
|
Move Feedback button closer to the left | var intervalTracker = {};
var customizeGitShoes = function(){
if (jQuery("#feedback-container")[0]) {
// Move gitShoes to the left side
jQuery("#feedback-container").css('right', 'none').css('left','5px')
jQuery("#gitshoes-button").css('float', 'left');
// Customize gitShoes text
jQuery("label[for=issue_body").text("Problems with the site? Suggestions? Comments? Let us know!");
jQuery("#feedback-submit").attr('value', 'Submit!');
// Make link to gitShoes website open in a new window
jQuery("#feedback-container a").attr('target', '_blank');
// Let users see it now!
jQuery("#feedback-container").css('display', 'block');
// Don't repeat!
clearInterval(intervalTracker.intervalID);
}
};
jQuery(document).ready(function(){
jQuery("#main-wrapper").click(function(){
jQuery("#gitshoes-form").slideUp();
})
intervalTracker.intervalID = setInterval('customizeGitShoes()', 500);
}); | var intervalTracker = {};
var customizeGitShoes = function(){
if (jQuery("#feedback-container")[0]) {
// Move gitShoes to the left side
jQuery("#feedback-container").css('right', 'none').css('left','30px');
jQuery("#gitshoes-button").css('float', 'left');
// Customize gitShoes text
jQuery("label[for=issue_body").text("Problems with the site? Suggestions? Comments? Let us know!");
jQuery("#feedback-submit").attr('value', 'Submit!');
// Make link to gitShoes website open in a new window
jQuery("#feedback-container a").attr('target', '_blank');
// Let users see it now!
jQuery("#feedback-container").css('display', 'block');
// Don't repeat!
clearInterval(intervalTracker.intervalID);
}
};
jQuery(document).ready(function(){
jQuery("#main-wrapper").click(function(){
jQuery("#gitshoes-form").slideUp();
})
intervalTracker.intervalID = setInterval('customizeGitShoes()', 500);
}); |
Improve safe mode notification using the new Orchestra\Messages::extend() API
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Event;
use Orchestra\Support\Messages;
use Orchestra\Foundation\Services\UserMetaRepository;
App::make('orchestra.memory')->extend('user', function ($app, $name)
{
return new UserMetaRepository($app, $name);
});
/*
|--------------------------------------------------------------------------
| Bind Installation Interface
|--------------------------------------------------------------------------
|
| These interface allow Orchestra Platform installation process to be
| customized by the application when there a requirement for it.
|
*/
App::bind('Orchestra\Foundation\Installation\InstallerInterface', function ()
{
return new Orchestra\Foundation\Installation\Installer(App::make('app'));
});
App::bind('Orchestra\Foundation\Installation\RequirementInterface', function ()
{
return new Orchestra\Foundation\Installation\Requirement(App::make('app'));
});
/*
|--------------------------------------------------------------------------
| Inject Safe Mode Notification
|--------------------------------------------------------------------------
|
| This event listener would allow Orchestra Platform to display notification
| if the application is running on safe mode.
|
*/
Event::listen('composing: *', function ()
{
if ('on' === App::make('session')->get('orchestra.safemode'))
{
App::make('orchestra.messages')->extend(function ($messages)
{
$messages->add('info', trans('orchestra/foundation::response.safe-mode'));
});
}
});
| <?php
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Event;
use Orchestra\Support\Messages;
use Orchestra\Foundation\Services\UserMetaRepository;
App::make('orchestra.memory')->extend('user', function ($app, $name)
{
return new UserMetaRepository($app, $name);
});
/*
|--------------------------------------------------------------------------
| Bind Installation Interface
|--------------------------------------------------------------------------
|
| These interface allow Orchestra Platform installation process to be
| customized by the application when there a requirement for it.
|
*/
App::bind('Orchestra\Foundation\Installation\InstallerInterface', function ()
{
return new Orchestra\Foundation\Installation\Installer(App::make('app'));
});
App::bind('Orchestra\Foundation\Installation\RequirementInterface', function ()
{
return new Orchestra\Foundation\Installation\Requirement(App::make('app'));
});
/*
|--------------------------------------------------------------------------
| Inject Safe Mode Notification
|--------------------------------------------------------------------------
|
| This event listener would allow Orchestra Platform to display notification
| if the application is running on safe mode.
|
*/
Event::listen('composing: *', function ()
{
if ('on' === App::make('session')->get('orchestra.safemode'))
{
$messages = App::make('orchestra.messages')->retrieve();
($messages instanceof Messages) or $messages = new Messages;
$messages->add('info', trans('orchestra/foundation::response.safe-mode'));
$messages->save();
}
});
|
Update of rules, cosmetic changes ,added ranking | @extends('main')
@section('head')
<style>
.container {
text-align: center;
}
</style>
@endsection
@section('content')
@include('hs.nav')
@include('messages')
<div class="container">
<img src="http://upload.wikimedia.org/wikipedia/en/1/1c/Hearthstone_Logo.png">
<p>RANKING</p>
<iframe width="100%" height="700px" src="https://docs.google.com/spreadsheets/d/1tDrspJY6s_0eCeLfocPVH77MgqDei8XKdKcH-SQ8tsE/pubhtml?gid=719055177&single=true&widget=true&headers=false"></iframe>
<hr>
@include('hs.footer')
</div>
@endsection | @extends('main')
@section('head')
<style>
.container {
text-align: center;
}
</style>
@endsection
@section('content')
@include('hs.nav')
@include('messages')
<div class="container">
<img src="http://upload.wikimedia.org/wikipedia/en/1/1c/Hearthstone_Logo.png">
<p>RANKING</p>
<iframe src="https://docs.google.com/spreadsheets/d/1tDrspJY6s_0eCeLfocPVH77MgqDei8XKdKcH-SQ8tsE/pubhtml?gid=719055177&single=true&widget=true&headers=false"></iframe>
<hr>
@include('hs.footer')
</div>
@endsection |
CHANGE install docs on homepage to new package name | import React from 'react';
import { Link } from 'react-router';
import './style.css';
const MainLinks = () => (
<div id="main-links" className="row">
<div className="col-md-12">
<div className="row">
<div className="main-links-container">
<div className="col-xs-6 try-now">
<h2>Try Now</h2>
<pre>
<code>
npm i -g @storybook/cli<br />
cd my-react-app<br />
getstorybook<br />
</code>
</pre>
</div>
<div className="col-xs-6 read-docs">
<h2>Read Docs</h2>
<center>
<Link to="/docs/react-storybook/basics/introduction/">
<div className="docs-img" />
</Link>
</center>
</div>
</div>
</div>
</div>
</div>
);
export default MainLinks;
| import React from 'react';
import { Link } from 'react-router';
import './style.css';
const MainLinks = () => (
<div id="main-links" className="row">
<div className="col-md-12">
<div className="row">
<div className="main-links-container">
<div className="col-xs-6 try-now">
<h2>Try Now</h2>
<pre>
<code>
npm i -g getstorybook<br />
cd my-react-app<br />
getstorybook<br />
</code>
</pre>
</div>
<div className="col-xs-6 read-docs">
<h2>Read Docs</h2>
<center>
<Link to="/docs/react-storybook/basics/introduction/">
<div className="docs-img" />
</Link>
</center>
</div>
</div>
</div>
</div>
</div>
);
export default MainLinks;
|
Use the Dough README on docs landing page | var gulp = require('gulp'),
jsdoc = require('gulp-jsdoc'),
ghPages = require('gulp-gh-pages'),
docsSrcDir = './assets/js/**/*.js',
docsDestDir = './docs/js',
jsDocTask;
jsDocTask = function() {
return gulp.src([docsSrcDir, './README.md'])
.pipe(
jsdoc(docsDestDir,
{
path: './node_modules/jaguarjs-jsdoc',
applicationName: 'Dough JavaScript',
cleverLinks: true,
copyright: 'Copyright Money Advice Service ©',
linenums: true,
collapseSymbols: false
},
{
plugins: ['plugins/markdown'],
}
)
);
};
gulp.task('deploy', function() {
return gulp.src(docsDestDir + '/**/*')
.pipe(ghPages());
});
gulp.task('default', ['jsdoc']);
gulp.task('build', ['jsdoc', 'deploy']);
gulp.task('jsdoc', jsDocTask);
gulp.task('watch', function() {
jsDocTask();
gulp.watch(docsSrcDir, ['jsdoc']);
});
| var gulp = require('gulp'),
jsdoc = require('gulp-jsdoc'),
ghPages = require('gulp-gh-pages'),
docsSrcDir = './assets/js/**/*.js',
docsDestDir = './docs/js',
jsDocTask;
jsDocTask = function() {
return gulp.src(docsSrcDir)
.pipe(
jsdoc(docsDestDir,
{
path: './node_modules/jaguarjs-jsdoc',
applicationName: 'Dough JavaScript',
cleverLinks: true,
copyright: 'Copyright Money Advice Service ©',
linenums: true,
collapseSymbols: false
},
{
plugins: ['plugins/markdown'],
}
)
);
};
gulp.task('deploy', function() {
return gulp.src(docsDestDir + '/**/*')
.pipe(ghPages());
});
gulp.task('default', ['jsdoc']);
gulp.task('build', ['jsdoc', 'deploy']);
gulp.task('jsdoc', jsDocTask);
gulp.task('watch', function() {
jsDocTask();
gulp.watch(docsSrcDir, ['jsdoc']);
});
|
Switch to a new integration URL
Closes #8 | <?php
/**
* RoboKassa driver for Omnipay PHP payment library.
*
* @link https://github.com/hiqdev/omnipay-robokassa
* @package omnipay-robokassa
* @license MIT
* @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
*/
namespace Omnipay\RoboKassa\Message;
use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RedirectResponseInterface;
/**
* RoboKassa Purchase Response.
*/
class PurchaseResponse extends AbstractResponse implements RedirectResponseInterface
{
protected $_redirect = 'https://auth.robokassa.ru/Merchant/Index.aspx';
public function isSuccessful()
{
return false;
}
public function isRedirect()
{
return true;
}
public function getRedirectUrl()
{
return $this->_redirect;
}
public function getRedirectMethod()
{
return 'POST';
}
public function getRedirectData()
{
return $this->data;
}
}
| <?php
/**
* RoboKassa driver for Omnipay PHP payment library.
*
* @link https://github.com/hiqdev/omnipay-robokassa
* @package omnipay-robokassa
* @license MIT
* @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
*/
namespace Omnipay\RoboKassa\Message;
use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RedirectResponseInterface;
/**
* RoboKassa Purchase Response.
*/
class PurchaseResponse extends AbstractResponse implements RedirectResponseInterface
{
protected $_redirect = 'https://merchant.roboxchange.com/Index.aspx';
public function isSuccessful()
{
return false;
}
public function isRedirect()
{
return true;
}
public function getRedirectUrl()
{
return $this->_redirect;
}
public function getRedirectMethod()
{
return 'POST';
}
public function getRedirectData()
{
return $this->data;
}
}
|
Fix version number and remove obsolete importexport service which is now part of the main aws-sdk-php | <?php
namespace MvbCoding\Silex;
use Aws\ImportExport\ImportExportClient;
use Aws\SimpleDb\SimpleDbClient;
use Silex\Application;
use Silex\ServiceProviderInterface;
/**
* AWS SDK for PHP service provider for Silex applications
*/
class AwsV3BridgeServiceProvider implements ServiceProviderInterface
{
const VERSION = '2.0.1';
public function register(Application $app)
{
$app['aws.simpledb'] = $app->share(function (Application $app) {
$config = isset($app['aws.config']) ? $app['aws.config'] : [];
return new SimpleDbClient($config + ['ua_append' => [
'Silex/' . Application::VERSION,
'SXMOD/' . self::VERSION,
]]);
});
}
public function boot(Application $app)
{
}
}
| <?php
namespace MvbCoding\Silex;
use Aws\ImportExport\ImportExportClient;
use Aws\SimpleDb\SimpleDbClient;
use Silex\Application;
use Silex\ServiceProviderInterface;
/**
* AWS SDK for PHP service provider for Silex applications
*/
class AwsV3BridgeServiceProvider implements ServiceProviderInterface
{
const VERSION = '1.0.0';
public function register(Application $app)
{
$app['aws.simpledb'] = $app->share(function (Application $app) {
$config = isset($app['aws.config']) ? $app['aws.config'] : [];
return new SimpleDbClient($config + ['ua_append' => [
'Silex/' . Application::VERSION,
'SXMOD/' . self::VERSION,
]]);
});
$app['aws.importexport'] = $app->share(function (Application $app) {
$config = isset($app['aws.config']) ? $app['aws.config'] : [];
return new ImportExportClient($config + ['ua_append' => [
'Silex/' . Application::VERSION,
'SXMOD/' . self::VERSION,
]]);
});
}
public function boot(Application $app)
{
}
}
|
Remove option to filter Offline on the actual files | # -*- encoding: utf-8 -*-
from django.shortcuts import render
# API v1
from rest_framework import mixins, viewsets
from rest_framework.permissions import AllowAny
from apps.offline.models import Issue
from apps.offline.serializers import OfflineIssueSerializer
def main(request):
issues = Issue.objects.all()
years = set()
for issue in issues:
years.add(issue.release_date.year)
years = list(reversed(sorted(years)))
ctx = {
"issues": issues,
"years": years,
}
return render(request, "offline/offline.html", ctx)
class OfflineIssueViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin):
queryset = Issue.objects.all()
serializer_class = OfflineIssueSerializer
permission_classes = (AllowAny,)
filter_fields = ('id', 'release_date', 'title')
| # -*- encoding: utf-8 -*-
from django.shortcuts import render
# API v1
from rest_framework import mixins, viewsets
from rest_framework.permissions import AllowAny
from apps.offline.models import Issue
from apps.offline.serializers import OfflineIssueSerializer
def main(request):
issues = Issue.objects.all()
years = set()
for issue in issues:
years.add(issue.release_date.year)
years = list(reversed(sorted(years)))
ctx = {
"issues": issues,
"years": years,
}
return render(request, "offline/offline.html", ctx)
class OfflineIssueViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin):
queryset = Issue.objects.all()
serializer_class = OfflineIssueSerializer
permission_classes = (AllowAny,)
filter_fields = ('id', 'issue', 'release_date', 'title')
|
Use 1M transaction cost model instead of 10,000 | package org.ligoj.app.plugin.prov.model;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import lombok.Getter;
import lombok.Setter;
/**
* Storage price for a storage type.<br>
* The meaning to the cost attribute is the monthly cost of 1GiB (1024 MiB).
*/
@Getter
@Setter
@Entity
@Table(name = "LIGOJ_PROV_STORAGE_PRICE", uniqueConstraints = @UniqueConstraint(columnNames = { "type", "location" }))
public class ProvStoragePrice extends AbstractPrice<ProvStorageType> {
/**
* The monthly cost of 1GiB (Gibibyte Bytes).
* @see https://en.wikipedia.org/wiki/Gibibyte
*/
private double costGb = 0;
/**
* The cost per million transactions. May be <code>0</code>.
*/
private double costTransaction;
}
| package org.ligoj.app.plugin.prov.model;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import lombok.Getter;
import lombok.Setter;
/**
* Storage price for a storage type.<br>
* The meaning to the cost attribute is the monthly cost of 1GiB (1024 MiB).
*/
@Getter
@Setter
@Entity
@Table(name = "LIGOJ_PROV_STORAGE_PRICE", uniqueConstraints = @UniqueConstraint(columnNames = { "type", "location" }))
public class ProvStoragePrice extends AbstractPrice<ProvStorageType> {
/**
* The monthly cost of 1GiB (Gibibyte Bytes).
* @see https://en.wikipedia.org/wiki/Gibibyte
*/
private double costGb = 0;
/**
* The cost per transaction. May be <code>0</code>.
*/
private double costTransaction;
}
|
Use specified images for snapshot fixture | import pytest
from cosmo_tester.framework.test_hosts import Hosts, get_image
from cosmo_tester.test_suites.snapshots import get_multi_tenant_versions_list
@pytest.fixture(scope='function', params=get_multi_tenant_versions_list())
def hosts(request, ssh_key, module_tmpdir, test_config, logger):
hosts = Hosts(
ssh_key, module_tmpdir,
test_config, logger, request,
number_of_instances=3,
)
hosts.instances[0] = get_image(request.param, test_config)
hosts.instances[1] = get_image('master', test_config)
hosts.instances[2] = get_image('centos', test_config)
vm = hosts.instances[2]
vm.image_name = test_config.platform['centos_7_image']
vm.username = test_config['test_os_usernames']['centos_7']
hosts.create()
try:
yield hosts
finally:
hosts.destroy()
| import pytest
from cosmo_tester.framework.test_hosts import Hosts
from cosmo_tester.test_suites.snapshots import get_multi_tenant_versions_list
@pytest.fixture(scope='function', params=get_multi_tenant_versions_list())
def hosts(request, ssh_key, module_tmpdir, test_config, logger):
hosts = Hosts(
ssh_key, module_tmpdir,
test_config, logger, request,
number_of_instances=3,
)
hosts.instances[0].image_type = request.param
vm = hosts.instances[2]
vm.image_name = test_config.platform['centos_7_image']
vm.username = test_config['test_os_usernames']['centos_7']
hosts.create()
try:
yield hosts
finally:
hosts.destroy()
|
Remove logo from viewSource button | const sheet = document.createElement('style');
sheet.innerHTML = `
@media screen {
#viewSourceHeader.π-view-source-header {
display: block !important;
}
}
.π-view-source-header {
display: none;
top: 0;
left: 0;
right: unset;
bottom: unset;
padding: 1em;
background: transparent;
box-shadow: none;
}
`;
const segments = window.location.pathname.split('/');
let id = segments.pop();
if (id === '') id = segments.pop();
const buttons = document.createElement('div');
buttons.classList.add('π-view-source-header');
buttons.classList.add('π-controls');
buttons.id = 'viewSourceHeader';
buttons.innerHTML = `
<a class="π-btn" href="https://github.com/evnbr/bindery/tree/master/docs/examples/${id}">View Source β</a>
`;
document.head.appendChild(sheet);
document.body.appendChild(buttons);
| const sheet = document.createElement('style');
sheet.innerHTML = `
@media screen {
#viewSourceHeader.π-view-source-header {
display: block !important;
}
}
.π-view-source-header {
display: none;
top: 0;
left: 0;
right: unset;
bottom: unset;
padding: 1em;
background: transparent;
box-shadow: none;
}
.π-logo {
width: 32px;
height: 32px;
background: url(http://evanbrooks.info/bindery/assets/logo.svg) no-repeat;
background-size: contain;
vertical-align: middle;
margin-right: 0.8rem;
display: inline-block;
}
`;
const segments = window.location.pathname.split('/');
let id = segments.pop();
if (id === '') id = segments.pop();
const buttons = document.createElement('div');
buttons.classList.add('π-view-source-header');
buttons.classList.add('π-controls');
buttons.id = 'viewSourceHeader';
buttons.innerHTML = `
<a href="/bindery/"><div class="π-logo"></div></a>
<a class="π-btn" href="https://github.com/evnbr/bindery/tree/master/docs/examples/${id}">View Source β</a>
`;
document.body.appendChild(buttons);
document.head.appendChild(sheet);
|
Fix default option value of styles | 'use strict';
var piedmont = require('piedmont'),
process = require('process');
module.exports = function (grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('piedmont', 'Generate a Living Styleguide based on a Frontend Prototype', function () {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
dest: './styling-guidelines',
src: './dist',
styles: './src/sass',
tmp: '.tmp/styleguide'
}),
done = this.async();
piedmont({
cwd: process.cwd(),
dest: options.dest,
src: options.src,
styles: options.styles,
tmp: options.tmp
}, done);
grunt.log.writeln('Waiting for the files to be written...');
});
};
| 'use strict';
var piedmont = require('piedmont'),
process = require('process');
module.exports = function (grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('piedmont', 'Generate a Living Styleguide based on a Frontend Prototype', function () {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
dest: './styling-guidelines',
src: './dist',
styles: './src/sass/**/*.scss',
tmp: '.tmp/styleguide'
}),
done = this.async();
piedmont({
cwd: process.cwd(),
dest: options.dest,
src: options.src,
styles: options.styles,
tmp: options.tmp
}, done);
grunt.log.writeln('Waiting for the files to be written...');
});
};
|
Update the benchmark to use the document.readyState to measure page-completedness
rather than the onload event. Extensions were moved from the pre-onload state
to running at document idle some time ago.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/397013
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@32076 0039d316-1c4b-4281-b951-d872f2087c98 | // The port for communicating back to the extension.
var benchmarkExtensionPort = chrome.extension.connect();
// The url is what this page is known to the benchmark as.
// The benchmark uses this id to differentiate the benchmark's
// results from random pages being browsed.
// TODO(mbelshe): If the page redirects, the location changed and the
// benchmark stalls.
var benchmarkExtensionUrl = window.location.toString();
function sendTimesToExtension() {
if (window.parent != window) {
return;
}
var times = window.chrome.loadTimes();
// If the load is not finished yet, schedule a timer to check again in a
// little bit.
if (times.finishLoadTime != 0) {
benchmarkExtensionPort.postMessage({message: "load", url: benchmarkExtensionUrl, values: times});
} else {
window.setTimeout(sendTimesToExtension, 100);
}
}
// We can't use the onload event because this script runs at document idle,
// which may run after the onload has completed.
sendTimesToExtension();
| // The port for communicating back to the extension.
var benchmarkExtensionPort = chrome.extension.connect();
// The url is what this page is known to the benchmark as.
// The benchmark uses this id to differentiate the benchmark's
// results from random pages being browsed.
// TODO(mbelshe): If the page redirects, the location changed and the
// benchmark stalls.
var benchmarkExtensionUrl = window.location.toString();
function sendTimesToExtension() {
var times = window.chrome.loadTimes();
if (times.finishLoadTime != 0) {
benchmarkExtensionPort.postMessage({message: "load", url: benchmarkExtensionUrl, values: times});
} else {
window.setTimeout(sendTimesToExtension, 100);
}
}
function loadComplete() {
// Only trigger for top-level frames (e.g. the one we benchmarked)
if (window.parent == window) {
sendTimesToExtension();
}
}
window.addEventListener("load", loadComplete);
|
Fix Buble classes being transpiled to variable | import React from 'react'
import transform from './transform'
import errorBoundary from './errorBoundary'
import evalCode from './evalCode'
export const generateElement = (
{ code = '', scope = {} },
errorCallback
) => {
// NOTE: Workaround for classes, since buble doesn't allow `return` without a function
const transformed = transform(code)
.trim()
.replace(/^var \w+ =/, '')
return errorBoundary(
evalCode(
`return ${transformed}`,
{ ...scope, React }
),
errorCallback
)
}
export const renderElementAsync = (
{ code = '', scope = {} },
resultCallback,
errorCallback
) => {
const render = element => {
resultCallback(
errorBoundary(
element,
errorCallback
)
)
}
if (!/render\s*\(/.test(code)) {
return errorCallback(
new SyntaxError('No-Inline evaluations must call `render`.')
)
}
evalCode(
transform(code),
{ ...scope, render, React }
)
}
| import React from 'react'
import transform from './transform'
import errorBoundary from './errorBoundary'
import evalCode from './evalCode'
export const generateElement = (
{ code = '', scope = {} },
errorCallback
) => (
errorBoundary(
evalCode(
`return (${transform(code)})`,
{ ...scope, React }
),
errorCallback
)
)
export const renderElementAsync = (
{ code = '', scope = {} },
resultCallback,
errorCallback
) => {
const render = element => {
resultCallback(
errorBoundary(
element,
errorCallback
)
)
}
if (!/render\s*\(/.test(code)) {
return errorCallback(
new SyntaxError('No-Inline evaluations must call `render`.')
)
}
evalCode(
transform(code),
{ ...scope, render, React }
)
}
|
Adjust when to load data. | # -*- coding: utf-8 -*-
import schedule
from feed import load_feed
from twitter import send_queued_tweet
import time
import os
RSS_FEED_LIST = os.environ['RSS_FEED_LIST']
def parse_feed_list(s):
parsed = s.split(',')
if parsed == ['']:
return []
else:
return parsed
def main():
rsslist = parse_feed_list(RSS_FEED_LIST)
schedule.every().hour.do(load_feed, rsslist)
schedule.every(5).minutes.do(send_queued_tweet)
while True:
schedule.run_pending()
time.sleep(1)
def __main__():
main()
if __name__ == "__main__":
try:
__main__()
except (KeyboardInterrupt):
exit('Received Ctrl+C. Stopping application.', 1)
| # -*- coding: utf-8 -*-
import schedule
from feed import load_feed
from twitter import send_queued_tweet
import time
import os
RSS_FEED_LIST = os.environ['RSS_FEED_LIST']
def parse_feed_list(s):
parsed = s.split(',')
if parsed == ['']:
return []
else:
return parsed
def main():
rsslist = parse_feed_list(RSS_FEED_LIST)
schedule.every(10).seconds.do(load_feed, rsslist)
schedule.every(5).minutes.do(send_queued_tweet)
while True:
schedule.run_pending()
time.sleep(1)
def __main__():
main()
if __name__ == "__main__":
try:
__main__()
except (KeyboardInterrupt):
exit('Received Ctrl+C. Stopping application.', 1)
|
Add pause after button click to handle delays | function createDoc(browser, docType) {
const devServer = browser.globals.devServerURL;
browser.url(`${devServer}/`);
browser.expect.element('#app').to.be.visible.before(5000);
browser.execute(() => {
const className = `.${docType}`;
const numDocs = document.querySelectorAll(className).length;
return numDocs;
}, [docType], (numDocs) => {
try {
const createButton = `#button-create-${docType}`;
const numDocsAfterCreate = numDocs.value + 1;
browser
.click(createButton)
.pause(500);
browser
.expect(numDocs.value).to.equal(numDocsAfterCreate);
} catch (error) {
console.log(error);
}
});
}
describe('FileManager\'s create file/folder button', function() {
after((browser, done) => {
browser.end(() => done());
});
it('should create a new file', (browser) => {
createDoc(browser, 'file');
});
it('should create a new folder', (browser) => {
createDoc(browser, 'folder');
});
});
| function createDoc(browser, docType) {
const devServer = browser.globals.devServerURL;
browser.url(`${devServer}/`);
browser.expect.element('#app').to.be.visible.before(5000);
browser.execute(() => {
const className = `.${docType}`;
const numDocs = document.querySelectorAll(className).length;
return numDocs;
}, [docType], (numDocs) => {
try {
const createButton = `#button-create-${docType}`;
const numDocsAfterCreate = numDocs.value + 1;
browser
.click(createButton);
browser
.expect(numDocs.value).to.equal(numDocsAfterCreate);
} catch (error) {
console.log(error);
}
});
}
describe('FileManager\'s create file/folder button', function() {
after((browser, done) => {
browser.end(() => done());
});
it('should create a new file', (browser) => {
createDoc(browser, 'file');
});
it('should create a new folder', (browser) => {
createDoc(browser, 'folder');
});
});
|
Allow to change flexibee url | package com.adleritech.flexibee.core.api;
import com.adleritech.flexibee.core.api.domain.WinstromRequest;
import com.adleritech.flexibee.core.api.domain.WinstromResponse;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import java.io.IOException;
public class FlexibeeClient {
private static final String API_BASE_URL = "https://demo.flexibee.eu:5434";
private final String company;
private final Api client;
public FlexibeeClient(String username, String password, String company) {
this.company = company;
client = RetrofitClientFactory.createService(Api.class, API_BASE_URL, username, password);
}
public FlexibeeClient(String username, String password, String company, String apiBaseUrl) {
this.company = company;
client = RetrofitClientFactory.createService(Api.class, apiBaseUrl, username, password);
}
public WinstromResponse createInvoice(WinstromRequest winstromRequest) throws IOException {
Response<WinstromResponse> response = client.issueInvoice(company, winstromRequest).execute();
return response.body();
}
interface Api {
@PUT("/c/{company}/faktura-vydana.xml")
Call<WinstromResponse> issueInvoice(@Path("company") String company, @Body WinstromRequest request);
}
}
| package com.adleritech.flexibee.core.api;
import com.adleritech.flexibee.core.api.domain.WinstromRequest;
import com.adleritech.flexibee.core.api.domain.WinstromResponse;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import java.io.IOException;
public class FlexibeeClient {
private static final String API_BASE_URL = "https://demo.flexibee.eu:5434";
private final String company;
private final Api client;
public FlexibeeClient(String username, String password, String company) {
this.company = company;
client = RetrofitClientFactory.createService(Api.class, API_BASE_URL, username, password);
}
public WinstromResponse createInvoice(WinstromRequest winstromRequest) throws IOException {
Response<WinstromResponse> response = client.issueInvoice(company, winstromRequest).execute();
return response.body();
}
interface Api {
@PUT("/c/{company}/faktura-vydana.xml")
Call<WinstromResponse> issueInvoice(@Path("company") String company, @Body WinstromRequest request);
}
}
|
TBR: Remove dependency on crypto, since that adds about 1M.
Change-Id: I30bfb3c33445bf36cbf23adcc748fd4b324dc92e | module.exports = {
shortName: shortName,
firstShortName: firstShortName,
randomHex: randomHex
};
// Note, shortName and firstShortName are duplicated between JS and Go.
function shortName(fullName) {
// Split into components and see if any is an email address. A very
// sophisticated technique is used to determine if the component is an email
// address: presence of an "@" character.
var parts = fullName.split('/'); // security.ChainSeparator
for (var j = 0; j < parts.length; j++) {
var p = parts[j];
if (p.indexOf('@') > 0) {
return p;
}
}
return '';
}
function firstShortName(blessings) {
if (!blessings || blessings.length === 0) {
return 'unknown';
}
for (var i = 0; i < blessings.length; i++) {
var sn = shortName(blessings[i]);
if (sn) return sn;
}
return blessings[0];
}
function randomBytes(len) {
len = len || 1;
var array = new Int8Array(len);
window.crypto.getRandomValues(array);
return new Buffer(array);
}
function randomHex(len) {
return randomBytes(Math.ceil(len/2)).toString('hex').substr(0, len);
}
| var crypto = require('crypto');
module.exports = {
shortName: shortName,
firstShortName: firstShortName,
randomHex: randomHex
};
// Note, shortName and firstShortName are duplicated between JS and Go.
function shortName(fullName) {
// Split into components and see if any is an email address. A very
// sophisticated technique is used to determine if the component is an email
// address: presence of an "@" character.
var parts = fullName.split('/'); // security.ChainSeparator
for (var j = 0; j < parts.length; j++) {
var p = parts[j];
if (p.indexOf('@') > 0) {
return p;
}
}
return '';
}
function firstShortName(blessings) {
if (!blessings || blessings.length === 0) {
return 'unknown';
}
for (var i = 0; i < blessings.length; i++) {
var sn = shortName(blessings[i]);
if (sn) return sn;
}
return blessings[0];
}
function randomHex(len) {
return crypto.randomBytes(Math.ceil(len/2)).toString('hex').slice(0, len);
}
|
[FIX] Correct author
(../trunk-generic/ rev 29.1.22) | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Joel Grand-Guillaume
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import model
| # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import model
|
Allow plugin to be disabled | package helpers;
import play.Play;
import play.libs.Codec;
import play.mvc.Http;
/**
* @author jtremeaux
*/
public class BasicAuthHelper {
public static void unauthorized(Http.Response response) {
String realm = Play.configuration.getProperty("basicAuth.realm", "Secure Realm");
response.status = Http.StatusCode.UNAUTHORIZED;
response.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
}
public static boolean checkAuthenticationHeaders(Http.Request request) {
String username = Play.configuration.getProperty("basicAuth.username");
String password = Play.configuration.getProperty("basicAuth.password");
if (username == null || password == null) {
return true;
}
Http.Header authHeader = request.headers.get("authorization");
if (authHeader != null) {
String expected = "Basic " + Codec.encodeBASE64(username + ":" + password);
if (expected.equals(authHeader.value())) {
return true;
}
}
return false;
}
}
| package helpers;
import play.Play;
import play.libs.Codec;
import play.mvc.Http;
/**
* @author jtremeaux
*/
public class BasicAuthHelper {
public static void unauthorized(Http.Response response) {
String realm = Play.configuration.getProperty("basicAuth.realm", "Secure Realm");
response.status = Http.StatusCode.UNAUTHORIZED;
response.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
}
public static boolean checkAuthenticationHeaders(Http.Request request) {
Http.Header authHeader = request.headers.get("authorization");
if (authHeader != null) {
String username = Play.configuration.getProperty("basicAuth.username");
String password = Play.configuration.getProperty("basicAuth.password");
if (username == null || password == null) {
return true;
}
String expected = "Basic " + Codec.encodeBASE64(username + ":" + password);
if (expected.equals(authHeader.value())) {
return true;
}
}
return false;
}
}
|
Check default country is defined before starting app. | package plugins;
import com.google.inject.Guice;
import com.google.inject.Injector;
import controllers.CountryOperations;
import io.sphere.sdk.client.PlayJavaClient;
import play.Application;
import play.GlobalSettings;
public class Global extends GlobalSettings {
private Injector injector;
@Override
public void onStart(final Application app) {
checkDefaultCountry(app);
super.onStart(app);
injector = createInjector(app);
}
protected Injector createInjector(Application app) {
return Guice.createInjector(new ProductionModule(app));
}
private void checkDefaultCountry(Application app) {
CountryOperations.of(app.configuration()).defaultCountry();
}
@Override
public void onStop(final Application app) {
injector.getInstance(PlayJavaClient.class).close();
super.onStop(app);
}
@Override
public <A> A getControllerInstance(final Class<A> controllerClass) throws Exception {
return injector.getInstance(controllerClass);
}
}
| package plugins;
import com.google.inject.Guice;
import com.google.inject.Injector;
import io.sphere.sdk.client.PlayJavaClient;
import play.Application;
import play.GlobalSettings;
public class Global extends GlobalSettings {
private Injector injector;
@Override
public void onStart(final Application app) {
super.onStart(app);
injector = createInjector(app);
}
protected Injector createInjector(Application app) {
return Guice.createInjector(new ProductionModule(app));
}
@Override
public void onStop(final Application app) {
injector.getInstance(PlayJavaClient.class).close();
super.onStop(app);
}
@Override
public <A> A getControllerInstance(final Class<A> controllerClass) throws Exception {
return injector.getInstance(controllerClass);
}
}
|
Make it respond to touch events - much more responsive now | import React, { Component } from 'react';
import './Tile.css';
class Tile extends Component {
showTile(e,tileId) {
e.preventDefault();
this.props.showTile(tileId);
}
render() {
let {tile} = this.props;
let selected = tile.selected || tile.match ? " flipped" : "";
let imgUrl = tile.selected ? tile.src : tile.src;
let match = tile.match ? " match" : "";
const componentClasses = ['container'];
componentClasses.push(match);
const backTileImageSrc = `images/back/${this.props.backTileId}.jpg`;
return (
<li>
<section className={componentClasses.join("")} onTouchEnd={(e) => this.showTile(e,tile.id)} onClick={(e) => this.showTile(e,tile.id)}>
<div className={"card" + selected}>
<figure className="front">
<img src={backTileImageSrc} role="presentation"/>
</figure>
<figure className="back">
<img src={imgUrl} role="presentation"/>
</figure>
</div>
</section>
</li>
);
}
}
export default Tile;
| import React, { Component } from 'react';
import './Tile.css';
class Tile extends Component {
showTile(tileId) {
this.props.showTile(tileId);
}
render() {
let {tile} = this.props;
let selected = tile.selected || tile.match ? " flipped" : "";
let imgUrl = tile.selected ? tile.src : tile.src;
let match = tile.match ? " match" : "";
const componentClasses = ['container'];
componentClasses.push(match);
const backTileImageSrc = `images/back/${this.props.backTileId}.jpg`;
return (
<li>
<section className={componentClasses.join("")} onClick={() => this.showTile(tile.id)}>
<div className={"card" + selected}>
<figure className="front">
<img src={backTileImageSrc} role="presentation"/>
</figure>
<figure className="back">
<img src={imgUrl} role="presentation"/>
</figure>
</div>
</section>
</li>
);
}
}
export default Tile;
|
Use code tags for Make script checks | // @flow
import type { ActionArgs } from '../src/runners/action-args.js'
const util = require('util')
const exec = util.promisify(require('child_process').exec)
const path = require('path')
module.exports = async function (args: ActionArgs) {
const makeExpression = args.nodes.text()
const expected = makeExpression.replace(/make\s+/, '')
const makePath = path.join(args.configuration.sourceDir, 'Makefile')
const { stdout, stderr } = await exec(
`cat ${makePath} | grep '^[^ ]*:' | grep -v '.PHONY' | grep -v help | sed 's/:.*#//'`
)
if (stderr.length > 0) {
throw new Error(`Error running 'make help': ${stderr}`)
}
const actuals = stdout.split('\n').map(actual => actual.split(' ')[0])
if (!actuals.includes(expected)) {
throw new Error(`make script '${expected}' does not exist`)
}
}
| // @flow
import type { ActionArgs } from '../src/runners/action-args.js'
const util = require('util')
const exec = util.promisify(require('child_process').exec)
module.exports = async function (args: ActionArgs) {
const makeExpression = args.nodes.textInNodeOfType('code')
const expected = makeExpression.split(' ')[1]
const { stdout, stderr } = await exec(
"cat Makefile | grep '^[^ ]*:' | grep -v '.PHONY' | grep -v help | sed 's/:.*#//'"
)
if (stderr.length > 0) {
throw new Error(`Error running 'make help': ${stderr}`)
}
const actuals = stdout.split('\n').map(actual => actual.split(' ')[0])
if (!actuals.includes(expected)) {
throw new Error(`binary '${expected}' does not exist`)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.