text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Allow turbolinks to handle our custom push states
|
// This code is to implement the tabs on the home page
// navigate to the selected tab or the first tab
function tabNavigation(e) {
var activeTab = $('[href="' + location.hash + '"]');
if (activeTab.length) {
activeTab.tab('show');
} else {
var firstTab = $('.nav-tabs a:first');
// select the first tab if it has an id and is expected to be selected
if ((firstTab[0] !== undefined) && (firstTab[0].id != "")){
$(firstTab).tab('show');
}
}
}
Blacklight.onLoad(function () {
// When we visit a link to a tab, open that tab.
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
}
// Change the url when a tab is clicked.
$('a[data-toggle="tab"]').on('click', function(e) {
// Set turbolinks: true so that turbolinks can handle the back requests
// See https://github.com/turbolinks/turbolinks/blob/master/src/turbolinks/history.coffee#L28
history.pushState({turbolinks: true}, null, $(this).attr('href'));
});
// navigate to a tab when the history changes (back button)
window.addEventListener("popstate", tabNavigation);
});
|
// This code is to implement the tabs on the home page
// navigate to the selected tab or the first tab
function tabNavigation(e) {
var activeTab = $('[href="' + location.hash + '"]');
if (activeTab.length) {
activeTab.tab('show');
} else {
var firstTab = $('.nav-tabs a:first');
// select the first tab if it has an id and is expected to be selected
if ((firstTab[0] !== undefined) && (firstTab[0].id != "")){
$(firstTab).tab('show');
}
}
}
Blacklight.onLoad(function () {
// When we visit a link to a tab, open that tab.
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
}
// Change the url when a tab is clicked.
$('a[data-toggle="tab"]').on('click', function(e) {
history.pushState(null, null, $(this).attr('href'));
});
// navigate to a tab when the history changes (back button)
window.addEventListener("popstate", tabNavigation);
});
|
Exclude index.html and tests from manifest
|
var path = require('path');
var fs = require('fs');
var mergeTrees = require('broccoli-merge-trees');
var fileRemover = require('broccoli-file-remover');
var manifest = require('./manifest');
module.exports = {
name: 'broccoli-manifest',
initializeOptions: function() {
var defaultOptions = {
enabled: this.app.env === 'production',
appcacheFile: "/manifest.appcache"
}
this.options = this.app.options.manifest = this.app.options.manifest || {};
for (var option in defaultOptions) {
if (!this.options.hasOwnProperty(option)) {
this.options[option] = defaultOptions[option];
}
}
},
postprocessTree: function (type, tree) {
if (type === 'all') { //} && this.options.enabled) {
tree = removeFile(tree, {
paths: ['index.html', 'tests/']
});
return mergeTrees([tree, manifest(tree, this.options)]);
}
return tree;
},
included: function (app) {
this.app = app;
this.initializeOptions();
},
treeFor: function() {}
}
|
var path = require('path');
var fs = require('fs');
var mergeTrees = require('broccoli-merge-trees');
var manifest = require('./manifest');
module.exports = {
name: 'broccoli-manifest',
initializeOptions: function() {
var defaultOptions = {
enabled: this.app.env === 'production',
appcacheFile: "/manifest.appcache"
}
this.options = this.app.options.manifest = this.app.options.manifest || {};
for (var option in defaultOptions) {
if (!this.options.hasOwnProperty(option)) {
this.options[option] = defaultOptions[option];
}
}
},
postprocessTree: function (type, tree) {
if (type === 'all') { //} && this.options.enabled) {
return mergeTrees([tree, manifest(tree, this.options)]);
}
return tree;
},
included: function (app) {
this.app = app;
this.initializeOptions();
},
treeFor: function() {}
}
|
Put server version back to dev.
--HG--
branch : dev
|
package server
import (
"time"
)
const (
ServerVersion = "dev"
MDBInitialSize = 1048576
TwoToTheSixtyThree = 9223372036854775808
SubmissionInitialAttempts = 5
SubmissionInitialBackoff = 2 * time.Microsecond
SubmissionMaxSubmitDelay = 2 * time.Second
VarIdleTimeoutMin = 50 * time.Millisecond
VarIdleTimeoutRange = 250
FrameLockMinExcessSize = 100
FrameLockMinRatio = 2
ConnectionRestartDelayRangeMS = 5000
ConnectionRestartDelayMin = 3 * time.Second
MostRandomByteIndex = 7 // will be the lsb of a big-endian client-n in the txnid.
MigrationBatchElemCount = 64
)
|
package server
import (
"time"
)
const (
ServerVersion = "0.2"
MDBInitialSize = 1048576
TwoToTheSixtyThree = 9223372036854775808
SubmissionInitialAttempts = 5
SubmissionInitialBackoff = 2 * time.Microsecond
SubmissionMaxSubmitDelay = 2 * time.Second
VarIdleTimeoutMin = 50 * time.Millisecond
VarIdleTimeoutRange = 250
FrameLockMinExcessSize = 100
FrameLockMinRatio = 2
ConnectionRestartDelayRangeMS = 5000
ConnectionRestartDelayMin = 3 * time.Second
MostRandomByteIndex = 7 // will be the lsb of a big-endian client-n in the txnid.
MigrationBatchElemCount = 64
)
|
Update encoding test to work with new interface.
|
package pd1_test
import (
// "math/rand"
"fmt"
"reflect"
"testing"
"time"
"github.com/influxdb/influxdb/tsdb/engine/pd1"
)
func TestEncoding_FloatBlock(t *testing.T) {
valueCount := 1000
times := getTimes(valueCount, 60, time.Second)
values := make(pd1.Values, len(times))
for i, t := range times {
values[i] = pd1.NewValue(t, float64(i))
}
b := values.Encode(nil)
fmt.Println("**** ", len(b))
decodedValues := values.DecodeSameTypeBlock(b)
if !reflect.DeepEqual(decodedValues, values) {
t.Fatalf("unexpected results:\n\tgot: %v\n\texp: %v\n", decodedValues, values)
}
}
func getTimes(n, step int, precision time.Duration) []time.Time {
t := time.Now().Round(precision)
a := make([]time.Time, n)
for i := 0; i < n; i++ {
a[i] = t.Add(60 * precision)
}
return a
}
|
package pd1_test
import (
// "math/rand"
// "reflect"
"testing"
"time"
// "github.com/influxdb/influxdb/tsdb/engine/pd1"
)
func TestEncoding_FloatBlock(t *testing.T) {
// valueCount := 100
// times := getTimes(valueCount, 60, time.Second)
// values := make([]Value, len(times))
// for i, t := range times {
// values[i] = pd1.NewValue(t, rand.Float64())
// }
// b := pd1.EncodeFloatBlock(nil, values)
// decodedValues, err := pd1.DecodeFloatBlock(b)
// if err != nil {
// t.Fatalf("error decoding: %s", err.Error)
// }
// if !reflect.DeepEqual(decodedValues, values) {
// t.Fatalf("unexpected results:\n\tgot: %v\n\texp: %v\n", decodedValues, values)
// }
}
func getTimes(n, step int, precision time.Duration) []time.Time {
t := time.Now().Round(precision)
a := make([]time.Time, n)
for i := 0; i < n; i++ {
a[i] = t.Add(60 * precision)
}
return a
}
|
Add Chapter 09, exercise 1
|
// Fill in the regular expressions
verify(/ca[rt]/,
["my car", "bad cats"],
["camper", "high art"]);
verify(/pr?op/,
["pop culture", "mad props"],
["plop"]);
verify(/ferr(et|y|ari)/,
["ferret", "ferry", "ferrari"],
["ferrum", "transfer A"]);
verify(/ious\b/,
["how delicious", "spacious room"],
["ruinous", "consciousness"]);
verify(/\s[.,:;]/,
["bad punctuation ."],
["escape the period"]);
verify(/\w{7,}/,
["hottentottententen"],
["no", "hotten totten tenten"]);
verify(/\b[^e\s]+\b/,
["red platypus", "wobbling nest"],
["earth bed", "learning ape"]);
|
verify(/ca[rt]/,
["my car", "bad cats"],
["camper", "high art"]);
verify(/pr?op/,
["pop culture", "mad props"],
["plop"]);
verify(/ferr[et|y|ari]/,
["ferret", "ferry", "ferrari"],
["ferrum", "transfer A"]);
verify(/ious\b/,
["how delicious", "spacious room"],
["ruinous", "consciousness"]);
verify(/\s[.,:;]/,
["bad punctuation ."],
["escape the dot"]);
verify(/\w{7,}/,
["hottentottententen"],
["no", "hotten totten tenten"]);
verify(/\b[^e ]+\b/,
["red platypus", "wobbling nest"],
["earth bed", "learning ape"]);
|
[CIKit] Add "-h" and "-v" to mutually exclusive group
|
from os import path
from actions import VersionAction
from argparse import ArgumentParser
from functions import parse_extra_vars
parser = ArgumentParser(
prog='cikit',
add_help=False,
)
parser.add_argument(
'playbook',
nargs='?',
default='',
help='The name of a playbook to run.',
)
options = parser.add_mutually_exclusive_group()
options.add_argument(
'-h',
action='help',
help='Show this help message and exit.',
)
options.add_argument(
'-v',
dest='%s/.version' % path.realpath(__file__ + '/..'),
action=VersionAction,
default='1.0.0',
)
parser.add_argument(
'--dry-run',
action='store_true',
help='Run CIKit without passing the control to Ansible.',
)
parser.add_argument(
'--limit',
metavar='HOST',
nargs='?',
help=(
'The host to run a playbook at. The value of this option must '
'be an alias of a host from the "%%s/.cikit/inventory" file.'
),
)
args, argv = parser.parse_known_args()
args.extra = {}
parse_extra_vars(argv, args.extra)
# Duplicate the "limit" option as "extra" because some playbooks may
# require it and required options are checked within the "extra" only.
if args.limit:
args.extra['limit'] = args.limit
del argv
|
from os import path
from actions import VersionAction
from argparse import ArgumentParser
from functions import parse_extra_vars
parser = ArgumentParser(
prog='cikit',
add_help=False,
)
parser.add_argument(
'playbook',
nargs='?',
default='',
help='The name of a playbook to run.',
)
parser.add_argument(
'-h',
action='help',
help='Show this help message and exit.',
)
parser.add_argument(
'-v',
dest='%s/.version' % path.realpath(__file__ + '/..'),
action=VersionAction,
default='1.0.0',
)
parser.add_argument(
'--dry-run',
action='store_true',
help='Run CIKit without passing the control to Ansible.',
)
parser.add_argument(
'--limit',
metavar='HOST',
nargs='?',
help=(
'The host to run a playbook at. The value of this option must '
'be an alias of a host from the "%%s/.cikit/inventory" file.'
),
)
args, argv = parser.parse_known_args()
args.extra = {}
parse_extra_vars(argv, args.extra)
# Duplicate the "limit" option as "extra" because some playbooks may
# require it and required options are checked within the "extra" only.
if args.limit:
args.extra['limit'] = args.limit
del argv
|
Make sure site generation works with newer ClojureScript
|
var cljsLoad = require("./cljs-load");
var srcFile = "outsite/public/js/main.js";
var outputDirectory = "outsite/public/js/out/";
var devFile = "reagentdemo/core.js";
var beep = "\u0007";
if (typeof location === "undefined") {
// figwheel wants js/location to exist, even if it doesn't run,
// for some reason
global.location = {};
}
var gensite = function () {
console.log("Loading " + srcFile);
var optNone = cljsLoad.load(srcFile, outputDirectory, devFile);
sitetools.core.genpages({"opt-none": optNone});
}
var compileFail = function () {
var msg = process.argv[process.argv.length - 1];
if (msg && msg.match(/failed/)) {
console.log("Compilation failed" + beep);
return true;
}
};
if (!compileFail()) {
try {
gensite();
} catch (e) {
console.log(e + beep);
console.error(e.stack);
process.exit(1);
}
}
process.exit(0);
|
var cljsLoad = require("./cljs-load");
var srcFile = "outsite/public/js/main.js";
var outputDirectory = "outsite/public/js/out/";
var devFile = "reagentdemo/dev.js";
var beep = "\u0007";
if (typeof location === "undefined") {
// figwheel wants js/location to exist, even if it doesn't run,
// for some reason
global.location = {};
}
var gensite = function () {
console.log("Loading " + srcFile);
var optNone = cljsLoad.load(srcFile, outputDirectory, devFile);
sitetools.core.genpages({"opt-none": optNone});
}
var compileFail = function () {
var msg = process.argv[process.argv.length - 1];
if (msg && msg.match(/failed/)) {
console.log("Compilation failed" + beep);
return true;
}
};
if (!compileFail()) {
try {
gensite();
} catch (e) {
console.log(e + beep);
console.error(e.stack);
process.exit(1);
}
}
process.exit(0);
|
Make sure its defined before using it.
|
// Take the comma separated list for {field} from {item}.{field} and populate the select#{field} box
// Any of the values in the comma separated list for {field} that doesn't have an option in select#{field}
// Get stuffed into {field}Other as it's own comma separated list.
function setupDisplayFieldsEducationTab(item, field) {
if (item[field] != undefined && item[field] != '' && $('select#'+field)[0] != undefined) {
var itemOptions = item[field].split(',');
$('select#'+field+' option').each(function() {
if ($.inArray($(this).val(),itemOptions) !== -1) {
$(this).attr('selected',true);
}
});
var selectOptions = $('select#'+field+' option').map(function() { return this.value });
var otherOptions = [];
for (i in itemOptions) {
if ($.inArray(itemOptions[i], selectOptions) === -1) {
otherOptions.push(itemOptions[i]);
}
}
if (otherOptions.length > 0) {
$('#'+field+'Other').attr('value',otherOptions.join(','));
}
}
}
|
// Take the comma separated list for {field} from {item}.{field} and populate the select#{field} box
// Any of the values in the comma separated list for {field} that doesn't have an option in select#{field}
// Get stuffed into {field}Other as it's own comma separated list.
function setupDisplayFieldsEducationTab(item, field) {
if (item[field] != '' && $('select#'+field)[0] != undefined) {
var itemOptions = item[field].split(',');
$('select#'+field+' option').each(function() {
if ($.inArray($(this).val(),itemOptions) !== -1) {
$(this).attr('selected',true);
}
});
var selectOptions = $('select#'+field+' option').map(function() { return this.value });
var otherOptions = [];
for (i in itemOptions) {
if ($.inArray(itemOptions[i], selectOptions) === -1) {
otherOptions.push(itemOptions[i]);
}
}
if (otherOptions.length > 0) {
$('#'+field+'Other').attr('value',otherOptions.join(','));
}
}
}
|
Fix relative path test on windows
|
var fork = require('child_process').fork
var path = require('path')
var grabStdio = require('../grab-stdio')
module.exports = {
'loads scripts from a relative path': function (done) {
var stdio = {}
var windowsSuffix = process.platform === 'win32' ? '-win' : ''
var child = fork('../../../cli', [], {
cwd: path.join(__dirname, '..', 'fixtures', 'relative-path-loading'),
silent: true,
env: {
npm_lifecycle_event: 'secret',
npm_package_scripty_path: '../custom-user-scripts' + windowsSuffix,
SCRIPTY_SILENT: true
}
})
grabStdio(stdio)(child)
child.on('exit', function (code) {
assert.equal(code, 0)
assert.includes(stdio.stdout, 'SSHHH')
done()
})
}
}
|
var fork = require('child_process').fork
var path = require('path')
var grabStdio = require('../grab-stdio')
module.exports = {
'loads scripts from a relative path': function (done) {
var stdio = {}
var child = fork('../../../cli', [], {
cwd: path.join(__dirname, '..', 'fixtures', 'relative-path-loading'),
silent: true,
env: {
npm_lifecycle_event: 'secret',
npm_package_scripty_path: '../custom-user-scripts',
SCRIPTY_SILENT: true
}
})
grabStdio(stdio)(child)
child.on('exit', function (code) {
assert.equal(code, 0)
assert.includes(stdio.stdout, 'SSHHH')
done()
})
}
}
|
Remove async library for server
|
var fork = require('child_process').fork;
var amountConcurrentServers = process.argv[2] || 50;
var port = initialPortServer();
var servers = [];
var path = __dirname;
for(var i = 0; i < amountConcurrentServers; i++) {
var portForServer = port + i;
var serverIdentifier = i;
console.log('Creating server: ' + serverIdentifier + ' - ' + portForServer + ' - ' + serverIdentifier);
servers[i] = fork( path +'/server.js', [portForServer, serverIdentifier]);
}
process.on('exit', function() {
console.log('exit process');
for(var i = 0; i < amountConcurrentServers; i++) {
servers[i].kill();
}
});
function initialPortServer() {
if(process.argv[3]) {
return parseInt(process.argv[3]);
}
return 3000;
}
|
var fork = require('child_process').fork;
var async = require('async');
var amountConcurrentServers = process.argv[2] || 50;
var port = initialPortServer();
var servers = [];
var path = __dirname;
for(var i = 0; i < amountConcurrentServers; i++) {
var portForServer = port + i;
var serverIdentifier = i;
console.log('Creating server: ' + serverIdentifier + ' - ' + portForServer + ' - ' + serverIdentifier);
servers[i] = fork( path +'/server.js', [portForServer, serverIdentifier]);
}
process.on('exit', function() {
console.log('exit process');
for(var i = 0; i < amountConcurrentServers; i++) {
servers[i].kill();
}
});
function initialPortServer() {
if(process.argv[3]) {
return parseInt(process.argv[3]);
}
return 3000;
}
|
Use TestCase from Django
Set STATIC_URL
|
#from unittest import TestCase
from django.test import TestCase
from django.test.utils import setup_test_template_loader, override_settings
from django.template import Context
from django.template.loader import get_template
TEMPLATES = {
'basetag': '''{% load damn %}{% assets %}''',
'test2': '''
<!doctype html>{% load damn %}
<html>
<head>
{% assets %}
</head>
<body>
{% asset 'js/jquery.js' %}
</body>
</html>
''',
}
DAMN_PROCESSORS = {
'js': {
'processor': 'damn.processors.ScriptProcessor',
},
}
class TagTests(TestCase):
def setUp(self):
setup_test_template_loader(TEMPLATES)
@override_settings(
DAMN_PROCESSORS=DAMN_PROCESSORS,
STATIC_URL = '/',
)
def test_simple(self):
t = get_template('basetag')
t.render()
@override_settings(
DAMN_PROCESSORS=DAMN_PROCESSORS,
STATIC_URL = '/',
)
def test_one(self):
t = get_template('test2')
o = t.render(Context())
self.assertTrue('<script src="/static/js/jquery.js"></script>' in o)
|
from unittest import TestCase
from django.test.utils import setup_test_template_loader, override_settings
from django.template import Context
from django.template.loader import get_template
TEMPLATES = {
'basetag': '''{% load damn %}{% assets %}''',
'test2': '''
<!doctype html>{% load damn %}
<html>
<head>
{% assets %}
</head>
<body>
{% asset 'js/jquery.js' %}
</body>
</html>
''',
}
DAMN_PROCESSORS = {
'js': {
'class': 'damn.processors.ScriptProcessor',
},
}
class TagTests(TestCase):
def setUp(self):
setup_test_template_loader(TEMPLATES)
@override_settings(
DAMN_PROCESSORS=DAMN_PROCESSORS,
)
def test_simple(self):
t = get_template('basetag')
t.render()
@override_settings(
DAMN_PROCESSORS=DAMN_PROCESSORS,
)
def test_one(self):
t = get_template('test2')
o = t.render(Context())
self.assertContains(o, '<script src="/static/js/jquery.js"></script>')
|
Use eval-source-maps for dev package.
|
const path = require('path');
const packagejson = require('./package.json');
const dashLibraryName = packagejson.name.replace(/-/g, '_');
module.exports = (env, argv) => ({
entry: {main: './src/index.js'},
output: {
path: path.resolve(__dirname, dashLibraryName),
filename: 'bundle.js',
library: dashLibraryName,
libraryTarget: 'window',
},
externals: {
react: 'React',
'react-dom': 'ReactDOM',
'plotly.js': 'Plotly',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
}
],
},
devtool: argv.mode === 'development' ? "eval-source-map" : 'source-map'
});
|
const path = require('path');
const packagejson = require('./package.json');
const dashLibraryName = packagejson.name.replace(/-/g, '_');
module.exports = {
entry: {main: './src/index.js'},
output: {
path: path.resolve(__dirname, dashLibraryName),
filename: 'bundle.js',
library: dashLibraryName,
libraryTarget: 'window',
},
externals: {
react: 'React',
'react-dom': 'ReactDOM',
'plotly.js': 'Plotly',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
}
],
},
};
|
Add auto generated note on migration
|
# -*- coding: utf-8 -*-
# Auto generated by Django migrate
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('sketch', '0009_merge'),
]
operations = [
migrations.RemoveField(
model_name='sketch',
name='timelines',
),
migrations.AddField(
model_name='sketchtimeline',
name='sketch',
field=models.ForeignKey(default=2, to='sketch.Sketch'),
preserve_default=True,
),
migrations.AddField(
model_name='sketchtimeline',
name='user',
field=models.ForeignKey(default=1, to=settings.AUTH_USER_MODEL),
preserve_default=True,
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('sketch', '0009_merge'),
]
operations = [
migrations.RemoveField(
model_name='sketch',
name='timelines',
),
migrations.AddField(
model_name='sketchtimeline',
name='sketch',
field=models.ForeignKey(default=2, to='sketch.Sketch'),
preserve_default=True,
),
migrations.AddField(
model_name='sketchtimeline',
name='user',
field=models.ForeignKey(default=1, to=settings.AUTH_USER_MODEL),
preserve_default=True,
),
]
|
Make the port larger then zero
|
package main
import (
aguin_api "aguin/api"
"aguin/config"
"flag"
"fmt"
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
"net/http"
"aguin/utils"
)
func main() {
var (
host string
port int
)
log := utils.GetLogger("system")
flag.StringVar(&host, "h", "", "Host to listen on")
flag.IntVar(&port, "p", 0, "Port number to listen on")
flag.Parse()
config.ReadConfig("./config")
api := martini.Classic()
api.Use(render.Renderer())
api.Use(aguin_api.VerifyRequest())
api.Get("/", aguin_api.IndexGet)
api.Post("/", aguin_api.IndexPost)
api.Get("/status", aguin_api.IndexStatus)
api.NotFound(aguin_api.NotFound)
serverConfig := config.ServerConf()
if port > 0 {
serverConfig.Port = port
}
if host != "" {
serverConfig.Host = host
}
log.Print(fmt.Sprintf("listening to address %s:%d", serverConfig.Host, serverConfig.Port))
http.ListenAndServe(fmt.Sprintf("%s:%d", serverConfig.Host, serverConfig.Port), api)
}
|
package main
import (
aguin_api "aguin/api"
"aguin/config"
"flag"
"fmt"
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
"net/http"
"aguin/utils"
)
func main() {
var (
host string
port int
)
log := utils.GetLogger("system")
flag.StringVar(&host, "h", "", "Host to listen on")
flag.IntVar(&port, "p", 0, "Port number to listen on")
flag.Parse()
config.ReadConfig("./config")
api := martini.Classic()
api.Use(render.Renderer())
api.Use(aguin_api.VerifyRequest())
api.Get("/", aguin_api.IndexGet)
api.Post("/", aguin_api.IndexPost)
api.Get("/status", aguin_api.IndexStatus)
api.NotFound(aguin_api.NotFound)
serverConfig := config.ServerConf()
if port != 0 {
serverConfig.Port = port
}
if host != "" {
serverConfig.Host = host
}
log.Print(fmt.Sprintf("listening to address %s:%d", serverConfig.Host, serverConfig.Port))
http.ListenAndServe(fmt.Sprintf("%s:%d", serverConfig.Host, serverConfig.Port), api)
}
|
Add missing $separator parameter to interface
|
<?php
/**
* This file is part of cocur/slugify.
*
* (c) Florian Eckerstorfer <florian@eckerstorfer.co>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cocur\Slugify;
/**
* SlugifyInterface
*
* @package org.cocur.slugify
* @author Florian Eckerstorfer <florian@eckerstorfer.co>
* @author Marchenko Alexandr
* @copyright 2012-2014 Florian Eckerstorfer
* @license http://www.opensource.org/licenses/MIT The MIT License
*/
interface SlugifyInterface
{
/**
* Return a URL safe version of a string.
*
* @param string $string
*
* @return string
*/
public function slugify($string, $separator = '-');
}
|
<?php
/**
* This file is part of cocur/slugify.
*
* (c) Florian Eckerstorfer <florian@eckerstorfer.co>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cocur\Slugify;
/**
* SlugifyInterface
*
* @package org.cocur.slugify
* @author Florian Eckerstorfer <florian@eckerstorfer.co>
* @author Marchenko Alexandr
* @copyright 2012-2014 Florian Eckerstorfer
* @license http://www.opensource.org/licenses/MIT The MIT License
*/
interface SlugifyInterface
{
/**
* Return a URL safe version of a string.
*
* @param string $string
*
* @return string
*/
public function slugify($string);
}
|
Print a message and leave if couldn't obtain invite link
Closes #25
|
'use strict';
// Bot
const { replyOptions } = require('../../bot/options');
const { admin } = require('../../stores/user');
const { addGroup, managesGroup } = require('../../stores/group');
const { masterID } = require('../../config.json');
const addedToGroupHandler = async (ctx, next) => {
const msg = ctx.message;
const { telegram } = ctx;
const wasAdded = msg.new_chat_members.some(user =>
user.username === ctx.me);
if (wasAdded && ctx.from.id === masterID) {
await admin(ctx.from);
if (!await managesGroup(ctx.chat)) {
try {
const link = await telegram.exportChatInviteLink(ctx.chat.id);
ctx.chat.link = link ? link : '';
} catch (err) {
await ctx.replyWithHTML(
'⚠️ <b>Please re-add me with admin permissions.</b>' +
'\n\n' +
`<code>${err}</code>`);
return telegram.leaveChat(ctx.chat.id);
}
await addGroup(ctx.chat);
}
ctx.reply('🛠 <b>Ok, I\'ll help you manage this group from now.</b>',
replyOptions);
}
return next();
};
module.exports = addedToGroupHandler;
|
'use strict';
// Bot
const bot = require('../../bot');
const { replyOptions } = require('../../bot/options');
const { admin } = require('../../stores/user');
const { addGroup, managesGroup } = require('../../stores/group');
const { masterID } = require('../../config.json');
const addedToGroupHandler = async (ctx, next) => {
const msg = ctx.message;
const wasAdded = msg.new_chat_members.some(user =>
user.username === ctx.me);
if (wasAdded && ctx.from.id === masterID) {
await admin(ctx.from);
if (!await managesGroup(ctx.chat)) {
const link = await bot.telegram.exportChatInviteLink(ctx.chat.id);
ctx.chat.link = link ? link : '';
await addGroup(ctx.chat);
}
ctx.reply('🛠 <b>Ok, I\'ll help you manage this group from now.</b>',
replyOptions);
}
return next();
};
module.exports = addedToGroupHandler;
|
Add render and renderFile methods
|
/**
* Module dependencies
*/
var defaults = require('./helpers');
var template = require('./template');
module.exports = createInstance;
/**
* Create an instance of JSONt
*
* @return {JSONt}
*/
function createInstance() {
function JSONt(tmpl, options){ return JSONt.compile(tmpl, options); };
JSONt.helpers = {};
JSONt.helpers.__proto__ = defaults;
JSONt.use = use;
JSONt.plugin = plugin;
JSONt.compile = compile;
JSONt.render = render;
JSONt.renderFile = renderFile;
return JSONt;
};
/**
* Use a helpers
*
* @param {String} name
* @param {Function} fun
* @return {JSONt} for chaining
*/
function use(name, fun) {
this.helpers[name] = fun;
return this;
};
/**
* Register a collection of helpers
*/
function plugin(fn) {
fn(this);
return this;
};
/**
* Compile a template with the default helpers
*
* @param {String|Object} tmpl
* @param {Object} options
* @return {Template}
*/
function compile(tmpl, options) {
return template(tmpl, options || {}, this.helpers);
};
/**
* Compile and render a template
*
* @param {String|Object} tmpl
* @param {Object} options
* @param {Function} fn
*/
function render(tmpl, options, fn) {
this.compile(tmpl, options)(options, fn);
};
/**
* Compile and render a template
*
* @param {String} filename
* @param {Object} options
* @param {Function} fn
*/
function renderFile(file, options, fn) {
this.compile(require(file), options)(options, fn);
};
|
/**
* Module dependencies
*/
var defaults = require('./helpers');
var template = require('./template');
module.exports = createInstance;
/**
* Create an instance of JSONt
*
* @return {JSONt}
*/
function createInstance() {
function JSONt(tmpl, options){ return JSONt.compile(tmpl, options); };
JSONt.helpers = {};
JSONt.helpers.__proto__ = defaults;
JSONt.use = use;
JSONt.plugin = plugin;
JSONt.compile = compile;
return JSONt;
};
/**
* Use a helpers
*
* @param {String} name
* @param {Function} fun
* @return {JSONt} for chaining
*/
function use(name, fun) {
this.helpers[name] = fun;
return this;
};
/**
* Register a collection of helpers
*/
function plugin(fn) {
fn(this);
return this;
};
/**
* Compile a template with the default helpers
*
* @param {String|Object} tmpl
* @param {Object} options
* @return {Template}
*/
function compile(tmpl, options) {
return template(tmpl, options || {}, this.helpers);
};
|
Support running test just by test name
|
#!/usr/bin/env python
import sys
sys.path.append('lib/sdks/google_appengine_1.7.1/google_appengine')
import dev_appserver
import unittest
dev_appserver.fix_sys_path()
suites = unittest.loader.TestLoader().discover("src/givabit", pattern="*_test.py")
if len(sys.argv) > 1:
def GetTestCases(caseorsuite, acc=None):
if acc is None:
acc = []
if isinstance(caseorsuite, unittest.TestCase):
acc.append(caseorsuite)
return acc
for child in caseorsuite:
GetTestCases(child, acc)
return acc
all_tests = GetTestCases(suites)
tests = [test for test in all_tests if test.id().startswith(sys.argv[1]) or test.id().endswith(sys.argv[1])]
suites = unittest.TestSuite(tests)
unittest.TextTestRunner(verbosity=1).run(suites)
|
#!/usr/bin/env python
import sys
sys.path.append('lib/sdks/google_appengine_1.7.1/google_appengine')
import dev_appserver
import unittest
dev_appserver.fix_sys_path()
suites = unittest.loader.TestLoader().discover("src/givabit", pattern="*_test.py")
if len(sys.argv) > 1:
def GetTestCases(caseorsuite, acc=None):
if acc is None:
acc = []
if isinstance(caseorsuite, unittest.TestCase):
acc.append(caseorsuite)
return acc
for child in caseorsuite:
GetTestCases(child, acc)
return acc
all_tests = GetTestCases(suites)
tests = [test for test in all_tests if test.id().startswith(sys.argv[1])]
suites = unittest.TestSuite(tests)
unittest.TextTestRunner(verbosity=1).run(suites)
|
Fix server require statement paths
|
var userController = require('./users/userController.js');
var listingController = require('./listings/listingController.js');
module.exports = (app, db) => {
// Routes for all users
app.get('/api/users', userController.getAll);
app.post('/api/users', userController.createOne);
// Routes for specific user
app.get('api/users/:id', userController.getOne);
app.patch('api/users/:id', userController.patchOne);
app.delete('api/users/:id', userController.deleteOne);
// Routes for all listings belonging to a specific user
app.get('api/users/:id/listings', listingController.getAll);
app.post('api/users/:id/listings', listingController.createOne);
// Routes for a specific listing
app.get('api/listings/:listId', listingController.getOne);
app.patch('api/listings/:listId', listingController.patchOne);
app.delete('api/listings/:listId', listingController.deleteOne);
// Routes for a specific listing's photos
app.get('api/listings/:listId/photos', listingController.getAllPhotos);
app.post('api/listings/:listId/photos', listingController.createOnePhoto);
// Routes for a specific listing's specific photo
app.patch('api/listings/:listId/photos/:id', listingController.patchOnePhoto);
app.delete('api/listings/:listId/photos/:id', listingController.deleteOnePhoto);
}
|
var userController = require('../users/userController.js');
var listingController = require('../listings/listingController.js');
module.exports = (app, db) => {
// Routes for all users
app.get('/api/users', userController.getAll);
app.post('/api/users', userController.createOne);
// Routes for specific user
app.get('api/users/:id', userController.getOne);
app.patch('api/users/:id', userController.patchOne);
app.delete('api/users/:id', userController.deleteOne);
// Routes for all listings belonging to a specific user
app.get('api/users/:id/listings', listingController.getAll);
app.post('api/users/:id/listings', listingController.createOne);
// Routes for a specific listing
app.get('api/listings/:listId', listingController.getOne);
app.patch('api/listings/:listId', listingController.patchOne);
app.delete('api/listings/:listId', listingController.deleteOne);
// Routes for a specific listing's photos
app.get('api/listings/:listId/photos', listingController.getAllPhotos);
app.post('api/listings/:listId/photos', listingController.createOnePhoto);
// Routes for a specific listing's specific photo
app.patch('api/listings/:listId/photos/:id', listingController.patchOnePhoto);
app.delete('api/listings/:listId/photos/:id', listingController.deleteOnePhoto);
}
|
Check that options declares Google Fonts before building component
|
// @flow
import React from 'react'
module.exports = (options: any) =>
React.createClass({
displayName: 'GoogleFont',
render () {
// Create family + styles string
let fontsStr = ''
if (options.googleFonts) {
const fonts = options.googleFonts.map((font) => {
let str = ''
str += font.name.split(' ').join('+')
str += ':'
str += font.styles.join(',')
return str
})
fontsStr = fonts.join('|')
if (fontsStr) {
return React.DOM.link({
href: `//fonts.googleapis.com/css?family=${fontsStr}`,
rel: 'stylesheet',
type: 'text/css',
})
} else {
return null
}
} else {
return null
}
},
})
|
// @flow
import React from 'react'
module.exports = (options: any) =>
React.createClass({
displayName: 'GoogleFont',
render () {
// Create family + styles string
let fontsStr = ''
const fonts = options.googleFonts.map((font) => {
let str = ''
str += font.name.split(' ').join('+')
str += ':'
str += font.styles.join(',')
return str
})
fontsStr = fonts.join('|')
if (fontsStr) {
return React.DOM.link({
href: `//fonts.googleapis.com/css?family=${fontsStr}`,
rel: 'stylesheet',
type: 'text/css',
})
} else {
return null
}
},
})
|
Fix bug with repeated events
The first event from the first page was repeated at the top of the
second page
|
var Activity = require('./activity');
var Readable = require('stream').Readable;
var util = require('util');
/**
* Readable stream that emits event objects from the github events api for a
* given user
*/
function ActivityStream() {
this.eventsPromise = Activity.get();
this.eventIndex = 0;
Readable.call(this, {objectMode:true});
}
util.inherits(ActivityStream, Readable);
ActivityStream.prototype._read = function () {
pushNextEvent(this);
};
function pushNextEvent(stream) {
stream.eventsPromise.done(function(events) {
if (!events) {
return stream.push(null);
}
// If we're at the end of the current page of events,
// load some more.
if (!events[stream.eventIndex]) {
stream.eventsPromise = events.nextPage();
stream.eventIndex = 0;
pushNextEvent(stream);
} else {
stream.push(events[stream.eventIndex]);
stream.eventIndex++;
}
});
}
module.exports = ActivityStream;
|
var Activity = require('./activity');
var Readable = require('stream').Readable;
var util = require('util');
/**
* Readable stream that emits event objects from the github events api for a
* given user
*/
function ActivityStream() {
this.eventsPromise = Activity.get();
this.eventIndex = 0;
Readable.call(this, {objectMode:true});
}
util.inherits(ActivityStream, Readable);
ActivityStream.prototype._read = function () {
pushNextEvent(this);
};
function pushNextEvent(stream) {
stream.eventsPromise.done(function(events) {
if (!events) {
return stream.push(null);
}
if (!events[stream.eventIndex]) {
stream.eventsPromise = events.nextPage();
stream.eventIndex = 0;
pushNextEvent(stream);
}
stream.push(events[stream.eventIndex]);
stream.eventIndex++;
});
}
module.exports = ActivityStream;
|
Fix displaying of category description.
|
@extends('layouts.master')
@section('body', '')
@push('styles')
@endpush
@section('title')
{{ $category->title }} | @parent
@stop
@section('keywords', $category->param('meta_keywords') ?? config('site.keywords'))
@section('description', $category->param('meta_description') ?? config('site.description'))
@section('author', $category->param('author_alias') ?? config('site.author'))
@section('page-title')
{{ $category->title }}
@stop
@section('content')
@if($category->description)
<div class="row category-description">
<div class="col-md-12">
{!! $category->description !!}
</div>
</div>
@endif
@each('category.partials.articles', $articles, 'article', 'category.partials.no-articles')
{!! $articles->render() !!}
@stop
|
@extends('layouts.master')
@section('body', '')
@push('styles')
@endpush
@section('title')
{{ $category->title }} | @parent
@stop
@section('keywords', $category->param('meta_keywords') ?? config('site.keywords'))
@section('description', $category->param('meta_description') ?? config('site.description'))
@section('author', $category->param('author_alias') ?? config('site.author'))
@section('page-title')
{{ $category->title }}
@stop
@section('content')
@if($category->param('show_description'))
<div class="row category-description">
<div class="col-md-12">
{!! $category->description !!}
</div>
</div>
@endif
@each('category.partials.articles', $articles, 'article', 'category.partials.no-articles')
{!! $articles->render() !!}
@stop
|
Move to reports on Session verification
|
import Component from '@ember/component';
import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency';
export default Component.extend({
router: service(),
currentUser: service(),
store: service(),
flashMessages: service(),
verifySessionModal: false,
verifySessionModalError: false,
verifySession: task(function *() {
try {
yield this.get('model').verify({
'by': this.get('currentUser.user.id')
});
this.get('model').reload();
this.set('verifySessionModal', false);
this.set('verifySessionModalError', false);
this.get('flashMessages').success("Verified!");
this.get('router').transitionTo('dashboard.conventions.convention.sessions.session.reports');
} catch(e) {
this.set('verifySessionModalError', true);
}
}).drop(),
});
|
import Component from '@ember/component';
import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency';
export default Component.extend({
router: service(),
currentUser: service(),
store: service(),
flashMessages: service(),
verifySessionModal: false,
verifySessionModalError: false,
verifySession: task(function *() {
try {
yield this.get('model').verify({
'by': this.get('currentUser.user.id')
});
this.get('model').reload();
this.set('verifySessionModal', false);
this.set('verifySessionModalError', false);
this.get('flashMessages').success("Verified!");
this.get('router').transitionTo('dashboard.conventions.convention.sessions.session.details');
} catch(e) {
this.set('verifySessionModalError', true);
}
}).drop(),
});
|
Fix typo in previous commit
|
import Component from "@ember/component";
import { get, set } from "@ember/object";
import { next, scheduleOnce } from "@ember/runloop";
import layout from "./template.hbs";
import "./styles.less";
export default Component.extend({
layout,
error: false,
/* istanbul ignore next */
onLoad() {},
/* istanbul ignore next */
onError() {},
didInsertElement() {
this._super( ...arguments );
const setError = () => scheduleOnce( "afterRender", () => {
set( this, "error", true );
});
if ( !get( this, "src" ) ) {
return setError();
}
const img = this.element.querySelector( "img" );
const unbind = () => {
img.removeEventListener( "error", onError, false );
img.removeEventListener( "load", onLoad, false );
};
const onLoad = e => {
unbind();
next( () => this.onLoad( e ) );
};
const onError = e => {
unbind();
setError();
next( () => this.onError( e ) );
};
img.addEventListener( "error", onError, false );
img.addEventListener( "load", onLoad, false );
}
});
|
import Component from "@ember/component";
import { get, set } from "@ember/object";
import { next, scheduleOnce } from "@ember/runloop";
import layout from "./template.hbs";
import "./styles.less";
export default Component.extend({
layout,
error: false,
/* instanbul ignore next */
onLoad() {},
/* instanbul ignore next */
onError() {},
didInsertElement() {
this._super( ...arguments );
const setError = () => scheduleOnce( "afterRender", () => {
set( this, "error", true );
});
if ( !get( this, "src" ) ) {
return setError();
}
const img = this.element.querySelector( "img" );
const unbind = () => {
img.removeEventListener( "error", onError, false );
img.removeEventListener( "load", onLoad, false );
};
const onLoad = e => {
unbind();
next( () => this.onLoad( e ) );
};
const onError = e => {
unbind();
setError();
next( () => this.onError( e ) );
};
img.addEventListener( "error", onError, false );
img.addEventListener( "load", onLoad, false );
}
});
|
Allow code to be set in constructor
|
var util = require('util');
var assert = require('assert');
/**
* Add extend() method to Error type
*
* @param subTypeName
* @param errorCode [optional]
* @returns {SubType}
*/
Error.extend = function(subTypeName, errorCode /*optional*/) {
assert(subTypeName, 'subTypeName is required');
//define new error type
var SubType = (function(message, code) {
//handle constructor call without 'new'
if (! (this instanceof SubType)) {
return new SubType(message);
}
//populate error details
this.name = subTypeName;
this.code = code !== undefined ? code : errorCode;
this.message = message || '';
//include stack trace in error object
Error.captureStackTrace(this, this.constructor);
});
//inherit the base prototype chain
util.inherits(SubType, this);
//override the toString method to error type name and inspected message (to expand objects)
SubType.prototype.toString = function() {
return this.name + ': ' + util.inspect(this.message);
};
//attach extend() to the SubType to make it extendable further
SubType.extend = this.extend;
return SubType;
};
|
var util = require('util');
var assert = require('assert');
/**
* Add extend() method to Error type
*
* @param subTypeName
* @param errorCode [optional]
* @returns {SubType}
*/
Error.extend = function(subTypeName, errorCode /*optional*/) {
assert(subTypeName, 'subTypeName is required');
//define new error type
var SubType = (function(message) {
//handle constructor call without 'new'
if (! (this instanceof SubType)) {
return new SubType(message);
}
//populate error details
this.name = subTypeName;
this.code = errorCode;
this.message = message || '';
//include stack trace in error object
Error.captureStackTrace(this, this.constructor);
});
//inherit the base prototype chain
util.inherits(SubType, this);
//override the toString method to error type name and inspected message (to expand objects)
SubType.prototype.toString = function() {
return this.name + ': ' + util.inspect(this.message);
};
//attach extend() to the SubType to make it extendable further
SubType.extend = this.extend;
return SubType;
};
|
Update version to 0.1 -> 0.2
|
#!/usr/bin/env python
import io
from setuptools import setup, find_packages
with open('./README.md') as f:
readme = f.read()
setup(name='curwmysqladapter',
version='0.2',
description='MySQL Adapter for storing Weather Timeseries',
long_description=readme,
url='http://github.com/gihankarunarathne/CurwMySQLAdapter',
author='Gihan Karunarathne',
author_email='gckarunarathne@gmail.com',
license='Apache-2.0',
packages=['curwmysqladapter'],
install_requires=[
'PyMySQL',
],
test_suite='nose.collector',
tests_require=[
'nose',
'unittest2',
],
zip_safe=False
)
|
#!/usr/bin/env python
import io
from setuptools import setup, find_packages
with open('./README.md') as f:
readme = f.read()
setup(name='curwmysqladapter',
version='0.1',
description='MySQL Adapter for storing Weather Timeseries',
long_description=readme,
url='http://github.com/gihankarunarathne/CurwMySQLAdapter',
author='Gihan Karunarathne',
author_email='gckarunarathne@gmail.com',
license='Apache-2.0',
packages=['curwmysqladapter'],
install_requires=[
'PyMySQL',
],
test_suite='nose.collector',
tests_require=[
'nose',
'unittest2',
],
zip_safe=False
)
|
Add sample hook using sticky session variables
|
<?php
/**
* Hooks
*
* @author Gerry Demaret <gerry@tigron.be>
* @author Christophe Gosiau <christophe@tigron.be>
*/
class Hook_Admin {
/**
* Bootstrap the application
*
* @access private
*/
public static function bootstrap(\Skeleton\Core\Web\Module $module) {
// Bootsprap the application
// Example: check if we need to log in, if we do and we aren't, redirect
/*
if ($module->is_login_required()) {
if (!isset($_SESSION['user'])) {
\Skeleton\Core\Web\Session::destroy();
\Skeleton\Core\Web\Session::redirect('/login');
}
User::set($_SESSION['user']);
}
// Assign the sticky session object to our template
$template = \Skeleton\Core\Web\Template::get();
$sticky_session = new \Skeleton\Core\Web\Session\Sticky();
$template->add_environment('sticky_session', $sticky_session);
// This is entirely optional, the use cases for having access to the
// sticky session object in the module is are rather limited.
$module->sticky_session = $sticky_session;
// Clear the new session so we can start using it again
\Skeleton\Core\Web\Session::clear_sticky();
*/
}
/**
* Teardown of the application
*
* @access private
*/
public static function teardown(\Skeleton\Core\Web\Module $module) {
// Do your cleanup jobs here
}
}
|
<?php
/**
* Hooks
*
* @author Gerry Demaret <gerry@tigron.be>
* @author Christophe Gosiau <christophe@tigron.be>
*/
class Hook_Admin {
/**
* Bootstrap the application
*
* @access private
*/
public static function bootstrap(\Skeleton\Core\Web\Module $module) {
// Bootsprap the application
// Example: check if we need to log in, if we do and we aren't, redirect
/*
if ($module->is_login_required()) {
if (!isset($_SESSION['user'])) {
\Skeleton\Core\Web\Session::destroy();
\Skeleton\Core\Web\Session::redirect('/login');
}
User::set($_SESSION['user']);
}
*/
}
/**
* Teardown of the application
*
* @access private
*/
public static function teardown(\Skeleton\Core\Web\Module $module) {
// Do your cleanup jobs here
}
}
|
Add \Traversable typehint to phpdoc
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
interface DataMapperInterface
{
/**
* Maps properties of some data to a list of forms.
*
* @param mixed $data Structured data
* @param FormInterface[]|\Traversable $forms A list of {@link FormInterface} instances
*
* @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported.
*/
public function mapDataToForms($data, $forms);
/**
* Maps the data of a list of forms into the properties of some data.
*
* @param FormInterface[]|\Traversable $forms A list of {@link FormInterface} instances
* @param mixed $data Structured data
*
* @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported.
*/
public function mapFormsToData($forms, &$data);
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
interface DataMapperInterface
{
/**
* Maps properties of some data to a list of forms.
*
* @param mixed $data Structured data
* @param FormInterface[] $forms A list of {@link FormInterface} instances
*
* @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported.
*/
public function mapDataToForms($data, $forms);
/**
* Maps the data of a list of forms into the properties of some data.
*
* @param FormInterface[] $forms A list of {@link FormInterface} instances
* @param mixed $data Structured data
*
* @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported.
*/
public function mapFormsToData($forms, &$data);
}
|
tests: Make specific test files runnable
|
from __future__ import unicode_literals
import gc
import platform
import cffi
# Import the module so that ffi.verify() is run before cffi.verifier is used
import spotify # noqa
cffi.verifier.cleanup_tmpdir()
def buffer_writer(string):
"""Creates a function that takes a ``buffer`` and ``buffer_size`` as the
two last arguments and writes the given ``string`` to ``buffer``.
"""
def func(*args):
assert len(args) >= 2
buffer_, buffer_size = args[-2:]
# -1 to keep a char free for \0 terminating the string
length = min(len(string), buffer_size - 1)
# Due to Python 3 treating bytes as an array of ints, we have to
# encode and copy chars one by one.
for i in range(length):
buffer_[i] = string[i].encode('utf-8')
return len(string)
return func
def gc_collect():
"""Run enough GC collections to make object finalizers run."""
if platform.python_implementation() == 'PyPy':
# Since PyPy use garbage collection instead of reference counting
# objects are not finalized before the next major GC collection.
# Currently, the best way we have to ensure a major GC collection has
# run is to call gc.collect() a number of times.
[gc.collect() for _ in range(10)]
else:
gc.collect()
|
from __future__ import unicode_literals
import gc
import platform
import cffi
cffi.verifier.cleanup_tmpdir()
def buffer_writer(string):
"""Creates a function that takes a ``buffer`` and ``buffer_size`` as the
two last arguments and writes the given ``string`` to ``buffer``.
"""
def func(*args):
assert len(args) >= 2
buffer_, buffer_size = args[-2:]
# -1 to keep a char free for \0 terminating the string
length = min(len(string), buffer_size - 1)
# Due to Python 3 treating bytes as an array of ints, we have to
# encode and copy chars one by one.
for i in range(length):
buffer_[i] = string[i].encode('utf-8')
return len(string)
return func
def gc_collect():
"""Run enough GC collections to make object finalizers run."""
if platform.python_implementation() == 'PyPy':
# Since PyPy use garbage collection instead of reference counting
# objects are not finalized before the next major GC collection.
# Currently, the best way we have to ensure a major GC collection has
# run is to call gc.collect() a number of times.
[gc.collect() for _ in range(10)]
else:
gc.collect()
|
Clean up input text component
|
import React from 'react';
import DropdownList from 'react-widgets/lib/DropdownList';
import 'react-widgets/lib/scss/react-widgets.scss';
export const InputText = ({
input, label, type, icon, meta: { touched, error }, ...rest
}) => (
<div>
<i className="material-icons prefix">{ icon }</i>
<label className = "flow-text truncate active"> { label } </label>
<input {...input} type={type} onChange={input.onChange} { ...rest } />
{touched && error && <span className = "error flow-text"> {error} </span>}
</div>
);
export const renderDropdownList = ({
input, meta: { touched, error }, subjects, valueField, textField,
}) => (
<div>
<DropdownList { ...input } onChange={input.onChange} data={subjects}
valueField={valueField} textField={textField}/>
{touched && error && <span className = "error flow-text"> {error} </span>}
</div>
);
export const TextArea = ({
input, label, type, ...rest
}) => (
<div>
<label> { label } </label>
<textarea {...input} type={type} { ...rest } />
</div>
);
|
import React from 'react';
import DropdownList from 'react-widgets/lib/DropdownList';
import 'react-widgets/lib/scss/react-widgets.scss';
export const InputText = ({
input, label, type, defaultValue, icon, meta: { touched, error }, ...rest
}) => (
<div>
<i className="material-icons prefix">{ icon }</i>
<label className = "flow-text truncate"> { label } </label>
<input {...input} type={type} value= { defaultValue } { ...rest } />
{touched && error && <span className = "error flow-text"> {error} </span>}
</div>
);
export const renderDropdownList = ({
input, meta: { touched, error }, subjects, valueField, textField,
}) => (
<div>
<DropdownList { ...input } onChange={input.onChange} data={subjects}
valueField={valueField} textField={textField}/>
{touched && error && <span className = "error flow-text"> {error} </span>}
</div>
);
export const TextArea = ({
input, label, type, ...rest
}) => (
<div>
<label> { label } </label>
<textarea {...input} type={type} { ...rest } />
</div>
);
|
Make sure `didDestroyElement` hook is called
|
import { set } from 'ember-metal/property_set';
import Component from 'ember-views/components/component';
import { moduleFor, RenderingTest } from '../../utils/test-case';
moduleFor('Component willDestroyElement hook', class extends RenderingTest {
['@htmlbars it calls willDestroyElement when removed by if'](assert) {
let didInsertElementCount = 0;
let willDestroyElementCount = 0;
let FooBarComponent = Component.extend({
didInsertElement() {
didInsertElementCount++;
assert.notEqual(this.element.parentNode, null, 'precond component is in DOM');
},
willDestroyElement() {
willDestroyElementCount++;
assert.notEqual(this.element.parentNode, null, 'has not been removed from DOM yet');
}
});
this.registerComponent('foo-bar', { ComponentClass: FooBarComponent, template: 'hello' });
this.render('{{#if switch}}{{foo-bar}}{{/if}}', { switch: true });
assert.equal(didInsertElementCount, 1, 'didInsertElement was called once');
this.assertComponentElement(this.firstChild, { content: 'hello' });
this.runTask(() => set(this.context, 'switch', false));
assert.equal(willDestroyElementCount, 1, 'willDestroyElement was called once');
this.assertText('');
}
});
|
import { set } from 'ember-metal/property_set';
import Component from 'ember-views/components/component';
import { moduleFor, RenderingTest } from '../../utils/test-case';
moduleFor('Component willDestroyElement hook', class extends RenderingTest {
['@htmlbars it calls willDestroyElement when removed by if'](assert) {
let willDestroyElementCount = 0;
let FooBarComponent = Component.extend({
didInsertElement() {
assert.notEqual(this.element.parentNode, null, 'precond component is in DOM');
},
willDestroyElement() {
willDestroyElementCount++;
assert.notEqual(this.element.parentNode, null, 'has not been removed from DOM yet');
}
});
this.registerComponent('foo-bar', { ComponentClass: FooBarComponent, template: 'hello' });
this.render('{{#if switch}}{{foo-bar}}{{/if}}', { switch: true });
this.assertComponentElement(this.firstChild, { content: 'hello' });
this.runTask(() => set(this.context, 'switch', false));
assert.equal(willDestroyElementCount, 1, 'willDestroyElement was called once');
this.assertText('');
}
});
|
Fix hrose inventory open for 1.14+
|
package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_14r1_14r2;
import protocolsupport.protocol.ConnectionImpl;
import protocolsupport.protocol.packet.PacketType;
import protocolsupport.protocol.packet.middle.clientbound.play.MiddleInventoryHorseOpen;
import protocolsupport.protocol.packet.middleimpl.ClientBoundPacketData;
import protocolsupport.protocol.packet.middleimpl.IPacketData;
import protocolsupport.protocol.serializer.VarNumberSerializer;
import protocolsupport.utils.recyclable.RecyclableCollection;
import protocolsupport.utils.recyclable.RecyclableSingletonList;
public class InventoryHorseOpen extends MiddleInventoryHorseOpen {
public InventoryHorseOpen(ConnectionImpl connection) {
super(connection);
}
@Override
public RecyclableCollection<? extends IPacketData> toData() {
ClientBoundPacketData horseopen = ClientBoundPacketData.create(PacketType.CLIENTBOUND_PLAY_WINDOW_HORSE_OPEN);
horseopen.writeByte(windowId);
VarNumberSerializer.writeVarInt(horseopen, slots);
horseopen.writeInt(entityId);
return RecyclableSingletonList.create(horseopen);
}
}
|
package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_14r1_14r2;
import protocolsupport.protocol.ConnectionImpl;
import protocolsupport.protocol.packet.PacketType;
import protocolsupport.protocol.packet.middle.clientbound.play.MiddleInventoryHorseOpen;
import protocolsupport.protocol.packet.middleimpl.ClientBoundPacketData;
import protocolsupport.protocol.packet.middleimpl.IPacketData;
import protocolsupport.protocol.serializer.VarNumberSerializer;
import protocolsupport.utils.recyclable.RecyclableCollection;
import protocolsupport.utils.recyclable.RecyclableSingletonList;
public class InventoryHorseOpen extends MiddleInventoryHorseOpen {
public InventoryHorseOpen(ConnectionImpl connection) {
super(connection);
}
@Override
public RecyclableCollection<? extends IPacketData> toData() {
ClientBoundPacketData horseopen = ClientBoundPacketData.create(PacketType.CLIENTBOUND_PLAY_WINDOW_HORSE_OPEN);
horseopen.writeByte(windowId);
VarNumberSerializer.writeVarInt(horseopen, windowId);
horseopen.writeInt(entityId);
return RecyclableSingletonList.create(horseopen);
}
}
|
Update base 62 id after paste creation.
|
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from hashlib import md5
engine = create_engine("sqlite:///db/pastebin.db")
session = scoped_session(sessionmaker(bind = engine, autoflush = False))
Base = declarative_base(bind = engine)
def init_db():
"""
Creates the database schema. Import the models below to add them to the
schema generation.
Nothing happens when the database already exists.
"""
from mmmpaste.models import Paste
Base.metadata.create_all()
def nuke_db():
"""
Drop the bass.
"""
from mmmpaste.models import Paste
Base.metadata.drop_all()
def new_paste(content, filename = None):
from mmmpaste.models import Paste, Content
from mmmpaste.base62 import b62_encode
hash = md5(content).hexdigest()
dupe = session.query(Content).filter_by(hash = hash).first()
paste = Paste(content, filename)
if dupe is not None:
paste.content = dupe
session.add(paste)
session.commit()
paste.id_b62 = b62_encode(paste.id)
session.commit()
return paste.id_b62
def get_paste(id_b62):
from mmmpaste.models import Paste
return session.query(Paste).filter_by(id_b62 = id_b62).first()
|
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from hashlib import md5
engine = create_engine("sqlite:///db/pastebin.db")
session = scoped_session(sessionmaker(bind = engine, autoflush = False))
Base = declarative_base(bind = engine)
def init_db():
"""
Creates the database schema. Import the models below to add them to the
schema generation.
Nothing happens when the database already exists.
"""
from mmmpaste.models import Paste
Base.metadata.create_all()
def nuke_db():
"""
Drop the bass.
"""
from mmmpaste.models import Paste
Base.metadata.drop_all()
def new_paste(content, filename = None):
from mmmpaste.models import Paste, Content
hash = md5(content).hexdigest()
dupe = session.query(Content).filter_by(hash = hash).first()
paste = Paste(Content(content), filename)
if dupe is not None:
paste.content = dupe
session.add(paste)
session.commit()
def get_paste(id):
from mmmpaste.models import Paste
return session.query(Paste).filter_by(id = id).first()
|
Move CORS header setting into separate function
|
var _ = require('underscore')
, request = require('request')
, qs = require('querystring')
, express = require('express')
, app = express();
app.all('*', function (request, response, next) {
response.set({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'X-Requested-With'
});
});
app.get('/tag/:name', function (request, response) {
posts_for_tag(request.params.name, function (posts) {
response.json(posts);
});
});
function posts_for_tag (name, callback) {
var query = qs.stringify({
client_id: process.env.INSTAGRAM_CLIENT_ID
});
var url = 'https://api.instagram.com/v1/tags/' + name + '/media/recent?' + query;
request(url, function (error, response, body) {
var posts = JSON.parse(body).data;
var results = _(posts).map(function (post) {
return {
link: post.link,
image: post.images['standard_resolution'].url
};
});
callback(results);
});
}
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log("Listening on port " + port);
});
|
var _ = require('underscore')
, request = require('request')
, qs = require('querystring')
, express = require('express')
, app = express();
app.get('/tag/:name', function (request, response) {
response.set({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type, Authorization, Content-Length, X-Requested-With',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS'
});
posts_for_tag(request.params.name, function (posts) {
response.json(posts);
});
});
function posts_for_tag (name, callback) {
var query = qs.stringify({
count: 3,
client_id: process.env.INSTAGRAM_CLIENT_ID
});
var url = 'https://api.instagram.com/v1/tags/' + name + '/media/recent?' + query;
request(url, function (error, response, body) {
var posts = JSON.parse(body).data;
var results = _(posts).map(function (post) {
return {
link: post.link,
image: post.images['standard_resolution'].url
};
});
callback(results);
});
}
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log("Listening on port " + port);
});
|
Use StringBuilder instead of StringBuffer
|
package com.alibaba.fastjson.asm;
/**
* Created by wenshao on 05/08/2017.
*/
public class MethodCollector {
private final int paramCount;
private final int ignoreCount;
private int currentParameter;
private final StringBuilder result;
protected boolean debugInfoPresent;
protected MethodCollector(int ignoreCount, int paramCount) {
this.ignoreCount = ignoreCount;
this.paramCount = paramCount;
this.result = new StringBuilder();
this.currentParameter = 0;
// if there are 0 parameters, there is no need for debug info
this.debugInfoPresent = paramCount == 0;
}
protected void visitLocalVariable(String name, int index) {
if (index >= ignoreCount && index < ignoreCount + paramCount) {
if (!name.equals("arg" + currentParameter)) {
debugInfoPresent = true;
}
result.append(',');
result.append(name);
currentParameter++;
}
}
protected String getResult() {
return result.length() != 0 ? result.substring(1) : "";
}
}
|
package com.alibaba.fastjson.asm;
/**
* Created by wenshao on 05/08/2017.
*/
public class MethodCollector {
private final int paramCount;
private final int ignoreCount;
private int currentParameter;
private final StringBuffer result;
protected boolean debugInfoPresent;
protected MethodCollector(int ignoreCount, int paramCount) {
this.ignoreCount = ignoreCount;
this.paramCount = paramCount;
this.result = new StringBuffer();
this.currentParameter = 0;
// if there are 0 parameters, there is no need for debug info
this.debugInfoPresent = paramCount == 0;
}
protected void visitLocalVariable(String name, int index) {
if (index >= ignoreCount && index < ignoreCount + paramCount) {
if (!name.equals("arg" + currentParameter)) {
debugInfoPresent = true;
}
result.append(',');
result.append(name);
currentParameter++;
}
}
protected String getResult() {
return result.length() != 0 ? result.substring(1) : "";
}
}
|
Use version suffix instead of renaming
|
import sys
from setuptools import setup
extra = {}
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(name='mockito',
version='0.5.1-edgeware',
packages=['mockito', 'mockito_test', 'mockito_util'],
url='https://github.com/edgeware/mockito-python',
download_url='http://pypi.edgeware.tv/simple/mockito',
maintainer='Mockito Maintainers',
maintainer_email='mockito-python@googlegroups.com',
license='MIT',
description='Spying framework',
long_description=('Mockito is a spying framework based on Java library'
'with the same name.'),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Testing',
'Programming Language :: Python :: 2'
'Programming Language :: Python :: 3'
],
test_suite='nose.collector',
py_modules=['distribute_setup'],
setup_requires=['nose'],
**extra)
|
import sys
from setuptools import setup
extra = {}
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(name='mockito-edgeware',
version='1.0.0',
packages=['mockito', 'mockito_test', 'mockito_util'],
url='https://github.com/edgeware/mockito-python',
download_url='http://pypi.edgeware.tv/simple/mockito-edgeware',
maintainer='Mockito Maintainers',
maintainer_email='mockito-python@googlegroups.com',
license='MIT',
description='Spying framework',
long_description='Mockito is a spying framework based on Java library with the same name.',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Testing',
'Programming Language :: Python :: 2'
'Programming Language :: Python :: 3'
],
test_suite = 'nose.collector',
py_modules = ['distribute_setup'],
setup_requires = ['nose'],
**extra
)
|
Add console_scripts entry for python-pure-cdbdump
|
#!/usr/bin/env python
from os import environ
from setuptools import Extension, find_packages, setup
# Opt-in to building the C extensions for Python 2 by setting the
# ENABLE_DJB_HASH_CEXT environment variable
if environ.get('ENABLE_DJB_HASH_CEXT'):
ext_modules = [
Extension('cdblib._djb_hash', sources=['cdblib/_djb_hash.c']),
]
else:
ext_modules = []
description = "Pure Python reader/writer for Dan J. Berstein's CDB format."
setup(
author='David Wilson',
author_email='dw@botanicus.net',
description=description,
long_description=description,
download_url='https://github.com/dw/python-pure-cdb',
keywords='cdb file format appengine database db',
license='MIT',
name='pure-cdb',
version='2.1.0',
packages=find_packages(include=['cdblib']),
ext_modules=ext_modules,
install_requires=['six>=1.0.0,<2.0.0'],
test_suite='tests',
tests_require=['flake8'],
entry_points={
'console_scripts': [
'python-pure-cdbmake=cdblib.cdbmake:main',
'python-pure-cdbdump=cdblib.cdbdump:main',
],
},
)
|
#!/usr/bin/env python
from os import environ
from setuptools import Extension, find_packages, setup
# Opt-in to building the C extensions for Python 2 by setting the
# ENABLE_DJB_HASH_CEXT environment variable
if environ.get('ENABLE_DJB_HASH_CEXT'):
ext_modules = [
Extension('cdblib._djb_hash', sources=['cdblib/_djb_hash.c']),
]
else:
ext_modules = []
description = "Pure Python reader/writer for Dan J. Berstein's CDB format."
setup(
author='David Wilson',
author_email='dw@botanicus.net',
description=description,
long_description=description,
download_url='https://github.com/dw/python-pure-cdb',
keywords='cdb file format appengine database db',
license='MIT',
name='pure-cdb',
version='2.1.0',
packages=find_packages(include=['cdblib']),
ext_modules=ext_modules,
install_requires=['six>=1.0.0,<2.0.0'],
test_suite='tests',
tests_require=['flake8'],
entry_points={
'console_scripts': ['python-pure-cdbmake=cdblib.cdbmake:main'],
},
)
|
Add Windows Phone to 'mobile' variable
|
VK = {};
VK.requestCredential = function (options, credentialRequestCompleteCallback) {
if (!credentialRequestCompleteCallback && typeof options === 'function') {
credentialRequestCompleteCallback = options;
options = {};
}
var config = ServiceConfiguration.configurations.findOne({service: 'vk'});
if (!config) {
credentialRequestCompleteCallback && credentialRequestCompleteCallback(new ServiceConfiguration.ConfigError("Service not configured"));
return;
}
var credentialToken = Random.id();
var mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i.test(navigator.userAgent);
var display = mobile ? 'touch' : 'popup';
var scope = '';
if (options && options.requestPermissions) {
scope = options.requestPermissions.join(',');
}
var loginUrl =
'https://oauth.vk.com/authorize' +
'?client_id=' + config.appId +
'&scope=' + scope +
'&redirect_uri=' + Meteor.absoluteUrl('_oauth/vk?close=close', {replaceLocalhost: false}) +
'&response_type=code' +
'&display=' + display +
'&state=' + credentialToken;
Oauth.initiateLogin(credentialToken, loginUrl, credentialRequestCompleteCallback);
};
|
VK = {};
VK.requestCredential = function (options, credentialRequestCompleteCallback) {
if (!credentialRequestCompleteCallback && typeof options === 'function') {
credentialRequestCompleteCallback = options;
options = {};
}
var config = ServiceConfiguration.configurations.findOne({service: 'vk'});
if (!config) {
credentialRequestCompleteCallback && credentialRequestCompleteCallback(new ServiceConfiguration.ConfigError("Service not configured"));
return;
}
var credentialToken = Random.id();
var mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
var display = mobile ? 'touch' : 'popup';
var scope = '';
if (options && options.requestPermissions) {
scope = options.requestPermissions.join(',');
}
var loginUrl =
'https://oauth.vk.com/authorize' +
'?client_id=' + config.appId +
'&scope=' + scope +
'&redirect_uri=' + Meteor.absoluteUrl('_oauth/vk?close=close', {replaceLocalhost: false}) +
'&response_type=code' +
'&display=' + display +
'&state=' + credentialToken;
Oauth.initiateLogin(credentialToken, loginUrl, credentialRequestCompleteCallback);
};
|
Remove the unneeded lodash require
|
const syrup = require('../../');
syrup.scenario('array', `${__dirname}/test-array`);
syrup.scenario('object', `${__dirname}/test-object`);
syrup.scenario('save', `${__dirname}/test-save`);
syrup.scenario('get', `${__dirname}/test-get`, ['save']);
syrup.pour(function (error, results) {
console.log(JSON.stringify(results));
}, function (error, results) {
// Do something with the progress update
// Results Example:
//
// {
// array: 'done',
// object: 'done',
// save: 'done',
// get: 'pending'
// }
});
|
const syrup = require('../../');
const _ = require('lodash');
syrup.scenario('array', `${__dirname}/test-array`);
syrup.scenario('object', `${__dirname}/test-object`);
syrup.scenario('save', `${__dirname}/test-save`);
syrup.scenario('get', `${__dirname}/test-get`, ['save']);
syrup.pour(function (error, results) {
console.log(JSON.stringify(results));
}, function (error, results) {
// Do something with the progress update
// Results Example:
//
// {
// array: 'done',
// object: 'done',
// save: 'done',
// get: 'pending'
// }
});
|
Add api endpoint to delete portion
|
'use strict';
const passport = require('passport');
const main = require('../app/controllers/main');
const api = require('../app/controllers/api');
const auth = require('../app/controllers/auth');
/**
* Expose routes
*/
module.exports = function applyRoutes(app) {
app.get('/', main.index);
app.post('/auth/token', auth.token);
app.post('/auth/google-oauth2', auth.google.callback);
app.get('/:type(orders|accounts|portions|vendors)', passport.authenticate('jwt'), api);
app.get('/:type(orders|accounts|portions|vendors)/:id', passport.authenticate('jwt'), api);
app.patch('/:type(orders|portions)/:id', passport.authenticate('jwt'), api);
app.delete('/:type(portions)/:id', passport.authenticate('jwt'), api);
app.post('/:type(orders|portions|vendors)', passport.authenticate('jwt'), api);
app.post('/:type(accounts)', api);
app.patch('/:type(accounts)/:id', passport.authenticate('jwt'), api);
};
|
'use strict';
const passport = require('passport');
const main = require('../app/controllers/main');
const api = require('../app/controllers/api');
const auth = require('../app/controllers/auth');
/**
* Expose routes
*/
module.exports = function applyRoutes(app) {
app.get('/', main.index);
app.post('/auth/token', auth.token);
app.post('/auth/google-oauth2', auth.google.callback);
app.get('/:type(orders|accounts|portions|vendors)', passport.authenticate('jwt'), api);
app.get('/:type(orders|accounts|portions|vendors)/:id', passport.authenticate('jwt'), api);
app.patch('/:type(orders|portions)/:id', passport.authenticate('jwt'), api);
app.post('/:type(orders|portions|vendors)', passport.authenticate('jwt'), api);
app.post('/:type(accounts)', api);
app.patch('/:type(accounts)/:id', passport.authenticate('jwt'), api);
};
|
Clean up events bound on window, otherwise this will induce a memory leak.
|
var spyCallbacks = [];
var spySetState = [];
var currentPositionY = function() {
var supportPageOffset = window.pageXOffset !== undefined;
var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
return supportPageOffset ? window.pageYOffset : isCSS1Compat ?
document.documentElement.scrollTop : document.body.scrollTop;
};
var scrollHandler = function() {
for(var i = 0; i < spyCallbacks.length; i = i + 1) {
spyCallbacks[i](currentPositionY());
}
};
if (typeof document !== 'undefined') {
document.addEventListener('scroll', scrollHandler);
}
module.exports = {
unmount: function(){
document.removeEventListener('scroll', scrollHandler);
spySetState = [];
spyCallbacks = [];
},
addStateHandler: function(handler){
spySetState.push(handler);
},
addSpyHandler: function(handler){
spyCallbacks.push(handler);
},
updateStates: function(){
var length = spySetState.length;
for(var i = 0; i < length; i = i + 1) {
spySetState[i]();
}
}
};
|
var spyCallbacks = [];
var spySetState = [];
var currentPositionY = function() {
var supportPageOffset = window.pageXOffset !== undefined;
var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
return supportPageOffset ? window.pageYOffset : isCSS1Compat ?
document.documentElement.scrollTop : document.body.scrollTop;
};
if (typeof document !== 'undefined') {
document.addEventListener('scroll', function() {
for(var i = 0; i < spyCallbacks.length; i = i + 1) {
spyCallbacks[i](currentPositionY());
}
});
}
module.exports = {
unmount: function(){
spySetState = [];
spyCallbacks = [];
},
addStateHandler: function(handler){
spySetState.push(handler);
},
addSpyHandler: function(handler){
spyCallbacks.push(handler);
},
updateStates: function(){
var length = spySetState.length;
for(var i = 0; i < length; i = i + 1) {
spySetState[i]();
}
}
};
|
Add argument parsing to customize input file
|
package main
import (
"fmt"
"flag"
)
const (
MaxRedirects = 10
)
func main() {
flag.Parse()
filename := flag.Arg(0)
if filename == "" {
filename = "301s.csv"
}
redirects := ReadCsv(filename)
log := make([]redirectResult, 0)
for _, info := range redirects {
result := CheckUrl(info)
log = append(log, result)
}
for _, logItem := range log {
if logItem.FinalUrl == logItem.ExpectedUrl {
fmt.Printf("OK: %v Matched\n", logItem.Url)
continue
}
if logItem.LooksLikeRedirectLoop() {
fmt.Printf("LOOP: %v Redirect Loop? Stopped after %v redirects\n", logItem.Url, logItem.Redirects)
continue
}
fmt.Printf("ERR: %v Unexpected destination: %v\n", logItem.Url, logItem.FinalUrl)
}
}
|
package main
import (
"fmt"
)
const (
MaxRedirects = 10
)
func main() {
redirects := ReadCsv("301s.csv")
log := make([]redirectResult, 0)
for _, info := range redirects {
result := CheckUrl(info)
log = append(log, result)
}
for _, logItem := range log {
if logItem.FinalUrl == logItem.ExpectedUrl {
fmt.Printf("OK: %v Matched\n", logItem.Url)
continue
}
if logItem.LooksLikeRedirectLoop() {
fmt.Printf("LOOP: %v Redirect Loop? Stopped after %v redirects\n", logItem.Url, logItem.Redirects)
continue
}
fmt.Printf("ERR: %v Unexpected destination: %v\n", logItem.Url, logItem.FinalUrl)
}
}
|
Add PYTHON_ARGCOMPLETE_OK to enable completion for argcomplete users
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# PYTHON_ARGCOMPLETE_OK
import argh
import argparse
from cr8 import __version__
from cr8.timeit import timeit
from cr8.insert_json import insert_json
from cr8.insert_fake_data import insert_fake_data
from cr8.insert_blob import insert_blob
from cr8.run_spec import run_spec
from cr8.run_crate import run_crate
from cr8.run_track import run_track
def main():
p = argh.ArghParser(
prog='cr8', formatter_class=argparse.RawTextHelpFormatter)
p.add_argument(
'--version', action='version', version="%(prog)s " + __version__)
p.add_commands([timeit,
insert_json,
insert_fake_data,
insert_blob,
run_spec,
run_crate,
run_track])
p.dispatch()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argh
import argparse
from cr8 import __version__
from cr8.timeit import timeit
from cr8.insert_json import insert_json
from cr8.insert_fake_data import insert_fake_data
from cr8.insert_blob import insert_blob
from cr8.run_spec import run_spec
from cr8.run_crate import run_crate
from cr8.run_track import run_track
def main():
p = argh.ArghParser(
prog='cr8', formatter_class=argparse.RawTextHelpFormatter)
p.add_argument(
'--version', action='version', version="%(prog)s " + __version__)
p.add_commands([timeit,
insert_json,
insert_fake_data,
insert_blob,
run_spec,
run_crate,
run_track])
p.dispatch()
if __name__ == '__main__':
main()
|
Update Twig filters and extension
Hello,
I just updated this file to be compatible with Symfony 5.
The twig filters and extensions were deprecated.
Cheers 😉
|
<?php
namespace Knp\Bundle\MarkdownBundle\Twig\Extension;
use Knp\Bundle\MarkdownBundle\Parser\ParserManager;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class MarkdownTwigExtension extends AbstractExtension
{
private $parserManager;
public function __construct(ParserManager $parserManager)
{
$this->parserManager = $parserManager;
}
public function getFilters()
{
return array(
new TwigFilter('markdown', array($this, 'markdown'), array('is_safe' => array('html'))),
);
}
public function markdown($text, $parser = null)
{
return $this->parserManager->transform($text, $parser);
}
public function getName()
{
return 'markdown';
}
}
|
<?php
namespace Knp\Bundle\MarkdownBundle\Twig\Extension;
use Knp\Bundle\MarkdownBundle\Parser\ParserManager;
class MarkdownTwigExtension extends \Twig_Extension
{
private $parserManager;
public function __construct(ParserManager $parserManager)
{
$this->parserManager = $parserManager;
}
public function getFilters()
{
return array(
new \Twig_SimpleFilter('markdown', array($this, 'markdown'), array('is_safe' => array('html'))),
);
}
public function markdown($text, $parser = null)
{
return $this->parserManager->transform($text, $parser);
}
public function getName()
{
return 'markdown';
}
}
|
Agentctl2: Rename CLI command to vppcli
Signed-off-by: Andrej Kozemcak <806670a1cb1f0508258ef96648425f1247742d81@pantheon.tech>
|
package cmd
import (
"fmt"
"os"
"github.com/ligato/vpp-agent/cmd/agentctl2/restapi"
"github.com/spf13/cobra"
)
// RootCmd represents the base command when called without any subcommands.
var cliConfig = &cobra.Command{
Use: "vppcli",
Short: "CLI command for VPP",
Long: `
Run CLI command for VPP
`,
Args: cobra.MinimumNArgs(1),
Run: cliFunction,
}
func init() {
RootCmd.AddCommand(cliConfig)
}
func cliFunction(cmd *cobra.Command, args []string) {
var cli string
for _, str := range args {
cli = cli + " " + str
}
msg := fmt.Sprintf("{\"vppclicommand\":\"%v\"}", cli)
fmt.Fprintf(os.Stdout, "%s\n", msg)
resp := restapi.PostMsg(globalFlags.Endpoints, "/vpp/command", msg)
//TODO: Need format
fmt.Fprintf(os.Stdout, "%s\n", resp)
}
|
package cmd
import (
"fmt"
"os"
"github.com/ligato/vpp-agent/cmd/agentctl2/restapi"
"github.com/spf13/cobra"
)
// RootCmd represents the base command when called without any subcommands.
var cliConfig = &cobra.Command{
Use: "cli",
Aliases: []string{"c"},
Short: "CLI command for VPP",
Long: `
Run CLI command for VPP
`,
Args: cobra.MinimumNArgs(1),
Run: cliFunction,
}
func init() {
RootCmd.AddCommand(cliConfig)
}
func cliFunction(cmd *cobra.Command, args []string) {
var cli string
for _, str := range args {
cli = cli + " " + str
}
msg := fmt.Sprintf("{\"vppclicommand\":\"%v\"}", cli)
fmt.Fprintf(os.Stdout, "%s\n", msg)
resp := restapi.PostMsg(globalFlags.Endpoints, "/vpp/command", msg)
//TODO: Need format
fmt.Fprintf(os.Stdout, "%s\n", resp)
}
|
Fix flow error on reducer
|
// @flow
import {GameStage} from '../../game-stage'
import {computeScores} from './compute-scores'
import {toEndedState} from './converter'
import {bidWinGenerator} from './bid-win-generator'
import {toFront} from '../../utils'
import type {GameState, WaitingBidState, WaitingWinState} from './types'
import type {WIN_ACTION} from '../../actions/current-game'
/**
* Handler for WIN action
*/
export function winHandler(state: WaitingBidState | WaitingWinState, action: WIN_ACTION): GameState {
if (state.stage === GameStage.waitingBid) {
return state
}
const win = action.win || state.win
if (state.rounds === state.currentRound) {
// Last round
const newState = toEndedState(state, action.time)
return {
...newState,
scores: computeScores(state.bid, win, state.scores)
}
} else {
const newState: WaitingBidState = {
...state,
stage: GameStage.waitingBid,
bid: bidWinGenerator(Object.keys(state.names)),
currentRound: state.currentRound + 1,
currentPlayerOrder: toFront(state.currentPlayerOrder, 1),
scores: computeScores(state.bid, win, state.scores)
}
delete (newState: any).win
return newState
}
}
|
// @flow
import {GameStage} from '../../game-stage'
import {computeScores} from './compute-scores'
import {toEndedState} from './converter'
import {bidWinGenerator} from './bid-win-generator'
import {toFront} from '../../utils'
import type {GameState, WaitingBidState, WaitingWinState} from './types'
import type {WIN_ACTION} from '../../actions/current-game'
/**
* Handler for WIN action
*/
export function winHandler(state: WaitingBidState | WaitingWinState, action: WIN_ACTION): GameState {
if (state.stage === GameStage.waitingBid) {
return state
}
const win = action.win || state.win
if (state.rounds === state.currentRound) {
// Last round
const newState: WaitingWinState = {
...state,
scores: computeScores(state.bid, win, state.scores)
}
return toEndedState(newState, action.time)
} else {
const newState: WaitingBidState = {
...state,
stage: GameStage.waitingBid,
bid: bidWinGenerator(Object.keys(state.names)),
currentRound: state.currentRound + 1,
currentPlayerOrder: toFront(state.currentPlayerOrder, 1),
scores: computeScores(state.bid, win, state.scores)
}
delete (newState: any).win
return newState
}
}
|
Make Kureev happy with currying
|
const path = require('path');
const flatten = require('lodash.flatten');
/**
* Filter dependencies by name pattern
* @param {String} dependency Name of the dependency
* @return {Boolean} If dependency is a rnpm plugin
*/
const isPlugin = (dependency) => !!~dependency.indexOf('rnpm-plugin-');
/**
* Get default actions from rnpm's package.json
* @type {Array}
*/
const getActions = (cwd) => {
const pjson = require(path.join(cwd, 'package.json'));
return flatten(
Object.keys(pjson.dependencies || {}),
Object.keys(pjson.devDependencies || {})
)
.filter(isPlugin)
.map(getPluginConfig(cwd));
};
/**
* Get plugin config
* @param {String} name Name of the plugin
* @return {Object} Plugin's config
*/
const getPluginConfig = cwd => name =>
require(path.join(cwd, 'node_modules', name));
/**
* Compose a list of dependencies from default actions,
* package's dependencies & devDependencies
* @type {Array}
*/
const pluginsList = flatten([
getActions(path.join(__dirname, '..')),
getActions(process.cwd())
]);
module.exports = () => pluginsList;
|
const path = require('path');
const flatten = require('lodash.flatten');
/**
* Filter dependencies by name pattern
* @param {String} dependency Name of the dependency
* @return {Boolean} If dependency is a rnpm plugin
*/
const isPlugin = (dependency) => !!~dependency.indexOf('rnpm-plugin-');
/**
* Get default actions from rnpm's package.json
* @type {Array}
*/
const getActions = (cwd) => {
const pjson = require(path.join(cwd, 'package.json'));
return flatten(
Object.keys(pjson.dependencies || {}),
Object.keys(pjson.devDependencies || {})
)
.filter(isPlugin)
.map(name => getPluginConfig(cwd, name));
};
/**
* Get plugin config
* @param {String} name Name of the plugin
* @return {Object} Plugin's config
*/
const getPluginConfig = (cwd, name) =>
require(path.join(cwd, 'node_modules', name));
/**
* Compose a list of dependencies from default actions,
* package's dependencies & devDependencies
* @type {Array}
*/
const pluginsList = flatten([
getActions(path.join(__dirname, '..')),
getActions(process.cwd())
]);
module.exports = () => pluginsList;
|
Add security when converting milliseconds to time to avoid NaN
|
(function(app){
"use strict"
/**
* Creates a filter to convert a time in milliseconds to
* an hours:minutes:seconds format.
*
* e.g.
* {{60000 | millisecondsToTime}} // 01:00
* {{3600000 | millisecondsToTime}} // 01:00:00
*/
app.filter("millisecondsToTime", MillisecondsToTime);
function MillisecondsToTime(){
return function(time){
if(time < 0 || isNaN(time))
return "";
var seconds = parseInt((time / 1000) % 60);
var minutes = parseInt((time / (60000)) % 60);
var hours = parseInt((time / (3600000)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return ((hours !== "00") ? hours + ":" : "") + minutes + ":" + seconds;
}
};
})(angular.module("ov.player"));
|
(function(app){
"use strict"
/**
* Creates a filter to convert a time in milliseconds to
* an hours:minutes:seconds format.
*
* e.g.
* {{60000 | millisecondsToTime}} // 01:00
* {{3600000 | millisecondsToTime}} // 01:00:00
*/
app.filter("millisecondsToTime", MillisecondsToTime);
function MillisecondsToTime(){
return function(time){
if(time < 0)
return "";
var seconds = parseInt((time / 1000) % 60);
var minutes = parseInt((time / (60000)) % 60);
var hours = parseInt((time / (3600000)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return ((hours !== "00") ? hours + ":" : "") + minutes + ":" + seconds;
}
};
})(angular.module("ov.player"));
|
Add "pictures" and "videos" tables
|
<?php
/**
* @author Pierre-Henry Soria <hello@ph7cms.com>
* @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / Include / Class
*/
namespace PH7;
class DbTableName
{
const ADMIN = 'admins';
const MEMBER = 'members';
const MEMBERSHIP = 'memberships';
const AFFILIATE = 'affiliates';
const SUBSCRIBER = 'subscribers';
const MEMBER_INFO = 'members_info';
const AFFILIATE_INFO = 'affiliates_info';
const MEMBER_PRIVACY = 'members_privacy';
const MEMBER_NOTIFICATION = 'members_notifications';
const BLOCK_IP = 'block_ip';
const AD = 'ads';
const AD_AFFILIATE = 'ads_affiliates';
const PICTURE = 'pictures';
const VIDEO = 'videos';
const ALBUM_PICTURE = 'albums_pictures';
const ALBUM_VIDEO = 'albums_videos';
const USER_TABLES = [
self::ADMIN,
self::MEMBER,
self::AFFILIATE
];
}
|
<?php
/**
* @author Pierre-Henry Soria <hello@ph7cms.com>
* @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / Include / Class
*/
namespace PH7;
class DbTableName
{
const ADMIN = 'admins';
const MEMBER = 'members';
const MEMBERSHIP = 'memberships';
const AFFILIATE = 'affiliates';
const SUBSCRIBER = 'subscribers';
const MEMBER_INFO = 'members_info';
const AFFILIATE_INFO = 'affiliates_info';
const MEMBER_PRIVACY = 'members_privacy';
const MEMBER_NOTIFICATION = 'members_notifications';
const BLOCK_IP = 'block_ip';
const AD = 'ads';
const AD_AFFILIATE = 'ads_affiliates';
const ALBUM_PICTURE = 'albums_pictures';
const ALBUM_VIDEO = 'albums_videos';
const USER_TABLES = [
self::ADMIN,
self::MEMBER,
self::AFFILIATE
];
}
|
Add fallback in update method
|
myApp.service('breadCrumbService', function($location) {
this.crumbs = [
];
this.current = {
path: './',
display:'Inventories'
};
this.update = function(crumb) {
console.log("Updating crumbs:", crumb);
if(this.current.path === crumb.path || crumb.path === '/')
return;
var index = 0;
if(crumb.path) {
index = this.crumbs.findIndex(function(c) {
return c.path === crumb.path;
});
}
if(index == -1) {
this.crumbs.push(this.current);
this.current = crumb;
}
else {
this.current = this.crumbs[index] || this.current;
this.crumbs = this.crumbs.slice(0, index);
}
};
this.get = function(i) {
var index = i || 0;
return this.crumbs[index];
};
});
|
myApp.service('breadCrumbService', function($location) {
this.crumbs = [
];
this.current = {
path: './',
display:'Inventories'
};
this.update = function(crumb) {
console.log("Updating crumbs:", crumb);
if(this.current.path === crumb.path || crumb.path === '/')
return;
var index = 0;
if(crumb.path) {
index = this.crumbs.findIndex(function(c) {
return c.path === crumb.path;
});
}
if(index == -1) {
this.crumbs.push(this.current);
this.current = crumb;
}
else {
this.current = this.crumbs[index];
this.crumbs = this.crumbs.slice(0, index);
}
};
this.get = function(i) {
var index = i || 0;
return this.crumbs[index];
};
});
|
Move willTransition to action to fix
|
/**
Undo changes in the store made to an existing but not-saved
model. This should be mixed into 'edit' routes like
`CampaignEditRoute` and `BusinessEditRoute`. All non-persisted
changes to the model are undone.
@class DireyRecordHandler
@submodule mixins
*/
import Ember from 'ember';
import defaultFor from 'ember-easy-form-extensions/utils/default-for';
const { on } = Ember;
export default Ember.Mixin.create({
/**
If the model `isDirty` (i.e. some data has been temporarily
changed) rollback the record to the most recent clean version
in the store. If there is no clean version in the store,
delete the record.
TODO - add ability to stop transition and ask for transition confirm
@method rollbackifDirty
*/
actions: {
willTransition() {
const model = this.get('controller.model');
if (model && model.get('hasDirtyAttributes')) {
if (model.get('id')) {
model.rollbackAttributes();
} else {
model.deleteRecord();
}
}
return true;
}
},
});
|
/**
Undo changes in the store made to an existing but not-saved
model. This should be mixed into 'edit' routes like
`CampaignEditRoute` and `BusinessEditRoute`. All non-persisted
changes to the model are undone.
@class DireyRecordHandler
@submodule mixins
*/
import Ember from 'ember';
import defaultFor from 'ember-easy-form-extensions/utils/default-for';
const { on } = Ember;
export default Ember.Mixin.create({
/**
If the model `isDirty` (i.e. some data has been temporarily
changed) rollback the record to the most recent clean version
in the store. If there is no clean version in the store,
delete the record.
TODO - add ability to stop transition and ask for transition confirm
@method rollbackifDirty
*/
rollbackIfDirty: on('willTransition', function(model) {
model = defaultFor(model, this.get('controller.model'));
if (model.get('isDirty')) {
if (model.get('id')) {
model.rollback();
} else {
model.deleteRecord();
}
}
}),
});
|
Add browse sections to front page
By correspondent, location, decade
|
<?php
get_header(); ?>
<div id="splash" class="hero-area">
<div class="site-hero-title">
<h1 class="site-main-title"><span>Katherine</span> <span>Anne</span> <span>Porter</span></h1>
<span class="site-sub-title">correspondence</span>
</div><!-- .site-hero-title -->
</div><!-- .hero-area -->
<div id="primary" class="content-area">
<section class="site-about-teaser">
<div class="site-call-to-action">
<p class="intro">The University of Maryland Libraries are pleased to be
able to share over 5,000 pages of digitized materials granting
unprecedented access to the ideas, attitudes, and experiences of a
distinguished 20th century American writer.
</p>
<a href="introduction" class="btn main-action-button">Read More</a>
</div>
</section><!-- .site-call-to-action -->
<hr />
<div class="browse-options">
<section class="browse-teaser">
<h2><small>Browse by</small> Correspondent</h2>
</section>
<section class="browse-teaser">
<h2><small>Browse by</small> Location</h2>
</section>
<section class="browse-teaser">
<h2><small>Browse by</small> Decade</h2>
</section>
</div><!-- .browse-options -->
</div><!-- .content-area -->
<?php get_footer(); ?>
|
<?php
get_header(); ?>
<div id="splash" class="hero-area">
<div class="site-hero-title">
<h1 class="site-main-title"><span>Katherine</span> <span>Anne</span> <span>Porter</span></h1>
<span class="site-sub-title">correspondence</span>
</div><!-- .site-hero-title -->
</div><!-- .hero-area -->
<div id="primary" class="content-area">
<section class="site-about-teaser">
<div class="site-call-to-action">
<p class="intro">The University of Maryland Libraries are pleased to be
able to share over 5,000 pages of digitized materials granting
unprecedented access to the ideas, attitudes, and experiences of a
distinguished 20th century American writer.
</p>
<a href="introduction" class="btn main-action-button">Read More</a>
</div>
</section><!-- .site-call-to-action -->
</div><!-- .content-area -->
<?php get_footer(); ?>
|
Remove alias from service provider.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<?php namespace Orchestra\Resources;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
class ResourcesServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var boolean
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('orchestra.resources', function ($app) {
$dispatcher = new Dispatcher($app, $app['router'], $app['request']);
$response = new Response($app);
return new Environment($app, $dispatcher, $response);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('orchestra.resources');
}
}
|
<?php namespace Orchestra\Resources;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
class ResourcesServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var boolean
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('orchestra.resources', function ($app) {
$dispatcher = new Dispatcher($app, $app['router'], $app['request']);
$response = new Response($app);
return new Environment($app, $dispatcher, $response);
});
$this->app->booting(function () {
$loader = AliasLoader::getInstance();
$loader->alias('Orchestra\Resources', 'Orchestra\Support\Facades\Resources');
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('orchestra.resources');
}
}
|
Use integer distances to avoid so many events.
|
import threading
import time
class SensorThread(object):
def __init__(self, notify, delay=0):
self.notify = notify
self.delay = delay
self.interval = 1
self.distance = -1
def start(self, robot):
self.robot = robot
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
while True:
distance = int(self.robot.distance())
if not self.distance == distance:
self.notify.emit('sense', distance)
self.distance = distance
print "distance %scm" % distance
time.sleep(self.interval)
|
import threading
import time
class SensorThread(object):
def __init__(self, notify, delay=0):
self.notify = notify
self.delay = delay
self.interval = 1
self.distance = -1
def start(self, robot):
self.robot = robot
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
while True:
distance = self.robot.distance()
if not self.distance == distance:
self.notify.emit('sense', distance)
self.distance = distance
print "distance %scm" % distance
time.sleep(self.interval)
|
Replace YellowBox references with LogBox
Summary:
This diff replaces some YellowBox references with LogBox so we can remove it.
Changelog: [Internal]
Reviewed By: motiz88
Differential Revision: D19948126
fbshipit-source-id: b26ad1b78d86a8290f7e08396e4a8314fef7a9f3
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const invariant = require('invariant');
const levelsMap = {
log: 'log',
info: 'info',
warn: 'warn',
error: 'error',
fatal: 'error',
};
let warningHandler: ?(Array<any>) => void = null;
const RCTLog = {
// level one of log, info, warn, error, mustfix
logIfNoNativeHook(level: string, ...args: Array<any>): void {
// We already printed in the native console, so only log here if using a js debugger
if (typeof global.nativeLoggingHook === 'undefined') {
RCTLog.logToConsole(level, ...args);
} else {
// Report native warnings to LogBox
if (warningHandler && level === 'warn') {
warningHandler(...args);
}
}
},
// Log to console regardless of nativeLoggingHook
logToConsole(level: string, ...args: Array<any>): void {
const logFn = levelsMap[level];
invariant(
logFn,
'Level "' + level + '" not one of ' + Object.keys(levelsMap).toString(),
);
console[logFn](...args);
},
setWarningHandler(handler: typeof warningHandler): void {
warningHandler = handler;
},
};
module.exports = RCTLog;
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const invariant = require('invariant');
const levelsMap = {
log: 'log',
info: 'info',
warn: 'warn',
error: 'error',
fatal: 'error',
};
let warningHandler: ?(Array<any>) => void = null;
const RCTLog = {
// level one of log, info, warn, error, mustfix
logIfNoNativeHook(level: string, ...args: Array<any>): void {
// We already printed in the native console, so only log here if using a js debugger
if (typeof global.nativeLoggingHook === 'undefined') {
RCTLog.logToConsole(level, ...args);
} else {
// Report native warnings to YellowBox
if (warningHandler && level === 'warn') {
warningHandler(...args);
}
}
},
// Log to console regardless of nativeLoggingHook
logToConsole(level: string, ...args: Array<any>): void {
const logFn = levelsMap[level];
invariant(
logFn,
'Level "' + level + '" not one of ' + Object.keys(levelsMap).toString(),
);
console[logFn](...args);
},
setWarningHandler(handler: typeof warningHandler): void {
warningHandler = handler;
},
};
module.exports = RCTLog;
|
Add test for multiline object destructing
|
/* eslint-disable */
// input: property access
a['a'];
a[a];
a[b()];
a[b[c[0]]];
'abc'[1];
// output:
a['a'];
a[a];
a[b()];
a[b[c[0]]];
'abc'[1];
// input: declaration
// config: {"max-len": 30}
let a = {
b: function() {
return c;
},
c: a.b.c.d.e.f,
d: 1,
e: 'abc',
f: this,
[a]: undefined
};
// output:
let a = {
b: function() {
return c;
},
c: a.b.c.d.e.f,
d: 1,
e: 'abc',
f: this,
[a]: undefined
};
// input: destructuring
let a = {b, c, d};
// output:
let a = {b, c, d};
// input: multiline destructuring
// config: {"max-len": 30}
let a = {
aaaaaaaaaa,
bbbbbbbbbb,
dddddddddd
};
// output:
let a = {
aaaaaaaaaa,
bbbbbbbbbb,
dddddddddd
};
// input: one line objects
let a = {a: 1, b: 2};
// output:
let a = {a: 1, b: 2};
|
/* eslint-disable */
// input: property access
a['a'];
a[a];
a[b()];
a[b[c[0]]];
'abc'[1];
// output:
a['a'];
a[a];
a[b()];
a[b[c[0]]];
'abc'[1];
// input: declaration
// config: {"max-len": 30}
let a = {
b: function() {
return c;
},
c: a.b.c.d.e.f,
d: 1,
e: 'abc',
f: this,
[a]: undefined
};
// output:
let a = {
b: function() {
return c;
},
c: a.b.c.d.e.f,
d: 1,
e: 'abc',
f: this,
[a]: undefined
};
// input: destructuring
let a = {b, c, d};
// output:
let a = {b, c, d};
// input: one line objects
let a = {a: 1, b: 2};
// output:
let a = {a: 1, b: 2};
|
Adjust gRPC/Python sample to handle events.
|
import coprocess_object_pb2
import grpc, time, json
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
from concurrent import futures
def MyPreMiddleware(coprocess_object):
coprocess_object.request.set_headers["myheader"] = "myvalue"
return coprocess_object
def MyPostMiddleware(coprocess_object):
coprocess_object.request.set_headers["anotherheader"] = "anothervalue"
return coprocess_object
class MyDispatcher(coprocess_object_pb2.DispatcherServicer):
def Dispatch(self, coprocess_object, context):
if coprocess_object.hook_name == "MyPreMiddleware":
coprocess_object = MyPreMiddleware(coprocess_object)
if coprocess_object.hook_name == "MyPostMiddleware":
coprocess_object = MyPostMiddleware(coprocess_object)
return coprocess_object
def DispatchEvent(self, event_wrapper, context):
event = json.loads(event_wrapper.payload)
print("DispatchEvent:", event)
return coprocess_object_pb2.EventReply()
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
coprocess_object_pb2.add_DispatcherServicer_to_server(
MyDispatcher(), server)
server.add_insecure_port('[::]:5555')
server.start()
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
serve()
|
import coprocess_object_pb2
import grpc, time
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
from concurrent import futures
def MyPreMiddleware(coprocess_object):
coprocess_object.request.set_headers["myheader"] = "myvalue"
return coprocess_object
def MyPostMiddleware(coprocess_object):
coprocess_object.request.set_headers["anotherheader"] = "anothervalue"
return coprocess_object
class MyDispatcher(coprocess_object_pb2.DispatcherServicer):
def Dispatch(self, coprocess_object, context):
if coprocess_object.hook_name == "MyPreMiddleware":
coprocess_object = MyPreMiddleware(coprocess_object)
if coprocess_object.hook_name == "MyPostMiddleware":
coprocess_object = MyPostMiddleware(coprocess_object)
return coprocess_object
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
coprocess_object_pb2.add_DispatcherServicer_to_server(
MyDispatcher(), server)
server.add_insecure_port('[::]:5555')
server.start()
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
serve()
|
Add PageBegin to pkg exports
|
#copyright ReportLab Inc. 2000
#see license.txt for license details
#history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/platypus/__init__.py?cvsroot=reportlab
#$Header: /tmp/reportlab/reportlab/platypus/__init__.py,v 1.13 2002/03/15 09:03:37 rgbecker Exp $
__version__=''' $Id: __init__.py,v 1.13 2002/03/15 09:03:37 rgbecker Exp $ '''
__doc__=''
from reportlab.platypus.flowables import Flowable, Image, Macro, PageBreak, Preformatted, Spacer, XBox, \
CondPageBreak, KeepTogether
from reportlab.platypus.paragraph import Paragraph, cleanBlockQuotedText, ParaLines
from reportlab.platypus.paraparser import ParaFrag
from reportlab.platypus.tables import Table, TableStyle, CellStyle
from reportlab.platypus.frames import Frame
from reportlab.platypus.doctemplate import BaseDocTemplate, NextPageTemplate, PageTemplate, ActionFlowable, \
SimpleDocTemplate, FrameBreak, PageBegin
from xpreformatted import XPreformatted
|
#copyright ReportLab Inc. 2000
#see license.txt for license details
#history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/platypus/__init__.py?cvsroot=reportlab
#$Header: /tmp/reportlab/reportlab/platypus/__init__.py,v 1.12 2000/11/29 17:28:50 rgbecker Exp $
__version__=''' $Id: __init__.py,v 1.12 2000/11/29 17:28:50 rgbecker Exp $ '''
__doc__=''
from reportlab.platypus.flowables import Flowable, Image, Macro, PageBreak, Preformatted, Spacer, XBox, \
CondPageBreak, KeepTogether
from reportlab.platypus.paragraph import Paragraph, cleanBlockQuotedText, ParaLines
from reportlab.platypus.paraparser import ParaFrag
from reportlab.platypus.tables import Table, TableStyle, CellStyle
from reportlab.platypus.frames import Frame
from reportlab.platypus.doctemplate import BaseDocTemplate, NextPageTemplate, PageTemplate, ActionFlowable, \
SimpleDocTemplate, FrameBreak
from xpreformatted import XPreformatted
|
Update links from Github to Gitlab following project move.
|
# :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='Segue',
version='1.0.0dev',
description='Maya and Houdini geometry transfer helper.',
packages=[
'segue',
],
package_dir={
'': 'source'
},
author='Martin Pengelly-Phillips',
author_email='martin@4degrees.ltd.uk',
license='Apache License (2.0)',
long_description=open('README.rst').read(),
url='https://gitlab.com/4degrees/segue',
keywords='maya,houdini,transfer,cache'
)
|
# :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='Segue',
version='1.0.0dev',
description='Maya and Houdini geometry transfer helper.',
packages=[
'segue',
],
package_dir={
'': 'source'
},
author='Martin Pengelly-Phillips',
author_email='martin@4degrees.ltd.uk',
license='Apache License (2.0)',
long_description=open('README.rst').read(),
url='https://bitbucket.org/4degrees/segue',
keywords='maya,houdini,transfer,cache'
)
|
Fix foreign key constraint error
|
<?php
use Illuminate\Database\Seeder;
class TopicsTableSeeder extends Seeder {
public function run()
{
DB::table('topics')->delete();
$topic = [
'title' => 'My Topic',
'slug' => 'my-topic',
'forum_id' => DB::table('forums')->where('slug', 'my-forum')->pluck('id'),
'user_id' => DB::table('users')->where('name', 'Admin')->pluck('id'),
'first_post_id' => null,
'last_post_id' => 1,
'views' => 0,
'created_at' => new \DateTime(),
'updated_at' => new \DateTime(),
'num_posts' => 1,
];
DB::table('topics')->insert($topic);
}
}
|
<?php
use Illuminate\Database\Seeder;
class TopicsTableSeeder extends Seeder {
public function run()
{
DB::table('topics')->delete();
$topic = [
'title' => 'My Topic',
'slug' => 'my-topic',
'forum_id' => DB::table('forums')->where('slug', 'my-forum')->pluck('id'),
'user_id' => DB::table('users')->where('name', 'Admin')->pluck('id'),
'first_post_id' => 1,
'last_post_id' => 1,
'views' => 0,
'created_at' => new \DateTime(),
'updated_at' => new \DateTime(),
'num_posts' => 1,
];
DB::table('topics')->insert($topic);
}
}
|
[BACKLOG-19262] Fix to check style violation
|
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.big.data.kettle.plugins.recordsfromstream;
import org.pentaho.di.core.annotations.Step;
import org.pentaho.di.trans.steps.rowsfromresult.RowsFromResultMeta;
@Step( id = "RecordsFromStream", image = "get-records-from-stream.svg",
i18nPackageName = "org.pentaho.big.data.kettle.plugins.recordsfromstream",
name = "RecordsFromStream.TypeLongDesc",
description = "RecordsFromStream.TypeTooltipDesc",
categoryDescription = "i18n:org.pentaho.di.trans.step:BaseStep.Category.Streaming",
documentationUrl = "Products/Data_Integration/Transformation_Step_Reference/Get_Records_From_Stream" )
public class RecordsFromStreamMeta extends RowsFromResultMeta {
}
|
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.big.data.kettle.plugins.recordsfromstream;
import org.pentaho.di.core.annotations.Step;
import org.pentaho.di.trans.steps.rowsfromresult.RowsFromResultMeta;
@Step( id = "RecordsFromStream", image = "get-records-from-stream.svg",
i18nPackageName = "org.pentaho.big.data.kettle.plugins.recordsfromstream",
name = "RecordsFromStream.TypeLongDesc",
description = "RecordsFromStream.TypeTooltipDesc",
categoryDescription = "i18n:org.pentaho.di.trans.step:BaseStep.Category.Streaming",
documentationUrl = "Products/Data_Integration/Transformation_Step_Reference/Get_Records_From_Stream")
public class RecordsFromStreamMeta extends RowsFromResultMeta {
}
|
Add comments to MapWidget class and MapWidget.render method
|
from django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
"""Custom map widget for displaying interactive google map to geocode
addresses of learning centers.
This widget displays a readonly input box to store lat+lng data, an empty
help div, a map div for the google map, and a button to initiate geocoding.
"""
def render(self, name, value, attrs=None):
"""Overrides the render method. This controls the actual html output of a form
on the page
See widget docs for more information:
https://docs.djangoproject.com/en/1.4/ref/forms/widgets/
"""
widget = super(MapWidget, self).render(name, value, attrs)
return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60">
<br>
<input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()>
(<a onclick=ecepAdmin.mapHelp() href="#">?</a>)
<div id='map-help'></div><div id="map">%s</div>""" % (value, widget))
|
from django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
def render(self, name, value, attrs=None):
widget = super(MapWidget, self).render(name, value, attrs)
return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60">
<br>
<input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()>
(<a onclick=ecepAdmin.mapHelp() href="#">?</a>)
<div id='map-help'></div><div id="map">%s</div>""" % (value, widget))
|
Change window title based on current collection
|
// CHANGE the current collection
var changeCollection=function(new_index){
dbIndex = new_index;
imageDB = DATABASE[dbIndex];
$("#collectionFooter").text(collections[dbIndex]);
document.title = collections[dbIndex];
localStorage.setItem("last_visited_index",dbIndex); // saves the state AKA the last collection you had open
if(imageDB==null){
imageDB = [];
}
applyChanges();
List();
$('#txtInput').focus();
};
//CREATE a NEW collection
var newCollection = function(){
var new_collection;
new_collection = prompt("Enter a name for your new collection","","New image collection");
// if its bad input, just do nothing:
if(new_collection==""||new_collection==null){ // force the user to give the collection a name
$('#dropdown').prop("selectedIndex",(localStorage.getItem("last_visited_index"))); // a little trick to jump back out of the "new collection..." menu item
return;
}
collections.push(new_collection); // add new collection
localStorage.setItem("collection_names",JSON.stringify(collections)); // update the list of collection names ;
changeCollection(collections.length-1); // Switch over to the new collection
popDropdown();
};
|
// CHANGE the current collection
var changeCollection=function(new_index){
dbIndex = new_index;
imageDB = DATABASE[dbIndex];
$("#collectionFooter").text(collections[dbIndex]);
localStorage.setItem("last_visited_index",dbIndex); // saves the state AKA the last collection you had open
if(imageDB==null){
imageDB = [];
}
applyChanges();
List();
$('#txtInput').focus();
};
//CREATE a NEW collection
var newCollection = function(){
var new_collection;
new_collection = prompt("Enter a name for your new collection","","New image collection");
// if its bad input, just do nothing:
if(new_collection==""||new_collection==null){ // force the user to give the collection a name
$('#dropdown').prop("selectedIndex",(localStorage.getItem("last_visited_index"))); // a little trick to jump back out of the "new collection..." menu item
return;
}
collections.push(new_collection); // add new collection
localStorage.setItem("collection_names",JSON.stringify(collections)); // update the list of collection names ;
changeCollection(collections.length-1); // Switch over to the new collection
popDropdown();
};
|
Set timezone of the cronjob to the timezone of Switzerland
As the telegram bot is mostly used by Swiss people.
|
'use strict';
var sender = {
registerCronJob: function(bot) {
var CronJob = require('cron').CronJob;
// for testing: all minute
//new CronJob('*/1 * * * *', function() {
new CronJob('0 1 0 * * *', function() {
console.log("++++++++++++++++++\nTime to send the newest stuff to the users!\n++++++++++++++++++");
sender.sendMessagesToUsers(bot);
}, null, true, 'Europe/Zurich');
},
sendMessagesToUsers: function(bot) {
var users = require("./users");
users.getUsers().find({abo:1},{},function(err, docs) {
docs.forEach(function(user) {
sender.sendToUser(user, bot);
})
});
},
sendToUser: function(user, bot) {
console.log("sending to user " + user._id);
var webscraper = require("./web_scraper.js");
webscraper.scrapeThisShit(user.lang, function(data) {
console.log("send image");
bot.sendPhoto(user._id, data.image, {caption: data.title});
});
}
};
module.exports = sender;
|
'use strict';
var sender = {
registerCronJob: function(bot) {
var CronJob = require('cron').CronJob;
// for testing: all minute
//new CronJob('*/1 * * * *', function() {
new CronJob('0 1 0 * * *', function() {
console.log("++++++++++++++++++\nTime to send the newest stuff to the users!\n++++++++++++++++++");
sender.sendMessagesToUsers(bot);
}, null, true, 'America/Los_Angeles');
},
sendMessagesToUsers: function(bot) {
var users = require("./users");
users.getUsers().find({abo:1},{},function(err, docs) {
docs.forEach(function(user) {
sender.sendToUser(user, bot);
})
});
},
sendToUser: function(user, bot) {
console.log("sending to user " + user._id);
var webscraper = require("./web_scraper.js");
webscraper.scrapeThisShit(user.lang, function(data) {
console.log("send image");
bot.sendPhoto(user._id, data.image, {caption: data.title});
});
}
};
module.exports = sender;
|
Change canvas size into 612x612
|
(function() {
var frameContainer = document.getElementById("frame");
var capturing = false;
camera.init({
width: 612,
height: 612,
fps: 30,
mirror: true,
targetCanvas: frameContainer,
onFrame: function(canvas) {
},
onSuccess: function() {
document.getElementById("info").style.display = "none";
capturing = true;
document.getElementById("pause").style.display = "block";
document.getElementById("pause").onclick = function() {
if (capturing) {
camera.pause();
} else {
camera.start();
}
capturing = !capturing;
};
},
onError: function(error) {
// TODO: log error
},
onNotSupported: function() {
document.getElementById("info").style.display = "none";
asciiContainer.style.display = "none";
document.getElementById("notSupported").style.display = "block";
}
});
})();
|
(function() {
var frameContainer = document.getElementById("frame");
var capturing = false;
camera.init({
width: 160,
height: 120,
fps: 30,
mirror: true,
targetCanvas: frameContainer,
onFrame: function(canvas) {
},
onSuccess: function() {
document.getElementById("info").style.display = "none";
capturing = true;
document.getElementById("pause").style.display = "block";
document.getElementById("pause").onclick = function() {
if (capturing) {
camera.pause();
} else {
camera.start();
}
capturing = !capturing;
};
},
onError: function(error) {
// TODO: log error
},
onNotSupported: function() {
document.getElementById("info").style.display = "none";
asciiContainer.style.display = "none";
document.getElementById("notSupported").style.display = "block";
}
});
})();
|
Remove the container after the image has been created
No reason for having them to hang around
|
var argv = require('minimist')(process.argv.slice(2))
var execSync = require('child_process').execSync
if (argv.h || argv.help || argv._.length === 0) {
console.log('Usage: generate-static name [html]')
process.exit(0)
}
var imagename = argv._.shift()
var html = argv._.shift() || '<h1>Hello Docker</h1>'
console.log('Image:', imagename)
console.log('HTML:', html)
var command = 'docker pull nginx:latest'
console.log(command)
var pull = execSync(command).toString()
console.log(pull)
command = 'docker run -d nginx:latest'
console.log(command)
var id = execSync(command).toString().replace('\n', '')
console.log('id', id)
var index = 'echo "' + html + '" > /usr/share/nginx/html/index.html'
command = 'docker exec ' + id + ' /bin/sh -c "' + index.replace(/"/g, '\\"') + '"'
console.log(command)
var done = execSync(command).toString()
console.log(done)
command = 'docker commit ' + id + ' ' + imagename
console.log(command)
var container = execSync(command).toString()
console.log(container)
command = 'docker rm -f ' + id
console.log(command)
var rm = execSync(command).toString()
console.log(rm)
console.log('\nDocker image is now generated:')
console.log(imagename)
|
var argv = require('minimist')(process.argv.slice(2))
var execSync = require('child_process').execSync
if (argv.h || argv.help || argv._.length === 0) {
console.log('Usage: generate-static name [html]')
process.exit(0)
}
var imagename = argv._.shift()
var html = argv._.shift() || '<h1>Hello Docker</h1>'
console.log('Image:', imagename)
console.log('HTML:', html)
var command = 'docker pull nginx:latest'
console.log(command)
var pull = execSync(command).toString()
console.log(pull)
command = 'docker run -d nginx:latest'
console.log(command)
var id = execSync(command).toString().replace('\n', '')
console.log('id', id)
var index = 'echo "' + html + '" > /usr/share/nginx/html/index.html'
command = 'docker exec ' + id + ' /bin/sh -c "' + index.replace(/"/g, '\\"') + '"'
console.log(command)
var done = execSync(command).toString()
console.log(done)
command = 'docker commit ' + id + ' ' + imagename
console.log(command)
var container = execSync(command).toString()
console.log(container)
console.log('Docker image is now generated:')
console.log(imagename)
|
Fix tweets not being stored in list
|
/**
* ProcessedTweetList - Stores tweets/dms by room_id so we don't accidentally
* repeat any messages. Please note that the cache and slice size values are
* per room, not the total size of all stored rooms.
*
* @class
* @param {number} [128] cacheSize How many messages to store before cleanup occurs
* @param {number} [16] sliceSize On cleanup, how many messages will be kept
*/
var ProcessedTweetList = function (cacheSize, sliceSize) {
this._roomIdToTweetIds = new Map();
this._cacheSize = cacheSize || 128;
this._sliceSize = sliceSize || 16;
}
ProcessedTweetList.prototype.push = function (room_id, tweet_id) {
if(!this._roomIdToTweetIds.has(room_id)) {
this._roomIdToTweetIds.set(room_id, []);
}
this._roomIdToTweetIds.get(room_id).push(tweet_id);
if(this._roomIdToTweetIds.get(room_id).length > this._cacheSize) {
this._roomIdToTweetIds.get(room_id).splice(0, this._sliceSize);
}
}
ProcessedTweetList.prototype.contains = function (room_id, tweet_id) {
if(!this._roomIdToTweetIds.has(room_id)) {
return false;
}
return (this._roomIdToTweetIds.get(room_id).indexOf(tweet_id) != -1);
}
module.exports = ProcessedTweetList;
|
/**
* ProcessedTweetList - Stores tweets/dms by room_id so we don't accidentally
* repeat any messages. Please note that the cache and slice size values are
* per room, not the total size of all stored rooms.
*
* @class
* @param {number} [128] cacheSize How many messages to store before cleanup occurs
* @param {number} [16] sliceSize On cleanup, how many messages will be kept
*/
var ProcessedTweetList = function (cacheSize, sliceSize) {
this._roomIdToTweetIds = new Map();
this._cacheSize = cacheSize || 128;
this._sliceSize = sliceSize || 16;
}
ProcessedTweetList.prototype.push = function (room_id, tweet_id) {
if(!this._roomIdToTweetIds.has(room_id)) {
this._roomIdToTweetIds[room_id] = [];
}
this._roomIdToTweetIds[room_id].push(tweet_id);
if(this._roomIdToTweetIds[room_id].length > this._cacheSize) {
this._roomIdToTweetIds[room_id].splice(0, this._sliceSize);
}
}
ProcessedTweetList.prototype.contains = function (room_id, tweet_id) {
if(!this._roomIdToTweetIds.has(room_id)) {
return false;
}
return (this._roomIdToTweetIds[room_id].indexOf(tweet_id) != -1);
}
module.exports = ProcessedTweetList;
|
Add coverage reporter to browserstack build
|
const base = require('./karma.base.conf');
module.exports = function(config) {
config.set(Object.assign(base, {
browserStack: {
username: process.env.BROWSERSTACK_USERNAME,
accessKey: process.env.BROWSERSTACK_ACCESS_KEY
},
customLaunchers: {
bs_safari_mac: {
base: 'BrowserStack',
browser: 'safari',
os: 'OS X',
os_version: 'Sierra'
},
bs_firefox_mac: {
base: 'BrowserStack',
browser: 'firefox',
os: 'OS X',
os_version: 'Sierra'
},
bs_chrome_mac: {
base: 'BrowserStack',
browser: 'chrome',
os: 'OS X',
os_version: 'Sierra'
}
},
browsers: ['bs_safari_mac', 'bs_firefox_mac', 'bs_chrome_mac'],
autoWatch: false,
singleRun: true,
reporters: ['dots', 'BrowserStack', 'coverage']
}));
};
|
const base = require('./karma.base.conf');
module.exports = function(config) {
config.set(Object.assign(base, {
browserStack: {
username: process.env.BROWSERSTACK_USERNAME,
accessKey: process.env.BROWSERSTACK_ACCESS_KEY
},
customLaunchers: {
bs_safari_mac: {
base: 'BrowserStack',
browser: 'safari',
os: 'OS X',
os_version: 'Sierra'
},
bs_firefox_mac: {
base: 'BrowserStack',
browser: 'firefox',
os: 'OS X',
os_version: 'Sierra'
},
bs_chrome_mac: {
base: 'BrowserStack',
browser: 'chrome',
os: 'OS X',
os_version: 'Sierra'
}
},
browsers: ['bs_safari_mac', 'bs_firefox_mac', 'bs_chrome_mac'],
autoWatch: false,
singleRun: true,
reporters: ['dots', 'BrowserStack']
}));
};
|
Add db.js to jshint task
|
module.exports = function(grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
all: [
'Gruntfile.js',
'app.js',
'db.js',
'lib/**/*.js',
'routes/*.js',
'test/*.js',
'public/js/three-script.js'
]
},
stylus: {
compile : {
files : {
'public/css/style.css' : 'public/css/*.styl'
}
}
}
});
// Load the plugins.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-stylus');
// Default task(s).
grunt.registerTask('default', ['jshint', 'stylus']);
};
|
module.exports = function(grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
all: [
'Gruntfile.js',
'app.js',
'lib/**/*.js',
'routes/*.js',
'test/*.js',
'public/js/three-script.js'
]
},
stylus: {
compile : {
files : {
'public/css/style.css' : 'public/css/*.styl'
}
}
}
});
// Load the plugins.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-stylus');
// Default task(s).
grunt.registerTask('default', ['jshint', 'stylus']);
};
|
Make compatible with node 4
|
'use strict';
const uuid = require('uuid');
const cls = require('continuation-local-storage');
const store = cls.createNamespace('1d0e0c48-3375-46bc-b9ae-95c63b58938e');
function withId (work) {
if (!work) throw new Error('Missing work parameter');
store.run(() => {
store.set('correlator', uuid.v4());
work();
});
}
function bindId (work) {
if (!work) throw new Error('Missing work parameter');
return function () {
store.run(() => {
store.set('correlator', uuid.v4());
work.apply(null, [].slice.call(arguments));
});
};
}
function getId () {
return store.get('correlator');
}
function express () {
return (req, res, next) => {
store.run(() => {
store.set('correlator', uuid.v4());
next();
});
};
}
module.exports = {
withId,
bindId,
getId,
express
};
|
'use strict';
const uuid = require('uuid');
const cls = require('continuation-local-storage');
const store = cls.createNamespace('1d0e0c48-3375-46bc-b9ae-95c63b58938e');
function withId (work) {
if (!work) throw new Error('Missing work parameter');
store.run(() => {
store.set('correlator', uuid.v4());
work();
});
}
function bindId (work) {
if (!work) throw new Error('Missing work parameter');
return (...args) => {
store.run(() => {
store.set('correlator', uuid.v4());
work(...args);
});
};
}
function getId () {
return store.get('correlator');
}
function express () {
return (req, res, next) => {
store.run(() => {
store.set('correlator', uuid.v4());
next();
});
};
}
module.exports = {
withId,
bindId,
getId,
express
};
|
Revert "CAMEL-14020 - Migrate getOut to getMessage in camel-spring-integration"
This reverts commit d3586cc0af2af7719f5612ab3398d079f398e1ef.
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.spring.integration;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
public class MyProcessor implements Processor {
@Override
public void process(Exchange exchange) throws Exception {
exchange.getOut().setHeader("Status", "Done");
String result = exchange.getIn().getBody() + " is processed";
exchange.getOut().setBody(result);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.spring.integration;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
public class MyProcessor implements Processor {
@Override
public void process(Exchange exchange) throws Exception {
exchange.getMessage().setHeader("Status", "Done");
String result = exchange.getIn().getBody() + " is processed";
exchange.getMessage().setBody(result);
}
}
|
Fix logger error case at start-up
|
/* 2017 Omikhleia
* License: MIT
*
* RoomJS bot main.
*/
const bunyan = require('bunyan')
const dotenv = require('dotenv')
const RoomJSBot = require('./src/room-js-bot')
const pkg = require('./package.json')
dotenv.config()
const config = {
username: process.env.BOT_USER,
password: process.env.BOT_PASSWORD,
character: process.env.BOT_CHARACTER,
address: process.env.ADDRESS || '127.0.0.1',
port: process.env.PORT || '8888',
inactivity: parseInt(process.env.BOT_INACTIVITY) || 60000,
speed: parseInt(process.env.BOT_CPM) || 800,
logLevel: process.env.LOG_LEVEL || 'info',
appName: pkg.name
}
const { appName, logLevel } = config
const logger = bunyan.createLogger({ name: appName, level: logLevel })
if (config.username && config.password && config.character) {
const client = new RoomJSBot(logger, config)
} else {
logger.fatal('Credentials missing from environment configuration')
process.exit(1)
}
|
/* 2017 Omikhleia
* License: MIT
*
* RoomJS bot main.
*/
const bunyan = require('bunyan')
const dotenv = require('dotenv')
const RoomJSBot = require('./src/room-js-bot')
const pkg = require('./package.json')
dotenv.config()
const config = {
username: process.env.BOT_USER,
password: process.env.BOT_PASSWORD,
character: process.env.BOT_CHARACTER,
address: process.env.ADDRESS || '127.0.0.1',
port: process.env.PORT || '8888',
inactivity: parseInt(process.env.BOT_INACTIVITY) || 60000,
speed: parseInt(process.env.BOT_CPM) || 800,
logLevel: process.env.LOG_LEVEL || 'info',
appName: pkg.name
}
const { appName, logLevel } = config
const logger = bunyan.createLogger({ name: appName, level: logLevel })
if (config.username && config.password && config.character) {
const client = new RoomJSBot(logger, config)
} else {
this.logger.fatal('Credentials missing from environment configuration')
process.exit(1)
}
|
Mark moment as external again
|
const path = require('path')
module.exports = (env, argv) => ({
entry: './src/components/App.js',
output: {
filename: 'bundle.js',
path: __dirname
},
devtool: argv.mode === 'production' ? false : 'cheap-module-eval-source-map',
target: 'electron-renderer',
node: {
__dirname: false
},
resolve: {
alias: {
'react': path.join(__dirname, 'node_modules/preact/dist/preact.min'),
'preact': path.join(__dirname, 'node_modules/preact/dist/preact.min'),
'prop-types': path.join(__dirname, 'src/modules/shims/prop-types')
}
},
externals: {
'moment': 'null'
}
})
|
const path = require('path')
module.exports = (env, argv) => ({
entry: './src/components/App.js',
output: {
filename: 'bundle.js',
path: __dirname
},
devtool: argv.mode === 'production' ? false : 'cheap-module-eval-source-map',
target: 'electron-renderer',
node: {
__dirname: false
},
resolve: {
alias: {
'react': path.join(__dirname, 'node_modules/preact/dist/preact.min'),
'preact': path.join(__dirname, 'node_modules/preact/dist/preact.min'),
'prop-types': path.join(__dirname, 'src/modules/shims/prop-types')
}
}
})
|
Change order of arguments in Fragment.handle
|
'use strict';
export default class Fragment {
render () {
return null;
}
/**
* Generic event handler. Turns class methods into closures that can be used as event handlers. If you need to use
* data from the event object, or have access to the event object in general, use handleEvent instead.
*
* For non class methods (or methods that call into a different `this`, use framework/utils/handle).
*/
handle (fn, args, final=false) {
var self = this;
return function (ev) {
fn.apply(self, args);
if (final) {
ev.preventDefault();
ev.stopPropagation();
return false;
}
}
}
}
|
'use strict';
export default class Fragment {
render () {
return null;
}
/**
* Generic event handler. Turns class methods into closures that can be used as event handlers. If you need to use
* data from the event object, or have access to the event object in general, use handleEvent instead.
*
* For non class methods (or methods that call into a different `this`, use framework/utils/handle).
*/
handle (fn, final=false, args) {
var self = this;
return function (ev) {
fn.apply(self, args);
if (final) {
ev.preventDefault();
ev.stopPropagation();
return false;
}
}
}
}
|
Update Star plugin to use new caching API
|
import urllib.request
import urllib.error
import json
import plugin
import command
import message
import caching
import os
def onInit(plugin):
star_command = command.command(plugin, 'star', shortdesc='Post a random picture of Star Butterfly to the channel')
return plugin.plugin.plugin(plugin, 'star', [star_command])
def onCommand(message_in):
if message_in.command == 'star':
try:
f = urllib.request.urlopen("https://sydneyerickson.me/starapi/rand.php").read().decode("utf-8")
except urllib.error.URLError as e:
return message.message(body='There was an issue connecting to Starapi'.format(message_in.body))
imageName = f.split('/')
caching.downloadToCache(f, imageName[-1])
return message.message(file='cache/star_' + imageName[-1])
|
import urllib.request
import urllib.error
import json
import plugin
import command
import message
import os
def onInit(plugin):
star_command = command.command(plugin, 'star', shortdesc='Post a random picture of Star Butterfly to the channel')
return plugin.plugin.plugin(plugin, 'star', [star_command])
def onCommand(message_in):
if message_in.command == 'star':
try:
f = urllib.request.urlopen("https://sydneyerickson.me/starapi/rand.php").read().decode("utf-8")
except urllib.error.URLError as e:
return message.message(body='There was an issue connecting to XKCD'.format(message_in.body))
imageName = f.split('/')
if os.path.isfile('cache/star_' + imageName[-1]):
pass
else:
urllib.request.urlretrieve(f, 'cache/star_' + imageName[-1])
return message.message(file='cache/star_' + imageName[-1])
|
Return when nomad syslog command has invalid number of argument
|
package command
import (
"os"
"strings"
"github.com/hashicorp/go-plugin"
"github.com/hashicorp/nomad/client/driver"
)
type SyslogPluginCommand struct {
Meta
}
func (e *SyslogPluginCommand) Help() string {
helpText := `
This is a command used by Nomad internally to launch a syslog collector"
`
return strings.TrimSpace(helpText)
}
func (s *SyslogPluginCommand) Synopsis() string {
return "internal - lanch a syslog collector plugin"
}
func (s *SyslogPluginCommand) Run(args []string) int {
if len(args) == 0 {
s.Ui.Error("log output file isn't provided")
return 1
}
logFileName := args[0]
stdo, err := os.OpenFile(logFileName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
if err != nil {
s.Ui.Error(err.Error())
return 1
}
plugin.Serve(&plugin.ServeConfig{
HandshakeConfig: driver.HandshakeConfig,
Plugins: driver.GetPluginMap(stdo),
})
return 0
}
|
package command
import (
"os"
"strings"
"github.com/hashicorp/go-plugin"
"github.com/hashicorp/nomad/client/driver"
)
type SyslogPluginCommand struct {
Meta
}
func (e *SyslogPluginCommand) Help() string {
helpText := `
This is a command used by Nomad internally to launch a syslog collector"
`
return strings.TrimSpace(helpText)
}
func (s *SyslogPluginCommand) Synopsis() string {
return "internal - lanch a syslog collector plugin"
}
func (s *SyslogPluginCommand) Run(args []string) int {
if len(args) == 0 {
s.Ui.Error("log output file isn't provided")
}
logFileName := args[0]
stdo, err := os.OpenFile(logFileName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
if err != nil {
s.Ui.Error(err.Error())
return 1
}
plugin.Serve(&plugin.ServeConfig{
HandshakeConfig: driver.HandshakeConfig,
Plugins: driver.GetPluginMap(stdo),
})
return 0
}
|
Change settings timestamps to nullable columns
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSettingsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->increments('id');
$table->timestamp('exchanges_start_at')->nullable();
$table->timestamp('exchanges_end_at')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('settings');
}
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSettingsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->increments('id');
$table->timestamp('exchanges_start_at');
$table->timestamp('exchanges_end_at');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('settings');
}
}
|
Remove dodgy mention from _short_description
The package name shouldn't be in the description.
|
# -*- coding: UTF-8 -*-
from distutils.core import setup
from setuptools import find_packages
from dodgy import __pkginfo__
_packages = find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"])
_short_description = "Searches for dodgy looking lines in Python code"
_install_requires = []
_classifiers = (
'Development Status :: 7 - Inactive',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: Unix',
'Topic :: Software Development :: Quality Assurance',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
)
setup(
name='dodgy',
url='https://github.com/landscapeio/dodgy',
author='landscape.io',
author_email='code@landscape.io',
description=_short_description,
install_requires=_install_requires,
entry_points={
'console_scripts': [
'dodgy = dodgy.run:main',
],
},
version=__pkginfo__.get_version(),
packages=_packages,
license='MIT',
keywords='check for suspicious code',
classifiers=_classifiers
)
|
# -*- coding: UTF-8 -*-
from distutils.core import setup
from setuptools import find_packages
from dodgy import __pkginfo__
_packages = find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"])
_short_description = "Dodgy: Searches for dodgy looking lines in Python code"
_install_requires = []
_classifiers = (
'Development Status :: 7 - Inactive',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: Unix',
'Topic :: Software Development :: Quality Assurance',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
)
setup(
name='dodgy',
url='https://github.com/landscapeio/dodgy',
author='landscape.io',
author_email='code@landscape.io',
description=_short_description,
install_requires=_install_requires,
entry_points={
'console_scripts': [
'dodgy = dodgy.run:main',
],
},
version=__pkginfo__.get_version(),
packages=_packages,
license='MIT',
keywords='check for suspicious code',
classifiers=_classifiers
)
|
Add CORS headers to GET response
|
'use strict';
const crypto = require('crypto');
// User ARN: arn:aws:iam::561178107736:user/prx-upload
// Access Key ID: AKIAJZ5C7KQPL34SQ63Q
const key = process.env.ACCESS_KEY;
exports.handler = (event, context, callback) => {
try {
if (!event.queryStringParameters || !event.queryStringParameters.to_sign) {
callback(null, { statusCode: 400, headers: {}, body: null });
} else {
const toSign = event.queryStringParameters.to_sign;
const signature = crypto.createHmac('sha1', key).update(toSign).digest('base64');
callback(null, {
statusCode: 200,
headers: {
'Content-Type': 'text/plain',
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
'Access-Control-Allow-Methods': 'GET,OPTIONS',
'Access-Control-Allow-Origin': '*'
},
body: signature
});
}
} catch (e) {
callback(e);
}
};
|
'use strict';
const crypto = require('crypto');
// User ARN: arn:aws:iam::561178107736:user/prx-upload
// Access Key ID: AKIAJZ5C7KQPL34SQ63Q
const key = process.env.ACCESS_KEY;
exports.handler = (event, context, callback) => {
try {
if (!event.queryStringParameters || !event.queryStringParameters.to_sign) {
callback(null, { statusCode: 400, headers: {}, body: null });
} else {
const toSign = event.queryStringParameters.to_sign;
const signature = crypto.createHmac('sha1', key).update(toSign).digest('base64');
callback(null, {
statusCode: 200,
headers: {
'Content-Type': 'text/plain'
},
body: signature
});
}
} catch (e) {
callback(e);
}
};
|
Update SVG when component is updated
|
import React, { Component, PropTypes } from 'react';
import SVGInjector from 'svg-injector';
export default class ReactSVG extends Component {
static defaultProps = {
evalScripts: 'never',
callback: () => {}
}
static propTypes = {
path: PropTypes.string.isRequired,
className: PropTypes.string,
evalScripts: PropTypes.oneOf(['always', 'once', 'never']),
fallbackPath: PropTypes.string,
callback: PropTypes.func
}
render() {
const {
className,
path,
fallbackPath
} = this.props;
return (
<img
className={className}
data-src={path}
data-fallback={fallbackPath}
ref={(img) => this._img = img}
/>
);
}
componentDidMount() {
this.updateSVG();
}
componentDidUpdate() {
this.updateSVG();
}
updateSVG() {
const {
evalScripts,
callback: each
} = this.props;
SVGInjector(this._img, {
evalScripts,
each
});
}
}
|
import React, { Component, PropTypes } from 'react';
import SVGInjector from 'svg-injector';
export default class ReactSVG extends Component {
static defaultProps = {
evalScripts: 'never',
callback: () => {}
}
static propTypes = {
path: PropTypes.string.isRequired,
className: PropTypes.string,
evalScripts: PropTypes.oneOf(['always', 'once', 'never']),
fallbackPath: PropTypes.string,
callback: PropTypes.func
}
render() {
const {
className,
path,
fallbackPath
} = this.props;
return (
<img
className={className}
data-src={path}
data-fallback={fallbackPath}
ref={(img) => this._img = img}
/>
);
}
componentDidMount() {
const {
evalScripts,
callback: each
} = this.props;
SVGInjector(this._img, {
evalScripts,
each
});
}
}
|
Update dependencies to be an exact copy of jquery-ui's custom download option
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-ui-sortable',
included: function(app) {
this._super.included(app);
app.import(app.bowerDirectory + '/jquery-ui/ui/version.js');
app.import(app.bowerDirectory + '/jquery-ui/ui/data.js');
app.import(app.bowerDirectory + '/jquery-ui/ui/ie.js');
app.import(app.bowerDirectory + '/jquery-ui/ui/safe-active-element.js');
app.import(app.bowerDirectory + '/jquery-ui/ui/safe-blur.js');
app.import(app.bowerDirectory + '/jquery-ui/ui/scroll-parent.js');
app.import(app.bowerDirectory + '/jquery-ui/ui/plugin.js');
app.import(app.bowerDirectory + '/jquery-ui/ui/widget.js');
app.import(app.bowerDirectory + '/jquery-ui/ui/widgets/mouse.js');
app.import(app.bowerDirectory + '/jquery-ui/ui/widgets/draggable.js');
app.import(app.bowerDirectory + '/jquery-ui/ui/widgets/sortable.js');
}
};
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-ui-sortable',
included: function(app) {
this._super.included(app);
//app.import(app.bowerDirectory + '/jquery-ui/ui/data.js');
//app.import(app.bowerDirectory + '/jquery-ui/ui/scroll-parent.js');
//app.import(app.bowerDirectory + '/jquery-ui/ui/widget.js');
//app.import(app.bowerDirectory + '/jquery-ui/ui/widgets/mouse.js');
//app.import(app.bowerDirectory + '/jquery-ui/ui/widgets/draggable.js');
//app.import(app.bowerDirectory + '/jquery-ui/ui/widgets/sortable.js');
app.import(app.bowerDirectory + '/jquery-ui/jquery-ui.js');
}
};
|
Fix mocha as promised location
|
var brunchConfig = require('../brunch-config').config.overrides['web:dev'];
var path = require('path');
var publicPath = path.resolve(__dirname, '..', brunchConfig.paths.public);
module.exports = function(config) {
config.set({
browsers: ['PhantomJS'],
frameworks: ['mocha', 'chai', 'sinon-chai'],
files: [
path.resolve(__dirname, '../node_modules/mocha-as-promised/mocha-as-promised.js'),
path.resolve(publicPath, '**/*.js'),
path.resolve(__dirname, 'code/*.js'),
path.resolve(__dirname, 'code/**/*.js')
],
exclude: [
path.resolve(publicPath, 'test/**/*.js')
]
});
};
|
var brunchConfig = require('../brunch-config').config.overrides['web:dev'];
var path = require('path');
var publicPath = path.resolve(__dirname, '..', brunchConfig.paths.public);
module.exports = function(config) {
config.set({
browsers: ['PhantomJS'],
frameworks: ['mocha', 'chai', 'sinon-chai'],
files: [
path.resolve(__dirname, 'node_modules/mocha-as-promised/mocha-as-promised.js'),
path.resolve(publicPath, '**/*.js'),
path.resolve(__dirname, 'code/*.js'),
path.resolve(__dirname, 'code/**/*.js')
],
exclude: [
path.resolve(publicPath, 'test/**/*.js')
]
});
};
|
Add 500 error to the rest framework for go agents
Signed-off-by: Oleksandr Garagatyi <4052944973da826587020fa2673f873866877623@redhat.com>
|
//
// Copyright (c) 2012-2018 Red Hat, Inc.
// This program and the accompanying materials are made
// available under the terms of the Eclipse Public License 2.0
// which is available at https://www.eclipse.org/legal/epl-2.0/
//
// SPDX-License-Identifier: EPL-2.0
//
// Contributors:
// Red Hat, Inc. - initial API and implementation
//
package rest
import (
"net/http"
)
// APIError represents http error
type APIError struct {
error
Code int
}
// BadRequest represents http error with 400 code
func BadRequest(err error) error {
return APIError{err, http.StatusBadRequest}
}
// NotFound represents http error with code 404
func NotFound(err error) error {
return APIError{err, http.StatusNotFound}
}
// Conflict represents http error with 409 code
func Conflict(err error) error {
return APIError{err, http.StatusConflict}
}
// Forbidden represents http error with 403 code
func Forbidden(err error) error {
return APIError{err, http.StatusForbidden}
}
// Unauthorized represents http error with 401 code
func Unauthorized(err error) error {
return APIError{err, http.StatusUnauthorized}
}
// ServerError represents http error with 500 code
func ServerError(err error) error {
return APIError{err, http.StatusInternalServerError}
}
|
//
// Copyright (c) 2012-2018 Red Hat, Inc.
// This program and the accompanying materials are made
// available under the terms of the Eclipse Public License 2.0
// which is available at https://www.eclipse.org/legal/epl-2.0/
//
// SPDX-License-Identifier: EPL-2.0
//
// Contributors:
// Red Hat, Inc. - initial API and implementation
//
package rest
import (
"net/http"
)
// APIError represents http error
type APIError struct {
error
Code int
}
// BadRequest represents http error with 400 code
func BadRequest(err error) error {
return APIError{err, http.StatusBadRequest}
}
// NotFound represents http error with code 404
func NotFound(err error) error {
return APIError{err, http.StatusNotFound}
}
// Conflict represents http error with 409 code
func Conflict(err error) error {
return APIError{err, http.StatusConflict}
}
// Forbidden represents http error with 403 code
func Forbidden(err error) error {
return APIError{err, http.StatusForbidden}
}
// Unauthorized represents http error with 401 code
func Unauthorized(err error) error {
return APIError{err, http.StatusUnauthorized}
}
|
Remove images globally when we remove images
|
import store from './index.js';
/**
* Deactivates and removes the tool from the target element with the provided name
*
* @export @public @method
* @name removeToolForElement
* @param {HTMLElement} element The element.
* @param {string} toolName The name of the tool.
*/
const removeToolForElement = function (element, toolName) {
const toolIndex = store.state.tools.findIndex(
(tool) => tool.element === element && tool.name === toolName
);
if (toolIndex >= 0) {
store.state.tools.splice(toolIndex, 1);
}
};
/**
* Removes all tools from all enabled elements with the provided name.
*
* @export @public @method
* @name removeTool
* @param {string} toolName The name of the tool.
*/
const removeTool = function (toolName) {
_removeToolGlobally(toolName);
store.state.enabledElements.forEach((element) => {
removeToolForElement(element, toolName);
});
};
/**
* Removes tool with matching name from globally registered tools.
* Requires `globalToolSyncEnabled` to be set to true
*
* @private @method
* @name removeToolGlobally
* @param {string} toolName The name of the tool to remove.
*/
const _removeToolGlobally = function (toolName) {
if (!store.modules.globalConfiguration.state.globalToolSyncEnabled) {
return;
}
if (store.state.globalTools[toolName]) {
delete store.state.globalTools[toolName];
}
};
export { removeTool, removeToolForElement };
|
import { state } from './index.js';
/**
* Removes all tools from the target element with the provided name
* @export @public @method
* @name removeToolForElement
*
* @param {HTMLElement} element The element.
* @param {string} toolName The name of the tool.
*/
const removeToolForElement = function (element, toolName) {
const toolIndex = state.tools.findIndex(
(tool) => tool.element === element && tool.name === toolName
);
if (toolIndex >= 0) {
state.tools.splice(toolIndex, 1);
}
};
/**
* Removes all tools from all enabled elements with the provided name.
* @export @public @method
* @name removeTool
*
* @param {string} toolName The name of the tool.
*/
const removeTool = function (toolName) {
state.enabledElements.forEach((element) => {
removeToolForElement(element, toolName);
});
};
export { removeTool, removeToolForElement };
|
Add encoding support, move output to separate directory, change output filename to DD_MM_YYYY.csv
|
import csv
import logging
import os
import time
from config.config import Config
from d_spider import DSpider
from dev.logger import logger_setup
def main():
# setup
logger_setup(Config.get('APP_LOG_FILE'), ['ddd_site_parse'])
# log
logger = logging.getLogger('ddd_site_parse')
logger.addHandler(logging.NullHandler())
logger.info(' --- ')
logger.info('Start app...')
# bot
output_file_name = time.strftime('%d_%m_%Y') + '.csv'
output_path = os.path.join(Config.get('APP_OUTPUT_DIR'), output_file_name)
if not os.path.exists(Config.get('APP_OUTPUT_DIR')):
logger.info('Create directory, because not exist')
os.makedirs(Config.get('APP_OUTPUT_DIR'))
with open(output_path, 'w', newline='', encoding=Config.get('APP_OUTPUT_ENC')) as output:
writer = csv.writer(output, delimiter=';')
try:
threads_counter = int(Config.get('APP_THREAD_COUNT'))
bot = DSpider(thread_number=threads_counter, logger_name='ddd_site_parse', writer=writer)
bot.run()
except Exception as e:
print(e)
logger.info('End app...\n\n')
if __name__ == '__main__':
main()
|
import csv
import logging
from config.config import Config
from d_spider import DSpider
from dev.logger import logger_setup
def main():
# setup
logger_setup(Config.get('APP_LOG_FILE'), ['ddd_site_parse'])
# log
logger = logging.getLogger('ddd_site_parse')
logger.addHandler(logging.NullHandler())
logger.info(' --- ')
logger.info('Start app...')
# bot
with open(Config.get('APP_OUTPUT_CSV'), 'w', newline='') as output:
writer = csv.writer(output, delimiter=';')
try:
threads_counter = int(Config.get('APP_THREAD_COUNT'))
bot = DSpider(thread_number=threads_counter, logger_name='ddd_site_parse', writer=writer)
bot.run()
except Exception as e:
print(e)
logger.info('End app...\n\n')
if __name__ == '__main__':
main()
|
Sort modules without start dates to the future
Modules without a start date (phases dates are not set) will be sorted
after every other module or offlineevent.
|
from functools import cmp_to_key
from django import template
from adhocracy4.modules.models import Module
from adhocracy4.phases.models import Phase
from meinberlin.apps.offlineevents.models import OfflineEvent
register = template.Library()
@register.assignment_tag
def offlineevents_and_modules_sorted(project):
modules = list(project.module_set.all())
events = list(OfflineEvent.objects.filter(project=project))
res = modules + events
return sorted(res, key=cmp_to_key(_cmp))
def _cmp(x, y):
x = x.first_phase_start_date if isinstance(x, Module) else x.date
if x is None:
return 1
y = y.first_phase_start_date if isinstance(y, Module) else y.date
if y is None:
return -1
return (x > y) - (y < x)
@register.filter
def is_phase(obj):
return isinstance(obj, Phase)
@register.filter
def is_module(obj):
return isinstance(obj, Module)
@register.filter
def is_offlineevent(obj):
return isinstance(obj, OfflineEvent)
|
from django import template
from adhocracy4.modules.models import Module
from adhocracy4.phases.models import Phase
from meinberlin.apps.offlineevents.models import OfflineEvent
register = template.Library()
@register.assignment_tag
def offlineevents_and_modules_sorted(project):
modules = list(project.module_set.all())
events = list(OfflineEvent.objects.filter(project=project))
res = modules + events
res_sorted = sorted(
res, key=lambda x: x.first_phase_start_date if
isinstance(x, Module) else x.date)
return res_sorted
@register.filter
def is_phase(obj):
return isinstance(obj, Phase)
@register.filter
def is_module(obj):
return isinstance(obj, Module)
@register.filter
def is_offlineevent(obj):
return isinstance(obj, OfflineEvent)
|
DEBUG true on deployment to see what's happening
|
"""
config.py
Looks for the RAD_PRODUCTION variable and creates path to database
"""
import os
_basedir = os.path.abspath(os.path.dirname(__file__))
class BaseConfig(object):
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'rad/rad.db')
MIGRATIONS_DIR = './remedy/rad/migrations'
SECRET_KEY = 'Our little secret'
class DevelopmentConfig(BaseConfig):
pass
class ProductionConfig(BaseConfig):
SQLALCHEMY_DATABASE_URI = 'mysql://{0}:{1}@{2}/{3}'.format(os.environ.get('RDS_USERNAME'),
os.environ.get('RDS_PASSWORD'),
os.environ.get('RDS_HOSTNAME'),
os.environ.get('RDS_DB_NAME'))
|
"""
config.py
Looks for the RAD_PRODUCTION variable and creates path to database
"""
import os
_basedir = os.path.abspath(os.path.dirname(__file__))
class BaseConfig(object):
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'rad/rad.db')
MIGRATIONS_DIR = './remedy/rad/migrations'
SECRET_KEY = 'Our little secret'
class DevelopmentConfig(BaseConfig):
pass
class ProductionConfig(BaseConfig):
DEBUG = False
SQLALCHEMY_DATABASE_URI = 'mysql://{0}:{1}@{2}/{3}'.format(os.environ.get('RDS_USERNAME'),
os.environ.get('RDS_PASSWORD'),
os.environ.get('RDS_HOSTNAME'),
os.environ.get('RDS_DB_NAME'))
|
Add ice skating routes to used services
|
import {Schema} from 'normalizr';
import {normalizeActionName} from '../common/helpers';
export const UnitServices = {
MECHANICALLY_FROZEN_ICE: 33417,
ICE_SKATING_FIELD: 33418,
ICE_RINK: 33419,
SPEED_SKATING_TRACK: 33420,
ICE_SKATING_ROUTE: 33421,
SKI_TRACK: 33483,
DOG_SKI_TRACK: 33492
};
export const IceSkatingServices = [
UnitServices.MECHANICALLY_FROZEN_ICE,
UnitServices.ICE_SKATING_FIELD,
UnitServices.ICE_RINK,
UnitServices.SPEED_SKATING_TRACK,
UnitServices.ICE_SKATING_ROUTE
];
export const SkiingServices = [
UnitServices.SKI_TRACK,
UnitServices.DOG_SKI_TRACK
];
export const SwimmingServices = [];
export const ServiceActions = {
FETCH: normalizeActionName('service/FETCH'),
RECEIVE: normalizeActionName('service/RECEIVE'),
FETCH_ERROR: normalizeActionName('service/FETCH_ERROR')
};
export type UnitState = {
isFetching: boolean,
byId: Object,
// Filtered arrays of ids
all: Array<string>,
skating: Array<string>,
skiing: Array<string>,
searchResults: Array<string>
};
export const serviceSchema = new Schema('service'/*, {}*/);
|
import {Schema} from 'normalizr';
import {normalizeActionName} from '../common/helpers';
export const UnitServices = {
MECHANICALLY_FROZEN_ICE: 33417,
ICE_SKATING_FIELD: 33418,
ICE_RINK: 33419,
SPEED_SKATING_TRACK: 33420,
SKI_TRACK: 33483,
DOG_SKI_TRACK: 33492
};
export const IceSkatingServices = [
UnitServices.MECHANICALLY_FROZEN_ICE,
UnitServices.ICE_SKATING_FIELD,
UnitServices.ICE_RINK,
UnitServices.SPEED_SKATING_TRACK
];
export const SkiingServices = [
UnitServices.SKI_TRACK,
UnitServices.DOG_SKI_TRACK
];
export const SwimmingServices = [];
export const ServiceActions = {
FETCH: normalizeActionName('service/FETCH'),
RECEIVE: normalizeActionName('service/RECEIVE'),
FETCH_ERROR: normalizeActionName('service/FETCH_ERROR')
};
export type UnitState = {
isFetching: boolean,
byId: Object,
// Filtered arrays of ids
all: Array<string>,
skating: Array<string>,
skiing: Array<string>,
searchResults: Array<string>
};
export const serviceSchema = new Schema('service'/*, {}*/);
|
Add a link to the forum thread about Heavyer Ink
|
<?php
/* Tab Menu */
$tabs = array(
array( 'url'=>"index.php", 'label'=>"Home" ),
/*array( 'url'=>"stats.php", 'label'=>"Stats" ),*/
array( 'url'=>"https://heavyink.com/forums/1/topics/2655", 'label'=>"Discuss" ),
array( 'url'=>"http://heavyink.com/", 'label'=>"HeavyInk" ) /* TODO: add a togle for Heavy/er Ink */
);
?>
<div class="nav tabs">
<ul>
<?php
foreach ($tabs as $tab):
$class = (isset($heri_selected_tab) && $heri_selected_tab == $tab['label'])
? "class=\"selected\"" : "";
$target = ( substr($tab['url'],0,4) == "http" )
? "target=\"_blank\"" : "";
?>
<li <?=$class;?>><a href="<?=$tab['url'];?>" <?=$target;?>><?=$tab['label'];?></a></li>
<?php
endforeach;
?>
</ul>
</div>
|
<?php
/* Tab Menu */
$tabs = array(
array( 'url'=>"index.php", 'label'=>"Home" ),
/*array( 'url'=>"stats.php", 'label'=>"Stats" ),*/
array( 'url'=>"http://heavyink.com/", 'label'=>"HeavyInk" ) /* TODO: add a togle for Heavy/er Ink */
);
?>
<div class="nav tabs">
<ul>
<?php
foreach ($tabs as $tab):
$class = (isset($heri_selected_tab) && $heri_selected_tab == $tab['label'])
? "class=\"selected\"" : "";
$target = ( substr($tab['url'],0,4) == "http" )
? "target=\"_blank\"" : "";
?>
<li <?=$class;?>><a href="<?=$tab['url'];?>" <?=$target;?>><?=$tab['label'];?></a></li>
<?php
endforeach;
?>
</ul>
</div>
|
Add link to partners in workhsops landing
|
<div class="partner">
<div class="container">
<div class="row">
<div class="col-md-offset-3 col-md-2 col-sm-4 col-xs-12">
<a target="_blank" href="https://aracoop.coop/projectes-singulars/">
<img class="img-responsive no-title" src="<?= SRC_URL . '/assets/img/workshop/ess.png' ?>">
</a>
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
<div class="title"><?= $this->text('workshsop-partner-promote') ?></div>
<img class="img-responsive" src="<?= SRC_URL . '/assets/img/workshop/treball.jpg' ?>">
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
<div class="title"><?= $this->text('workshsop-partner-finances') ?></div>
<img class="img-responsive" src="<?= SRC_URL . '/assets/img/workshop/mte.jpg' ?>">
</div>
</div>
</div>
</div>
|
<div class="partner">
<div class="container">
<div class="row">
<div class="col-md-offset-3 col-md-2 col-sm-4 col-xs-12">
<img class="img-responsive no-title" src="<?= SRC_URL . '/assets/img/workshop/ess.png' ?>">
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
<div class="title"><?= $this->text('workshsop-partner-promote') ?></div>
<img class="img-responsive" src="<?= SRC_URL . '/assets/img/workshop/treball.jpg' ?>">
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
<div class="title"><?= $this->text('workshsop-partner-finances') ?></div>
<img class="img-responsive" src="<?= SRC_URL . '/assets/img/workshop/mte.jpg' ?>">
</div>
</div>
</div>
</div>
|
Refactor login hook and re-enable success check
|
protractor.expect = {
challengeSolved: function (context) {
describe('(shared)', () => {
beforeEach(() => {
browser.get('/#/score-board')
})
it("challenge '" + context.challenge + "' should be solved on score board", () => {
expect(element(by.id(context.challenge + '.solved')).getAttribute('class')).not.toMatch('ng-hide')
expect(element(by.id(context.challenge + '.notSolved')).getAttribute('class')).toMatch('ng-hide')
})
})
}
}
protractor.beforeEach = {
login: function (context) {
describe('(shared)', () => {
beforeEach(() => {
browser.get('/#/login')
element(by.model('user.email')).sendKeys(context.email)
element(by.model('user.password')).sendKeys(context.password)
element(by.id('loginButton')).click()
})
it('should have logged in user "' + context.email + '" with password "' + context.password + '"', () => {
expect(browser.getCurrentUrl()).toMatch(/\/search/) // TODO Instead check for uib-tooltip of <i> with fa-user-circle
})
})
}
}
|
protractor.expect = {
challengeSolved: function (context) {
describe('(shared)', () => {
beforeEach(() => {
browser.get('/#/score-board')
})
it("challenge '" + context.challenge + "' should be solved on score board", () => {
expect(element(by.id(context.challenge + '.solved')).getAttribute('class')).not.toMatch('ng-hide')
expect(element(by.id(context.challenge + '.notSolved')).getAttribute('class')).toMatch('ng-hide')
})
})
}
}
protractor.beforeEach = {
login: function (context) {
describe('(shared)', () => {
let email, password
beforeEach(() => {
email = context.email
password = context.password
browser.get('/#/login')
element(by.model('user.email')).sendKeys(email)
element(by.model('user.password')).sendKeys(password)
element(by.id('loginButton')).click()
})
})
}
}
|
Support html classes through meta
|
'use strict';
var assign = require('es5-ext/object/assign')
, mixin = require('es5-ext/object/mixin')
, d = require('d')
, autoBind = require('d/auto-bind')
, DOMRadio = require('dbjs-dom/input/enum').Radio
, RadioBtnGroup = require('./inline-button-group')
, createOption = DOMRadio.prototype.createOption
, reload = DOMRadio.prototype.reload
, Radio;
module.exports = Radio = function (document, type/*, options*/) {
var options = Object(arguments[2]);
this.controlsOptions = Object(options.controls);
type.meta.forEach(function (itemMeta, name) {
if (itemMeta.htmlClass) this[name] = itemMeta.htmlClass;
}, this.classMap = {});
DOMRadio.call(this, document, type, options);
};
Radio.prototype = Object.create(DOMRadio.prototype);
mixin(Radio.prototype, RadioBtnGroup.prototype);
Object.defineProperties(Radio.prototype, assign({
constructor: d(Radio),
createOption: d(function (name) {
var dom = createOption.call(this, name);
this.listItems[name] = dom = dom.firstChild;
return dom;
})
}, autoBind({
reload: d(function () {
reload.apply(this, arguments);
this.dom.insertBefore(this.classHandlerScript, this.dom.firstChild);
})
})));
|
'use strict';
var assign = require('es5-ext/object/assign')
, mixin = require('es5-ext/object/mixin')
, d = require('d')
, autoBind = require('d/auto-bind')
, DOMRadio = require('dbjs-dom/input/enum').Radio
, RadioBtnGroup = require('./inline-button-group')
, createOption = DOMRadio.prototype.createOption
, reload = DOMRadio.prototype.reload
, Radio;
module.exports = Radio = function (document, type/*, options*/) {
var options = Object(arguments[2]);
this.controlsOptions = Object(options.controls);
DOMRadio.call(this, document, type, options);
};
Radio.prototype = Object.create(DOMRadio.prototype);
mixin(Radio.prototype, RadioBtnGroup.prototype);
Object.defineProperties(Radio.prototype, assign({
constructor: d(Radio),
createOption: d(function (name) {
var dom = createOption.call(this, name);
this.listItems[name] = dom = dom.firstChild;
return dom;
})
}, autoBind({
reload: d(function () {
reload.apply(this, arguments);
this.dom.insertBefore(this.classHandlerScript, this.dom.firstChild);
})
})));
|
Fix MongoDB auto configuration issue in integration tests
|
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.les;
import com.mangofactory.swagger.plugin.EnableSwagger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoDataAutoConfiguration;
import org.springframework.cloud.security.oauth2.resource.EnableOAuth2Resource;
@EnableOAuth2Resource
@SpringBootApplication
@EnableSwagger
@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
/**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.les;
import com.mangofactory.swagger.plugin.EnableSwagger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.security.oauth2.resource.EnableOAuth2Resource;
@EnableOAuth2Resource
@SpringBootApplication
@EnableSwagger
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
Check for the presence of $_SERVER
|
<?php
namespace COI\Social;
function getClassName($object) {
if (!is_object($object) && !is_string($object)) {
return false;
}
return trim(strrchr((is_string($object) ? $object : get_class($object)), '\\'), '\\');
}
function getCurrentUrl() {
if (!isset($_SERVER)) {
return '';
}
$pageURL = 'http';
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
$pageURL .= 's';
}
$pageURL .= '://';
if ($_SERVER['SERVER_PORT'] != '80') {
$pageURL .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
} else {
$pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
}
return $pageURL;
}
|
<?php
namespace COI\Social;
function getClassName($object) {
if (!is_object($object) && !is_string($object)) {
return false;
}
return trim(strrchr((is_string($object) ? $object : get_class($object)), '\\'), '\\');
}
function getCurrentUrl() {
$pageURL = 'http';
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
$pageURL .= 's';
}
$pageURL .= '://';
if ($_SERVER['SERVER_PORT'] != '80') {
$pageURL .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
} else {
$pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
}
return $pageURL;
}
|
Include i18n URLs in sandbox
|
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from apps.app import application
from accounts.dashboard.app import application as accounts_app
from accounts.views import AccountBalanceView
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^giftcard-balance/', AccountBalanceView.as_view(),
name="account-balance"),
(r'^dashboard/accounts/', include(accounts_app.urls)),
(r'', include(application.urls)),
)
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
urlpatterns += patterns('',
url(r'^404$', TemplateView.as_view(template_name='404.html')),
url(r'^500$', TemplateView.as_view(template_name='500.html')))
|
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from apps.app import application
from accounts.dashboard.app import application as accounts_app
from accounts.views import AccountBalanceView
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
url(r'^giftcard-balance/', AccountBalanceView.as_view(),
name="account-balance"),
(r'^dashboard/accounts/', include(accounts_app.urls)),
(r'', include(application.urls)),
)
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
urlpatterns += patterns('',
url(r'^404$', TemplateView.as_view(template_name='404.html')),
url(r'^500$', TemplateView.as_view(template_name='500.html')))
|
Add immutable code to Currency
[CurrencyBundle] Add AddCodeFormSubscriber to CurrencyType
[ResourceBundle] Modify AddCodeFormSubscriber to make possible passing type of code field
[Currency] Introduce code for Currency
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Currency\Model;
use Sylius\Component\Resource\Model\CodeAwareInterface;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;
use Sylius\Component\Resource\Model\ToggleableInterface;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface CurrencyInterface extends
CodeAwareInterface,
TimestampableInterface,
ToggleableInterface,
ResourceInterface
{
/**
* Get the human-friendly name.
*
* @return string
*/
public function getName();
/**
* @return float
*/
public function getExchangeRate();
/**
* @param float $rate
*/
public function setExchangeRate($rate);
}
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Currency\Model;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;
use Sylius\Component\Resource\Model\ToggleableInterface;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface CurrencyInterface extends
TimestampableInterface,
ToggleableInterface,
ResourceInterface
{
/**
* @return string
*/
public function getCode();
/**
* @param string $code
*/
public function setCode($code);
/**
* Get the human-friendly name.
*
* @return string
*/
public function getName();
/**
* @return float
*/
public function getExchangeRate();
/**
* @param float $rate
*/
public function setExchangeRate($rate);
}
|
Enable FF tracking Protection to speed up websites
|
user_pref("browser.backspace_action", 2);
user_pref("browser.bookmarks.max_backups", 2);
user_pref("browser.tabs.insertRelatedAfterCurrent", false);
user_pref("browser.urlbar.clickSelectsAll", true);
user_pref("browser.urlbar.trimURLs", false);
user_pref("devtools.inspector.enabled", false);
user_pref("devtools.styleinspector.enabled", false);
user_pref("dom.popup_maximum", 4);
user_pref("layout.spellcheckDefault", 2);
user_pref("layout.word_select.eat_space_to_next_word", true);
user_pref("network.dnsCacheEntries", 128);
user_pref("network.dnsCacheExpriation", 3600);
user_pref("network.http.pipelining", true);
user_pref("network.prefetch-next", false);
user_pref("plugins.click_to_play", true);
user_pref("privacy.trackingprotection.enabled", true);
|
user_pref("browser.backspace_action", 2);
user_pref("browser.bookmarks.max_backups", 2);
user_pref("browser.tabs.insertRelatedAfterCurrent", false);
user_pref("browser.urlbar.clickSelectsAll", true);
user_pref("browser.urlbar.trimURLs", false);
user_pref("devtools.inspector.enabled", false);
user_pref("devtools.styleinspector.enabled", false);
user_pref("dom.popup_maximum", 4);
user_pref("layout.spellcheckDefault", 2);
user_pref("layout.word_select.eat_space_to_next_word", true);
user_pref("network.dnsCacheEntries", 128);
user_pref("network.dnsCacheExpriation", 3600);
user_pref("network.http.pipelining", true);
user_pref("network.prefetch-next", false);
user_pref("plugins.click_to_play", true);
|
Fix use of deprecated find_module
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pkgutil
def test_imports():
"""
This just imports all modules in astropy, making sure they don't have any
dependencies that sneak through
"""
def onerror(name):
# We should raise any legitimate error that occurred, but not
# any warnings which happen to be caught because of our pytest
# settings (e.g., DeprecationWarning).
try:
raise
except Warning:
pass
for imper, nm, ispkg in pkgutil.walk_packages(['astropy'], 'astropy.',
onerror=onerror):
imper.find_spec(nm)
def test_toplevel_namespace():
import astropy
d = dir(astropy)
assert 'os' not in d
assert 'log' in d
assert 'test' in d
assert 'sys' not in d
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pkgutil
def test_imports():
"""
This just imports all modules in astropy, making sure they don't have any
dependencies that sneak through
"""
def onerror(name):
# We should raise any legitimate error that occurred, but not
# any warnings which happen to be caught because of our pytest
# settings (e.g., DeprecationWarning).
try:
raise
except Warning:
pass
for imper, nm, ispkg in pkgutil.walk_packages(['astropy'], 'astropy.',
onerror=onerror):
imper.find_module(nm)
def test_toplevel_namespace():
import astropy
d = dir(astropy)
assert 'os' not in d
assert 'log' in d
assert 'test' in d
assert 'sys' not in d
|
[native] Use hook instead of connect functions and HOC in ThreadSettingsVisibility
Test Plan: Flow
Reviewers: ashoat, palys-swm
Reviewed By: ashoat
Subscribers: zrebcu411, Adrian
Differential Revision: https://phabricator.ashoat.com/D479
|
// @flow
import type { ThreadInfo } from 'lib/types/thread-types';
import * as React from 'react';
import { Text, View } from 'react-native';
import ThreadVisibility from '../../components/thread-visibility.react';
import { useStyles, useColors } from '../../themes/colors';
type Props = {|
+threadInfo: ThreadInfo,
|};
function ThreadSettingsVisibility(props: Props) {
const styles = useStyles(unboundStyles);
const colors = useColors();
return (
<View style={styles.row}>
<Text style={styles.label}>Visibility</Text>
<ThreadVisibility
threadType={props.threadInfo.type}
color={colors.panelForegroundSecondaryLabel}
/>
</View>
);
}
const unboundStyles = {
label: {
color: 'panelForegroundTertiaryLabel',
fontSize: 16,
width: 96,
},
row: {
backgroundColor: 'panelForeground',
flexDirection: 'row',
paddingHorizontal: 24,
paddingVertical: 8,
},
};
export default ThreadSettingsVisibility;
|
// @flow
import type { ThreadInfo } from 'lib/types/thread-types';
import { connect } from 'lib/utils/redux-utils';
import * as React from 'react';
import { Text, View } from 'react-native';
import ThreadVisibility from '../../components/thread-visibility.react';
import type { AppState } from '../../redux/redux-setup';
import type { Colors } from '../../themes/colors';
import { colorsSelector, styleSelector } from '../../themes/colors';
type Props = {|
threadInfo: ThreadInfo,
// Redux state
colors: Colors,
styles: typeof styles,
|};
function ThreadSettingsVisibility(props: Props) {
return (
<View style={props.styles.row}>
<Text style={props.styles.label}>Visibility</Text>
<ThreadVisibility
threadType={props.threadInfo.type}
color={props.colors.panelForegroundSecondaryLabel}
/>
</View>
);
}
const styles = {
label: {
color: 'panelForegroundTertiaryLabel',
fontSize: 16,
width: 96,
},
row: {
backgroundColor: 'panelForeground',
flexDirection: 'row',
paddingHorizontal: 24,
paddingVertical: 8,
},
};
const stylesSelector = styleSelector(styles);
export default connect((state: AppState) => ({
colors: colorsSelector(state),
styles: stylesSelector(state),
}))(ThreadSettingsVisibility);
|
Allow crab to run on PRODUCTION datasets
|
__author__ = 'sbrochet'
def create_config(is_mc):
"""
Create a default CRAB configuration suitable to run the framework
:return:
"""
from CRABClient.UserUtilities import config, getUsernameFromSiteDB
config = config()
config.General.workArea = 'tasks'
config.General.transferOutputs = True
config.General.transferLogs = True
config.JobType.pluginName = 'Analysis'
config.JobType.disableAutomaticOutputCollection = True
config.JobType.outputFiles = []
config.JobType.allowUndistributedCMSSW = True
config.JobType.sendExternalFolder = True # To send electron MVA ids with jobs
config.Data.inputDBS = 'global'
config.Data.allowNonValidInputDataset = True
if is_mc:
config.Data.splitting = 'FileBased'
else:
config.Data.splitting = 'LumiBased'
config.Data.outLFNDirBase = '/store/user/%s/' % (getUsernameFromSiteDB())
config.Data.publication = False
config.Site.storageSite = 'T2_BE_UCL'
return config
|
__author__ = 'sbrochet'
def create_config(is_mc):
"""
Create a default CRAB configuration suitable to run the framework
:return:
"""
from CRABClient.UserUtilities import config, getUsernameFromSiteDB
config = config()
config.General.workArea = 'tasks'
config.General.transferOutputs = True
config.General.transferLogs = True
config.JobType.pluginName = 'Analysis'
config.JobType.disableAutomaticOutputCollection = True
config.JobType.outputFiles = []
config.JobType.allowUndistributedCMSSW = True
config.JobType.sendExternalFolder = True # To send electron MVA ids with jobs
config.Data.inputDBS = 'global'
if is_mc:
config.Data.splitting = 'FileBased'
else:
config.Data.splitting = 'LumiBased'
config.Data.outLFNDirBase = '/store/user/%s/' % (getUsernameFromSiteDB())
config.Data.publication = False
config.Site.storageSite = 'T2_BE_UCL'
return config
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.