text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix import error due to wrong import line | # Copyright (c) 2016, Daniele Venzano
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from zoe_lib.predefined_apps.copier import copier_app
from zoe_lib.predefined_apps.spark_interactive import spark_jupyter_notebook_app
from zoe_lib.predefined_apps.eurecom_aml_lab import spark_jupyter_notebook_lab_app
from zoe_lib.predefined_apps.hdfs import hdfs_app
from zoe_lib.predefined_apps.openmpi import openmpi_app
from zoe_lib.predefined_apps.spark_submit import spark_submit_app
from zoe_lib.predefined_apps.test_sleep import sleeper_app
PREDEFINED_APPS = [
copier_app,
spark_jupyter_notebook_app,
spark_jupyter_notebook_lab_app,
hdfs_app,
openmpi_app,
spark_submit_app,
sleeper_app
]
| # Copyright (c) 2016, Daniele Venzano
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from zoe_lib.predefined_apps.copier import copier_app
from zoe_lib.predefined_frameworks.jupyter_spark import spark_jupyter_notebook_app
from zoe_lib.predefined_apps.eurecom_aml_lab import spark_jupyter_notebook_lab_app
from zoe_lib.predefined_apps.hdfs import hdfs_app
from zoe_lib.predefined_apps.openmpi import openmpi_app
from zoe_lib.predefined_apps.spark_submit import spark_submit_app
from zoe_lib.predefined_apps.test_sleep import sleeper_app
PREDEFINED_APPS = [
copier_app,
spark_jupyter_notebook_app,
spark_jupyter_notebook_lab_app,
hdfs_app,
openmpi_app,
spark_submit_app,
sleeper_app
]
|
Make links type not nullable | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
class AddTypeToLinks extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('links', function (Blueprint $table) {
$table->string('type')->after('label')->nullable(false)->index();
});
DB::statement('UPDATE links SET type="external"');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('links', function (Blueprint $table) {
$table->dropColumn('type');
});
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
class AddTypeToLinks extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('links', function (Blueprint $table) {
$table->string('type')->after('label')->index();
});
DB::statement('UPDATE links SET type="external"');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('links', function (Blueprint $table) {
$table->dropColumn('type');
});
}
}
|
[svn] Tweak for exporting the symbols
--HG--
branch : trunk | import threadinglocal, sys
if sys.version < '2.4':
class _RequestConfig(object):
__shared_state = threadinglocal.local()
def __getattr__(self, name):
return self.__shared_state.__getattr__(name)
def __setattr__(self, name, value):
return self.__shared_state.__setattr__(name, value)
else:
class _RequestConfig(object):
__shared_state = threadinglocal.local()
def __getattr__(self, name):
return self.__shared_state.__getattribute__(name)
def __setattr__(self, name, value):
return self.__shared_state.__setattr__(name, value)
def request_config():
return _RequestConfig()
from base import Mapper
from util import url_for, redirect_to
__all__=['Mapper', 'url_for', 'redirect_to', 'request_config'] | import threadinglocal, sys
if sys.version < '2.4':
class _RequestConfig(object):
__shared_state = threadinglocal.local()
def __getattr__(self, name):
return self.__shared_state.__getattr__(name)
def __setattr__(self, name, value):
return self.__shared_state.__setattr__(name, value)
else:
class _RequestConfig(object):
__shared_state = threadinglocal.local()
def __getattr__(self, name):
return self.__shared_state.__getattribute__(name)
def __setattr__(self, name, value):
return self.__shared_state.__setattr__(name, value)
def request_config():
return _RequestConfig()
from base import Mapper
from util import url_for, redirect_to
|
Remove git commit/version from status endpoint
This is temporary for the purpose of getting running in
Docker with minimal build steps. | from flask import current_app, jsonify, request
from notifications_python_client.errors import HTTPError
from app import status_api_client
from app.status import status
@status.route("/_status", methods=["GET"])
def show_status():
if request.args.get("elb", None) or request.args.get("simple", None):
return jsonify(status="ok"), 200
else:
try:
api_status = status_api_client.get_status()
except HTTPError as e:
current_app.logger.exception("API failed to respond")
return jsonify(status="error", message=str(e.message)), 500
return jsonify(
status="ok",
api=api_status), 200
| from flask import current_app, jsonify, request
from notifications_python_client.errors import HTTPError
from app import status_api_client, version
from app.status import status
@status.route("/_status", methods=["GET"])
def show_status():
if request.args.get("elb", None) or request.args.get("simple", None):
return jsonify(status="ok"), 200
else:
try:
api_status = status_api_client.get_status()
except HTTPError as e:
current_app.logger.exception("API failed to respond")
return jsonify(status="error", message=str(e.message)), 500
return jsonify(status="ok", api=api_status, git_commit=version.__git_commit__, build_time=version.__time__), 200
|
Comment about keeping a commit together; also removed for loop where possible. | package disruptor
import "sync/atomic"
type SharedWriter struct {
written *Cursor
upstream Barrier
capacity int64
gate *Cursor
mask int64
shift uint8
committed []int32
}
func NewSharedWriter(write *SharedWriterBarrier, upstream Barrier) *SharedWriter {
return &SharedWriter{
written: write.written,
upstream: upstream,
capacity: write.capacity,
gate: NewCursor(),
mask: write.mask,
shift: write.shift,
committed: write.committed,
}
}
func (this *SharedWriter) Reserve(count int64) int64 {
for {
previous := this.written.Load()
upper := previous + count
for upper-this.capacity > this.gate.Load() {
this.gate.Store(this.upstream.Read(0))
}
if atomic.CompareAndSwapInt64(&this.written.sequence, previous, upper) {
return upper
}
}
}
func (this *SharedWriter) Commit(lower, upper int64) {
if lower == upper {
this.committed[upper&this.mask] = int32(upper >> this.shift)
} else {
// working down the array keeps all items in the commit together
// otherwise the reader(s) could split up the group
for upper >= lower {
this.committed[upper&this.mask] = int32(upper >> this.shift)
upper--
}
}
}
| package disruptor
import "sync/atomic"
type SharedWriter struct {
written *Cursor
upstream Barrier
capacity int64
gate *Cursor
mask int64
shift uint8
committed []int32
}
func NewSharedWriter(write *SharedWriterBarrier, upstream Barrier) *SharedWriter {
return &SharedWriter{
written: write.written,
upstream: upstream,
capacity: write.capacity,
gate: NewCursor(),
mask: write.mask,
shift: write.shift,
committed: write.committed,
}
}
func (this *SharedWriter) Reserve(count int64) int64 {
for {
previous := this.written.Load()
upper := previous + count
for upper-this.capacity > this.gate.Load() {
this.gate.Store(this.upstream.Read(0))
}
if atomic.CompareAndSwapInt64(&this.written.sequence, previous, upper) {
return upper
}
}
}
func (this *SharedWriter) Commit(lower, upper int64) {
// POTENTIAL TODO: start from upper and work toward lower
// this may have the effect of keeping a batch together which
// might otherwise be split up...
for lower <= upper {
this.committed[lower&this.mask] = int32(lower >> this.shift)
lower++
}
}
|
Throw instead of console for linter | function MockXHR() {
this.method = null
this.url = null
this.data = null
this.headers = {}
this.readyState = 0
this.status = 0
this.responseText = null
}
MockXHR.responses = {}
MockXHR.prototype.open = function(method, url) {
this.method = method
this.url = url
}
MockXHR.prototype.setRequestHeader = function (name, value) {
this.headers[name] = value
}
var origin = (function() {
var link = document.createElement('a')
link.href = '/'
return link.href
})()
MockXHR.prototype.send = function(data) {
this.data = data
var xhr = this
setTimeout(function() {
var path = xhr.url.replace(origin, '/')
var handle = MockXHR.responses[path]
if (handle) {
handle(xhr)
} else {
throw 'missing mocked response: ' + path
}
}, 100);
}
MockXHR.prototype.respond = function(status, body) {
this.readyState = 4
this.status = status
this.responseText = body
var event = {}
this.onload(event)
}
MockXHR.prototype.abort = function() {
// Do nothing.
}
MockXHR.prototype.slow = function() {
var event = {}
this.ontimeout(event)
}
MockXHR.prototype.error = function() {
var event = {}
this.onerror(event)
}
| function MockXHR() {
this.method = null
this.url = null
this.data = null
this.headers = {}
this.readyState = 0
this.status = 0
this.responseText = null
}
MockXHR.responses = {}
MockXHR.prototype.open = function(method, url) {
this.method = method
this.url = url
}
MockXHR.prototype.setRequestHeader = function (name, value) {
this.headers[name] = value
}
var origin = (function() {
var link = document.createElement('a')
link.href = '/'
return link.href
})()
MockXHR.prototype.send = function(data) {
this.data = data
var xhr = this
setTimeout(function() {
var path = xhr.url.replace(origin, '/')
var handle = MockXHR.responses[path]
if (handle) {
handle(xhr)
} else {
console.warn('missing mocked response', path)
}
}, 100);
}
MockXHR.prototype.respond = function(status, body) {
this.readyState = 4
this.status = status
this.responseText = body
var event = {}
this.onload(event)
}
MockXHR.prototype.abort = function() {
// Do nothing.
}
MockXHR.prototype.slow = function() {
var event = {}
this.ontimeout(event)
}
MockXHR.prototype.error = function() {
var event = {}
this.onerror(event)
}
|
Add test of detection using lanczos method | import unittest
import pandas as pd
from banpei.sst import SST
class TestSST(unittest.TestCase):
def setUp(self):
self.raw_data = pd.read_csv('tests/test_data/periodic_wave.csv')
self.data = self.raw_data['y']
def test_detect_by_svd(self):
model = SST(w=50)
results = model.detect(self.data)
self.assertEqual(len(self.data), len(results))
def test_detect_by_lanczos(self):
model = SST(w=50)
results = model.detect(self.data, is_lanczos=True)
self.assertEqual(len(self.data), len(results))
def test_stream_detect(self):
model = SST(w=50)
result = model.stream_detect(self.data)
self.assertIsInstance(result, float)
if __name__ == "__main__":
unittest.main()
| import unittest
import pandas as pd
from banpei.sst import SST
class TestSST(unittest.TestCase):
def setUp(self):
self.raw_data = pd.read_csv('tests/test_data/periodic_wave.csv')
self.data = self.raw_data['y']
def test_detect(self):
model = SST(w=50)
results = model.detect(self.data)
self.assertEqual(len(self.data), len(results))
def test_stream_detect(self):
model = SST(w=50)
result = model.stream_detect(self.data)
self.assertIsInstance(result, float)
if __name__ == "__main__":
unittest.main()
|
Add test for unexpected unicode kwargs. | from __future__ import print_function
import unittest
import wrapt
class TestArguments(unittest.TestCase):
def test_getcallargs(self):
def function(a, b=2, c=3, d=4, e=5, *args, **kwargs):
pass
expected = {'a': 10, 'c': 3, 'b': 20, 'e': 5, 'd': 40,
'args': (), 'kwargs': {'f': 50}}
calculated = wrapt.getcallargs(function, 10, 20, d=40, f=50)
self.assertEqual(expected, calculated)
expected = {'a': 10, 'c': 30, 'b': 20, 'e': 50, 'd': 40,
'args': (60,), 'kwargs': {}}
calculated = wrapt.getcallargs(function, 10, 20, 30, 40, 50, 60)
self.assertEqual(expected, calculated)
def test_unexpected_unicode_keyword(self):
def function(a=2):
pass
kwargs = { u'b': 40 }
self.assertRaises(TypeError, wrapt.getcallargs, function, **kwargs)
| from __future__ import print_function
import unittest
import wrapt
class TestArguments(unittest.TestCase):
def test_getcallargs(self):
def function(a, b=2, c=3, d=4, e=5, *args, **kwargs):
pass
expected = {'a': 10, 'c': 3, 'b': 20, 'e': 5, 'd': 40,
'args': (), 'kwargs': {'f': 50}}
calculated = wrapt.getcallargs(function, 10, 20, d=40, f=50)
self.assertEqual(expected, calculated)
expected = {'a': 10, 'c': 30, 'b': 20, 'e': 50, 'd': 40,
'args': (60,), 'kwargs': {}}
calculated = wrapt.getcallargs(function, 10, 20, 30, 40, 50, 60)
self.assertEqual(expected, calculated)
|
Allow to configure the virtualenv path from the Apache configuration | """
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moocng.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
#from django.core.wsgi import get_wsgi_application
#application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
def application(environ, start_response):
virtualenv = environ.get('VIRTUALENV', '/var/www')
activate_this = os.path.join(virtualenv, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
from django.core.wsgi import get_wsgi_application
django_app = get_wsgi_application()
return django_app(environ, start_response)
| """
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moocng.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
Use command help message edited | package cmd
import "github.com/codegangsta/cli"
var Commands = []cli.Command{
{
Name: "install",
ShortName: "i",
Usage: "Install specific Note.js version",
Action: Install,
},
{
Name: "use",
Usage: "Set specified Note.js version as current",
Action: Use,
},
{
Name: "remove",
ShortName: "rm",
Usage: "Remove installed Node.js version",
Action: Remove,
},
{
Name: "ls-remote",
ShortName: "lsr",
Usage: "List all available Note.js versions",
Action: LsRemote,
},
{
Name: "ls",
Usage: "List all installed Node.js versions",
Action: LsLocal,
},
}
| package cmd
import "github.com/codegangsta/cli"
var Commands = []cli.Command{
{
Name: "install",
ShortName: "i",
Usage: "Install specific Note.js version",
Action: Install,
},
{
Name: "use",
Usage: "Create symlink for specific Note.js version",
Action: Use,
},
{
Name: "remove",
ShortName: "rm",
Usage: "Remove installed Node.js version",
Action: Remove,
},
{
Name: "ls-remote",
ShortName: "lsr",
Usage: "List all available Note.js versions",
Action: LsRemote,
},
{
Name: "ls",
Usage: "List all installed Node.js versions",
Action: LsLocal,
},
}
|
Refresh access token while we're at it. | package com.uwetrottmann.getglue;
import junit.framework.TestCase;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import java.io.IOException;
public abstract class BaseTestCase extends TestCase {
protected static final String CLIENT_ID = "7FD930E5C9D030F696ACA631343EB3";
protected static final String CLIENT_SECRET = "EB4B93F673B95A5A2460CF983BB0A4";
private static final String TEMPORARY_ACCESS_TOKEN = "CF604DD9FB0FE147C0CD589C4F0B95"; /* Expires June 21, 2014, 1:13 p.m. */
protected static final String REDIRECT_URI = "http://localhost";
private final GetGlue mManager = new GetGlue();
@Override
protected void setUp() throws OAuthSystemException, IOException, OAuthProblemException {
getManager().setIsDebug(true);
getManager().setAccessToken(TEMPORARY_ACCESS_TOKEN);
}
protected final GetGlue getManager() {
return mManager;
}
}
| package com.uwetrottmann.getglue;
import junit.framework.TestCase;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import java.io.IOException;
public abstract class BaseTestCase extends TestCase {
protected static final String CLIENT_ID = "7FD930E5C9D030F696ACA631343EB3";
protected static final String CLIENT_SECRET = "EB4B93F673B95A5A2460CF983BB0A4";
private static final String TEMPORARY_ACCESS_TOKEN = "57EDD19812FCD9BFD12589AF24B9D2"; /* Expires April 23, 2014, 3:49 a.m. */
protected static final String REDIRECT_URI = "http://localhost";
private final GetGlue mManager = new GetGlue();
@Override
protected void setUp() throws OAuthSystemException, IOException, OAuthProblemException {
getManager().setIsDebug(true);
getManager().setAccessToken(TEMPORARY_ACCESS_TOKEN);
}
protected final GetGlue getManager() {
return mManager;
}
}
|
Enable Keystone's session auth for Rest API |
const keystone = require('keystone');
const jwt = require('jsonwebtoken');
/*
JWT middleware
*/
exports.requireJwtAuth = function(req, res, next) {
const errorMessage = {
badHeader: 'Bad request - missing JWT header',
unauthorized: 'Unauthorized - JWT',
};
// Enable auth with current Keystone's browser session
if (req.user) {
next();
return;
}
// Validate JWT header
if (!req.headers || !req.headers.authorization || !req.headers.authorization.startsWith("JWT ")) {
return res.status(400).json({ error: errorMessage.badHeader })
}
const token = req.headers.authorization.substr(4);
const secret = keystone._options.rest.jwtSecret;
// Decode and verify JWT header
try {
var decoded = jwt.verify(token, secret);
keystone.list('User').model.findOne({ _id: decoded.user }).exec(function(err, user) {
req.user = user;
next();
});
return;
} catch(err) {
// err
}
// Defaults to failure
return res.status(403).json({ error: errorMessage.unauthorized });
}
|
const keystone = require('keystone');
const jwt = require('jsonwebtoken');
/*
JWT middleware
*/
exports.requireJwtAuth = function(req, res, next) {
const errorMessage = {
badHeader: 'Bad request - missing JWT header',
unauthorized: 'Unauthorized - JWT',
};
if (!req.headers || !req.headers.authorization || !req.headers.authorization.startsWith("JWT ")) {
return res.status(400).json({ error: errorMessage.badHeader })
}
const token = req.headers.authorization.substr(4);
const secret = keystone._options.rest.jwtSecret;
try {
var decoded = jwt.verify(token, secret);
keystone.list('User').model.findOne({ _id: decoded.user }).exec(function(err, user) {
req.user = user;
next();
});
return;
} catch(err) {
// err
}
// if (req.headers.authorization === ) return next();
return res.status(403).json({ error: errorMessage.unauthorized });
}
|
Fix golint errors when generating informer code
Kubernetes-commit: acf78cd6133de6faea9221d8c53b02ca6009b0bb | /*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by informer-gen. DO NOT EDIT.
package internalinterfaces
import (
time "time"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
kubernetes "k8s.io/client-go/kubernetes"
cache "k8s.io/client-go/tools/cache"
)
// NewInformerFunc takes kubernetes.Interface and time.Duration to return a SharedIndexInformer.
type NewInformerFunc func(kubernetes.Interface, time.Duration) cache.SharedIndexInformer
// SharedInformerFactory a small interface to allow for adding an informer without an import cycle
type SharedInformerFactory interface {
Start(stopCh <-chan struct{})
InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer
}
// TweakListOptionsFunc is a function that transforms a v1.ListOptions.
type TweakListOptionsFunc func(*v1.ListOptions)
| /*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by informer-gen. DO NOT EDIT.
package internalinterfaces
import (
time "time"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
kubernetes "k8s.io/client-go/kubernetes"
cache "k8s.io/client-go/tools/cache"
)
type NewInformerFunc func(kubernetes.Interface, time.Duration) cache.SharedIndexInformer
// SharedInformerFactory a small interface to allow for adding an informer without an import cycle
type SharedInformerFactory interface {
Start(stopCh <-chan struct{})
InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer
}
type TweakListOptionsFunc func(*v1.ListOptions)
|
Update unittest to ignore disabled functions. | # OpenMV Unit Tests.
#
import os, sensor, gc
TEST_DIR = "unittest"
TEMP_DIR = "unittest/temp"
DATA_DIR = "unittest/data"
SCRIPT_DIR = "unittest/script"
if not (TEST_DIR in os.listdir("")):
raise Exception('Unittest dir not found!')
print("")
test_failed = False
def print_result(test, result):
s = "Unittest (%s)"%(test)
padding = "."*(60-len(s))
print(s + padding + result)
for test in sorted(os.listdir(SCRIPT_DIR)):
if test.endswith(".py"):
test_result = "PASSED"
test_path = "/".join((SCRIPT_DIR, test))
try:
exec(open(test_path).read())
gc.collect()
if unittest(DATA_DIR, TEMP_DIR) == False:
raise Exception()
except Exception as e:
test_failed = True
test_result = "DISABLED" if "unavailable" in str(e) else "FAILED"
print_result(test, test_result)
if test_failed:
print("\nSome tests have FAILED!!!\n\n")
else:
print("\nAll tests PASSED.\n\n")
| # OpenMV Unit Tests.
#
import os, sensor, gc
TEST_DIR = "unittest"
TEMP_DIR = "unittest/temp"
DATA_DIR = "unittest/data"
SCRIPT_DIR = "unittest/script"
if not (TEST_DIR in os.listdir("")):
raise Exception('Unittest dir not found!')
print("")
test_failed = False
def print_result(test, passed):
s = "Unittest (%s)"%(test)
padding = "."*(60-len(s))
print(s + padding + ("PASSED" if passed == True else "FAILED"))
for test in sorted(os.listdir(SCRIPT_DIR)):
if test.endswith(".py"):
test_passed = True
test_path = "/".join((SCRIPT_DIR, test))
try:
exec(open(test_path).read())
gc.collect()
if unittest(DATA_DIR, TEMP_DIR) == False:
raise Exception()
except Exception as e:
test_failed = True
test_passed = False
print_result(test, test_passed)
if test_failed:
print("\nSome tests have FAILED!!!\n\n")
else:
print("\nAll tests PASSED.\n\n")
|
Add temporary fix for odd outlook for ios user agent | // Check mobile platform
$(document).ready(function () {
// Temporary hack for oddball Outlook for iOS user agent
var ios = window.navigator.userAgent.match(/(Outlook-iOS)/);
if (ios) Framework7.prototype.device.ios = true;
if (Framework7.prototype.device.ios) {
// Redirect to iOS page
var iosPaneUrl = new URI('MobilePane-ios.html').absoluteTo(window.location).toString();
window.location.href = iosPaneUrl;
} else if (Framework7.prototype.device.android) {
$('#message').text('Android is not yet supported.');
} else {
$('#message').text('YOU SHOULD NOT BE HERE');
}
insertData('diag', 'User agent', window.navigator.userAgent);
insertData('diag', 'iOS', Framework7.prototype.device.ios);
insertData('diag', 'iPad', Framework7.prototype.device.ipad);
insertData('diag', 'iPhone', Framework7.prototype.device.iphone);
insertData('diag', 'Android', Framework7.prototype.device.android);
});
function insertData(id, headerText, valueText) {
var pane = $("#" + id);
var lf = $(document.createElement("br"));
var header = $(document.createElement("span"));
header.text(headerText + ': ');
var value = $(document.createElement("span"));
value.text(valueText);
pane.append(header);
pane.append(value);
pane.append(lf);
}
| // Check mobile platform
$(document).ready(function () {
if (Framework7.prototype.device.ios) {
// Redirect to iOS page
var iosPaneUrl = new URI('MobilePane-ios.html').absoluteTo(window.location).toString();
window.location.href = iosPaneUrl;
} else if (Framework7.prototype.device.android) {
$('#message').text('Android is not yet supported.');
} else {
$('#message').text('YOU SHOULD NOT BE HERE');
}
insertData('diag', 'User agent', window.navigator.userAgent);
insertData('diag', 'iOS', Framework7.prototype.device.ios);
insertData('diag', 'iPad', Framework7.prototype.device.ipad);
insertData('diag', 'iPhone', Framework7.prototype.device.iphone);
insertData('diag', 'Android', Framework7.prototype.device.android);
});
function insertData(id, headerText, valueText) {
var pane = $("#" + id);
var lf = $(document.createElement("br"));
var header = $(document.createElement("span"));
header.text(headerText + ': ');
var value = $(document.createElement("span"));
value.text(valueText);
pane.append(header);
pane.append(value);
pane.append(lf);
}
|
Allow deletedAt to be nullable | <?php
namespace Gedmo\SoftDeleteable\Traits;
/**
* SoftDeletable Trait, usable with PHP >= 5.4
*
* @author Wesley van Opdorp <wesley.van.opdorp@freshheads.com>
* @link http://www.gediminasm.org
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
trait SoftDeleteableEntity
{
/**
* @ORM\Column(type="datetime", nullable=true)
*/
protected $deletedAt;
/**
* Sets deletedAt.
*
* @param \Datetime|null $deletedAt
* @return $this
*/
public function setDeletedAt(\DateTime $deletedAt = null)
{
$this->deletedAt = $deletedAt;
return $this;
}
/**
* Returns deletedAt.
*
* @return DateTime
*/
public function getDeletedAt()
{
return $this->deletedAt;
}
}
| <?php
namespace Gedmo\SoftDeleteable\Traits;
/**
* SoftDeletable Trait, usable with PHP >= 5.4
*
* @author Wesley van Opdorp <wesley.van.opdorp@freshheads.com>
* @link http://www.gediminasm.org
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
trait SoftDeleteableEntity
{
/**
* @ORM\Column(type="datetime")
*/
protected $deletedAt;
/**
* Sets deletedAt.
*
* @param \Datetime|null $deletedAt
* @return $this
*/
public function setDeletedAt(\DateTime $deletedAt = null)
{
$this->deletedAt = $deletedAt;
return $this;
}
/**
* Returns deletedAt.
*
* @return DateTime
*/
public function getDeletedAt()
{
return $this->deletedAt;
}
}
|
Update null handling for enabledTemplates and excludedServiceIds | package com.hubspot.baragon.service.config;
import java.util.ArrayList;
import java.util.List;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.hubspot.baragon.models.BaragonService;
@JsonIgnoreProperties(ignoreUnknown = true)
public class PurgeCacheConfiguration {
@JsonProperty("enabledTemplates")
@NotNull
private List<String> enabledTemplates = new ArrayList<>();
@JsonProperty(value = "excludedServiceIds")
@NotNull
private List<String> excludedServiceIds = new ArrayList<>();
public List<String> getEnabledTemplates() {
return enabledTemplates;
}
public void setEnabledTemplates(List<String> enabledTemplates) {
this.enabledTemplates = enabledTemplates;
}
public List<String> getExcludedServiceIds() {
return excludedServiceIds;
}
public void setExcludedServiceIds(List<String> excludedServiceIds) {
this.excludedServiceIds = excludedServiceIds;
}
}
| package com.hubspot.baragon.service.config;
import java.util.ArrayList;
import java.util.List;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.hubspot.baragon.models.BaragonService;
@JsonIgnoreProperties(ignoreUnknown = true)
public class PurgeCacheConfiguration {
@JsonProperty("enabledTemplates")
@NotNull
private List<String> enabledTemplates;
@JsonProperty(value = "excludedServiceIds")
@NotNull
private List<String> excludedServiceIds;
public List<String> getEnabledTemplates() {
if (enabledTemplates == null) {
return new ArrayList<>();
}
return enabledTemplates;
}
public void setEnabledTemplates(List<String> enabledTemplates) {
this.enabledTemplates = enabledTemplates;
}
public List<String> getExcludedServiceIds() {
if (excludedServiceIds == null) {
return new ArrayList<>();
}
return excludedServiceIds;
}
public void setExcludedServiceIds(List<String> excludedServiceIds) {
this.excludedServiceIds = excludedServiceIds;
}
}
|
Update to new API endpoint | <?php
// Empty fallthrough response
$response = json_encode("{}");
switch(array_keys($_REQUEST)[0])
{
case 'building':
if ($_REQUEST['building'] > 0 && $_REQUEST['building'] < 1000)
{
if (array_key_exists('live', $_REQUEST) && $_REQUEST['live'] == true)
// Only live data
$response = file_get_contents('https://energy.itsapps.unc.edu/energy/rest/buildings/' . $_REQUEST['building'] . '/live');
else
// Live and historical data
$response = file_get_contents('https://energy.itsapps.unc.edu/energy/rest/buildings/' . $_REQUEST['building']);
}
break;
case 'campus':
// Aggregate data
$response = file_get_contents('https://energy.itsapps.unc.edu/energy/rest/campus');
break;
}
// Return
header('Content-Type: application/json');
echo($response);
?>
| <?php
// Empty fallthrough response
$response = json_encode("{}");
switch(array_keys($_REQUEST)[0])
{
case 'building':
if ($_REQUEST['building'] > 0 && $_REQUEST['building'] < 1000)
{
if (array_key_exists('live', $_REQUEST) && $_REQUEST['live'] == true)
// Only live data
$response = file_get_contents('https://itsapps.unc.edu/energy/rest/buildings/' . $_REQUEST['building'] . '/live');
else
// Live and historical data
$response = file_get_contents('https://itsapps.unc.edu/energy/rest/buildings/' . $_REQUEST['building']);
}
break;
case 'campus':
// Aggregate data
$response = file_get_contents('https://itsapps.unc.edu/energy/rest/campus');
break;
}
// Return
header('Content-Type: application/json');
echo($response);
?>
|
Add exception logging to Handlers | """Handle handlers."""
import logging
class Handlers(object):
"""Handlers."""
def __init__(self, *handlers):
self.logger = logging.getLogger(__name__)
self.handlers = handlers
def handle(self, event, packet):
"""Handle incoming data."""
for handler in self.handlers:
if hasattr(handler, "on_" + event):
response = ""
try:
response = getattr(handler, "on_" + event)(packet)
except Exception as e:
self.logger.warning(e)
else:
if response is StopIteration:
break
yield response
class Handler(object):
"""Handler."""
def __init__(self):
self.logger = logging.getLogger(__name__)
| """Handle handlers."""
import logging
class Handlers(object):
"""Handlers."""
def __init__(self, *handlers):
self.handlers = handlers
def handle(self, event, packet):
"""Handle incoming data."""
for handler in self.handlers:
if hasattr(handler, "on_" + event):
response = ""
try:
response = getattr(handler, "on_" + event)(packet)
except Exception as e:
print("Uh oh!")
print(e)
else:
if response is StopIteration:
break
yield response
class Handler(object):
"""Handler."""
def __init__(self):
self.logger = logging.getLogger(__name__)
|
Use default settings if no user settings | from os.path import basename
from website import settings
def serialize_addon_config(config):
lookup = config.template_lookup
return {
'addon_short_name': config.short_name,
'addon_full_name': config.full_name,
'node_settings_template': lookup.get_template(basename(config.node_settings_template)),
'user_settings_template': lookup.get_template(basename(config.user_settings_template)),
}
def get_addons_by_config_type(config_type, user):
addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs]
addon_settings = []
for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower()):
short_name = addon_config.short_name
config = serialize_addon_config(addon_config)
user_settings = user.get_addon(short_name)
if user_settings:
user_settings = user_settings.to_json(user)
config.update({
'user_settiongs': user_settings or addon_config.DEFAULT_SETTINGS,
})
addon_settings.append(config)
return addon_settings
| from os.path import basename
from website import settings
def serialize_addon_config(config):
lookup = config.template_lookup
return {
'addon_short_name': config.short_name,
'addon_full_name': config.full_name,
'node_settings_template': lookup.get_template(basename(config.node_settings_template)),
'user_settings_template': lookup.get_template(basename(config.user_settings_template)),
}
def get_addons_by_config_type(config_type, user):
addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs]
addon_settings = []
for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower()):
short_name = addon_config.short_name
config = serialize_addon_config(addon_config)
user_settings = user.get_addon(short_name)
if user_settings:
user_settings = user_settings.to_json(user)
config.update({
'user_settings': user_settings,
})
addon_settings.append(config)
return addon_settings
|
Change default terminal resize arguments | # -*- coding: iso-8859-15 -*-
"""Main HTTP routes request handlers."""
import tornado.web
import tornado.escape
from os import getcwd
class MainHandler(tornado.web.RequestHandler):
"""Handles creation of new terminals."""
@tornado.gen.coroutine
def post(self):
"""POST verb: Create a new terminal."""
rows = int(self.get_argument('rows', default=23))
cols = int(self.get_argument('cols', default=73))
cwd = self.get_cookie('cwd', default=getcwd())
self.application.logger.info('CWD: {0}'.format(cwd))
self.application.logger.info('Size: ({0}, {1})'.format(cols, rows))
pid = yield self.application.term_manager.create_term(rows, cols, cwd)
self.write(pid)
class ResizeHandler(tornado.web.RequestHandler):
"""Handles resizing of terminals."""
@tornado.gen.coroutine
def post(self, pid):
"""POST verb: Resize a terminal."""
rows = int(self.get_argument('rows', default=23))
cols = int(self.get_argument('cols', default=73))
self.application.term_manager.resize_term(pid, rows, cols)
| # -*- coding: iso-8859-15 -*-
"""Main HTTP routes request handlers."""
import tornado.web
import tornado.escape
from os import getcwd
class MainHandler(tornado.web.RequestHandler):
"""Handles creation of new terminals."""
@tornado.gen.coroutine
def post(self):
"""POST verb: Create a new terminal."""
rows = int(self.get_argument('rows', default=23))
cols = int(self.get_argument('cols', default=73))
cwd = self.get_cookie('cwd', default=getcwd())
self.application.logger.info('CWD: {0}'.format(cwd))
self.application.logger.info('Size: ({0}, {1})'.format(cols, rows))
pid = yield self.application.term_manager.create_term(rows, cols, cwd)
self.write(pid)
class ResizeHandler(tornado.web.RequestHandler):
"""Handles resizing of terminals."""
@tornado.gen.coroutine
def post(self, pid):
"""POST verb: Resize a terminal."""
rows = int(self.get_argument('rows', None, 23))
cols = int(self.get_argument('cols', None, 73))
self.application.term_manager.resize_term(pid, rows, cols)
|
Fix data being blown away on profile screen when fetching projects
fbshipit-source-id: 1aeab38 | import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
import Profile from '../components/Profile';
const ownProfileQuery = gql`
{
viewer {
me {
id
username
firstName
lastName
email
profilePhoto
appCount
isLegacy
apps(limit: 15, offset: 0) {
id
fullName
iconUrl
packageName
description
lastPublishedTime
}
likes(limit: 15, offset: 0) {
id
}
}
}
}
`
export default graphql(ownProfileQuery, {
props: (props) => {
let { data } = props;
let user;
if (data.viewer && data.viewer.me) {
user = data.viewer.me;
}
return {
...props,
data: {
...data,
user,
},
};
},
options: {
returnPartialData: true,
forceFetch: true,
},
})(Profile);
| import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
import Profile from '../components/Profile';
const ownProfileQuery = gql`
{
viewer {
me {
id
username
firstName
lastName
email
profilePhoto
appCount
isLegacy
apps(limit: 15, offset: 0) {
id
fullName
iconUrl
packageName
description
lastPublishedTime
}
likes(limit: 15, offset: 0) {
id
}
}
}
}
`
export default graphql(ownProfileQuery, {
props: (props) => {
let { data } = props;
let user;
if (data.viewer && data.viewer.me) {
user = data.viewer.me;
}
return {
...props,
data: {
...data,
user,
},
};
},
options: {
forceFetch: true,
},
})(Profile);
|
Return the number of items in the queue | import events from 'events';
class Feeder extends events.EventEmitter {
queue = [];
pending = false;
feed(data) {
this.queue = this.queue.concat(data);
}
clear() {
this.queue = [];
this.pending = false;
}
size() {
return this.queue.length;
}
next() {
if (this.queue.length === 0) {
this.pending = false;
return false;
}
const data = this.queue.shift();
this.pending = true;
this.emit('data', data);
return data;
}
isPending() {
return this.pending;
}
}
export default Feeder;
| import events from 'events';
class Feeder extends events.EventEmitter {
queue = [];
pending = false;
feed(data) {
this.queue = this.queue.concat(data);
}
clear() {
this.queue = [];
this.pending = false;
}
next() {
if (this.queue.length === 0) {
this.pending = false;
return false;
}
const data = this.queue.shift();
this.pending = true;
this.emit('data', data);
return data;
}
isPending() {
return this.pending;
}
}
export default Feeder;
|
Revert channel debugging since it breaks react-native | export class AddonStore {
constructor() {
this.loaders = {};
this.panels = {};
// this.channel should get overwritten by setChannel if package versions are
// correct and AddonStore is a proper singleton. If not, throw an error.
this.channel = null;
this.preview = null;
this.database = null;
}
getChannel() {
return this.channel;
}
setChannel(channel) {
this.channel = channel;
}
getPreview() {
return this.preview;
}
setPreview(preview) {
this.preview = preview;
}
getDatabase() {
return this.database;
}
setDatabase(database) {
this.database = database;
}
getPanels() {
return this.panels;
}
addPanel(name, panel) {
this.panels[name] = panel;
}
register(name, loader) {
this.loaders[name] = loader;
}
loadAddons(api) {
Object.keys(this.loaders).map(name => this.loaders[name]).forEach(loader => loader(api));
}
}
export default new AddonStore();
| function channelError() {
throw new Error(
'Accessing nonexistent addons channel, see https://storybook.js.org/basics/faq/#why-is-there-no-addons-channel'
);
}
export class AddonStore {
constructor() {
this.loaders = {};
this.panels = {};
// this.channel should get overwritten by setChannel if package versions are
// correct and AddonStore is a proper singleton. If not, throw an error.
this.channel = { on: channelError, emit: channelError };
this.preview = null;
this.database = null;
}
getChannel() {
return this.channel;
}
setChannel(channel) {
this.channel = channel;
}
getPreview() {
return this.preview;
}
setPreview(preview) {
this.preview = preview;
}
getDatabase() {
return this.database;
}
setDatabase(database) {
this.database = database;
}
getPanels() {
return this.panels;
}
addPanel(name, panel) {
this.panels[name] = panel;
}
register(name, loader) {
this.loaders[name] = loader;
}
loadAddons(api) {
Object.keys(this.loaders).map(name => this.loaders[name]).forEach(loader => loader(api));
}
}
export default new AddonStore();
|
Add a link to add a company in user profile
When a user change its experience, s⋅he can add an organization (not an
office) if it does not exist yet.
Link to autocomplete-light module's doc:
http://django-autocomplete-light.readthedocs.io/en/2.3.1/addanother.html#autocompletes.
Fix #3 | # -*- coding: utf-8
"""
ain7/annuaire/autocomplete_light_registry.py
"""
#
# Copyright © 2007-2016 AIn7 Devel Team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
#
from autocomplete_light import shortcuts as autocomplete_light
from ain7.organizations.models import (
Office, Organization, OrganizationActivityField
)
autocomplete_light.register(
Office,
search_fields=['name', 'organization__name'],
add_another_url_name='organization-add',
)
autocomplete_light.register(Organization)
autocomplete_light.register(OrganizationActivityField, search_fields=['label'])
| # -*- coding: utf-8
"""
ain7/annuaire/autocomplete_light_registry.py
"""
#
# Copyright © 2007-2016 AIn7 Devel Team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
#
from autocomplete_light import shortcuts as autocomplete_light
from ain7.organizations.models import (
Office, Organization, OrganizationActivityField
)
autocomplete_light.register(
Office,
search_fields=['name', 'organization__name'],
)
autocomplete_light.register(Organization)
autocomplete_light.register(OrganizationActivityField, search_fields=['label'])
|
Make sure we get Jackie Chan's name right | // register the grid component
Vue.component('demo-grid', {
template: '#grid-template',
replace: true,
props: {
data: Array,
columns: Array,
filterKey: String
},
data: function () {
var sortOrders = {}
this.columns.forEach(function (key) {
sortOrders[key] = 1
})
return {
sortKey: '',
sortOrders: sortOrders
}
},
methods: {
sortBy: function (key) {
this.sortKey = key
this.sortOrders[key] = this.sortOrders[key] * -1
}
}
})
// bootstrap the demo
var demo = new Vue({
el: '#demo',
data: {
searchQuery: '',
gridColumns: ['name', 'power'],
gridData: [
{ name: 'Chuck Norris', power: Infinity },
{ name: 'Bruce Lee', power: 9000 },
{ name: 'Jackie Chan', power: 7000 },
{ name: 'Jet Li', power: 8000 }
]
}
})
| // register the grid component
Vue.component('demo-grid', {
template: '#grid-template',
replace: true,
props: {
data: Array,
columns: Array,
filterKey: String
},
data: function () {
var sortOrders = {}
this.columns.forEach(function (key) {
sortOrders[key] = 1
})
return {
sortKey: '',
sortOrders: sortOrders
}
},
methods: {
sortBy: function (key) {
this.sortKey = key
this.sortOrders[key] = this.sortOrders[key] * -1
}
}
})
// bootstrap the demo
var demo = new Vue({
el: '#demo',
data: {
searchQuery: '',
gridColumns: ['name', 'power'],
gridData: [
{ name: 'Chuck Norris', power: Infinity },
{ name: 'Bruce Lee', power: 9000 },
{ name: 'Jacky Chang', power: 7000 },
{ name: 'Jet Li', power: 8000 }
]
}
})
|
Add default port for HAProxy | var fork = require('child_process').fork;
var async = require('async');
var amountConcurrentUsers = process.argv[2] || 200;
var host = process.argv[3] || 'http://localhost';
var initialPort = process.argv[4] || 3000;
var totalServers = process.argv[5] || 50;
var Client = require('./client');
var defaultHAProxyPort = 80;
var clientIdentifiers = [];
var clients = [];
for(var i = 0; i < amountConcurrentUsers; i++) {
clientIdentifiers.push(i);
};
console.log('Here we go');
console.log('amountConcurrentUsers: ' + amountConcurrentUsers);
console.log('Host: ' + host);
console.log('Initial port: ' + initialPort);
for(var j = 0; j < totalServers; j++) {
var port = (isHAProxyPort(defaultHAProxyPort, port)) ? defaultHAProxyPort : initialPort + j;
console.log('Connecting to port: ' + port);
async.each(clientIdentifiers, function(clientIdentifier) {
// clients[clientIdentifier] = fork('client.js', [host, port, clientIdentifier] );
console.log('Client: ' + clientIdentifier);
clients[clientIdentifier] = Client(host, port, port + '-' + clientIdentifier);
}, function(err){
console.log('UPSSS! Error!');
});
}
function isHAProxyPort(defaultHAProxyPort, port) {
return port === defaultHAProxyPort;
} | var fork = require('child_process').fork;
var async = require('async');
var amountConcurrentUsers = process.argv[2] || 200;
var host = process.argv[3] || 'http://localhost';
var initialPort = process.argv[4] || 3000;
var totalServers = process.argv[5] || 50;
var Client = require('./client');
var clientIdentifiers = [];
var clients = [];
for(var i = 0; i < amountConcurrentUsers; i++) {
clientIdentifiers.push(i);
};
console.log('Here we go');
console.log('amountConcurrentUsers: ' + amountConcurrentUsers);
console.log('Host: ' + host);
console.log('Initial port: ' + initialPort);
for(var j = 0; j < totalServers; j++) {
var port = initialPort + j;
console.log('connecting to port: ' + port);
async.each(clientIdentifiers, function(clientIdentifier) {
// clients[clientIdentifier] = fork('client.js', [host, port, clientIdentifier] );
console.log('Client: ' + clientIdentifier);
clients[clientIdentifier] = Client(host, port, port + '-' + clientIdentifier);
}, function(err){
console.log('UPSSS! Error!');
});
}
|
Revise to var n & add space line | """Leetcode 1. Two Sum
Easy
URL: https://leetcode.com/problems/two-sum/description/
Given an array of integers, return indices of the two numbers such that
they add up to a specific target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
"""
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
Time complexity: O(n).
Space complexity: O(n).
"""
num_idx_d = {}
for i, n in enumerate(nums):
if target - n in num_idx_d:
return [num_idx_d[target - n], i]
num_idx_d[n] = i
return []
def main():
print Solution().twoSum([2, 7, 11, 15], 9)
if __name__ == '__main__':
main()
| """Leetcode 1. Two Sum
Easy
URL: https://leetcode.com/problems/two-sum/description/
Given an array of integers, return indices of the two numbers such that
they add up to a specific target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
"""
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
Time complexity: O(n).
Space complexity: O(n).
"""
num_idx_d = {}
for i, num in enumerate(nums):
if target - num in num_idx_d:
return [num_idx_d[target - num], i]
num_idx_d[num] = i
return []
def main():
print Solution().twoSum([2, 7, 11, 15], 9)
if __name__ == '__main__':
main()
|
Use name =q (fix the onpage search) | import PropTypes from 'prop-types';
import React, { Fragment } from 'react';
/**
* The Search Results component
*
* @disable-docs
*/
const SearchResults = ( page ) => {
return (
<div className="container-fluid au-body">
<div className="row">
<div className="col-xs-12 searchresults__list">
<h2 className="au-display-xxl">{ page.heading }</h2>
<p><span id="searchresults__count" /> results for [query]</p>
<form className="search__searchbox" role="search" autoComplete="off" action="/search" method="get">
<input type="search" className="au-text-input" name="q" id="text-input" placeholder="Digital Guides"/>
<input type="submit" className="au-btn au-btn--light icon icon--search" value="Search" />
</form>
<ul className="searchresults__ul" id="searchresults__resultslist"></ul>
</div>
</div>
</div>
);
}
SearchResults.propTypes = {
/**
* _body: (partials)(4)
*/
_body: PropTypes.node.isRequired,
};
SearchResults.defaultProps = {};
export default SearchResults;
| import PropTypes from 'prop-types';
import React, { Fragment } from 'react';
/**
* The Search Results component
*
* @disable-docs
*/
const SearchResults = ( page ) => {
return (
<div className="container-fluid au-body">
<div className="row">
<div className="col-xs-12 searchresults__list">
<h2 className="au-display-xxl">{ page.heading }</h2>
<p><span id="searchresults__count" /> results for [query]</p>
<form className="search__searchbox" role="search" autoComplete="off" action="/search" method="get">
<input type="search" className="au-text-input" name="text-input" id="text-input" placeholder="Digital Guides"/>
<input type="submit" className="au-btn au-btn--light icon icon--search" value="Search" />
</form>
<ul className="searchresults__ul" id="searchresults__resultslist"></ul>
</div>
</div>
</div>
);
}
SearchResults.propTypes = {
/**
* _body: (partials)(4)
*/
_body: PropTypes.node.isRequired,
};
SearchResults.defaultProps = {};
export default SearchResults;
|
Add express-history-api-fallback to static app
Signed-off-by: Jordan Overbye <5b42e62121a3968f51bc2e512229a23195e6d9fe@gmail.com> | const fs = require('fs-extra');
const express = require('express');
const fallback = require('express-history-api-fallback');
const pathModule = require('path');
const getDistDir = (src, distDir) => {
const srcRelative = pathModule.relative(process.cwd(), src);
return pathModule.resolve(pathModule.join(distDir, srcRelative));
};
class StaticApp {
constructor({ path, src, fallback }) {
this._path = path;
this._src = src;
this._fallback = fallback;
}
prepareMiddleware({ dev, distDir }) {
const app = express();
const folderToServe = dev ? this._src : getDistDir(this._src, distDir);
app.use(this._path, express.static(folderToServe));
if (this._fallback) {
app.use(fallback(this._fallback, { root: folderToServe }));
}
return app;
}
build({ distDir }) {
const source = pathModule.resolve(this._src);
const destination = getDistDir(this._src, distDir);
return fs.copy(source, destination);
}
}
module.exports = {
StaticApp,
};
| const fs = require('fs-extra');
const express = require('express');
const pathModule = require('path');
const getDistDir = (src, distDir) => {
const srcRelative = pathModule.relative(process.cwd(), src);
return pathModule.resolve(pathModule.join(distDir, srcRelative));
};
class StaticApp {
constructor({ path, src }) {
this._path = path;
this._src = src;
}
prepareMiddleware({ dev, distDir }) {
const app = express();
const folderToServe = dev ? this._src : getDistDir(this._src, distDir);
app.use(this._path, express.static(folderToServe));
return app;
}
build({ distDir }) {
const source = pathModule.resolve(this._src);
const destination = getDistDir(this._src, distDir);
return fs.copy(source, destination);
}
}
module.exports = {
StaticApp,
};
|
Change style for better coverage report | import {Stream} from 'stream'
/**
* This is taken from event-stream npm module.
*
* Merges the given streams into a new stream.
*
* @param {Stream[]) toMerge streams to be merged
*/
export default function mergeStream(toMerge) {
const stream = new Stream()
stream.setMaxListeners(0) // allow adding more than 11 streams
let endCount = 0
stream.writable = stream.readable = true
toMerge.forEach(e => {
e.pipe(stream, {end: false})
let ended = false
e.on('end', () => {
if (ended) {
return
}
ended = true
endCount++
if (endCount === toMerge.length) {
stream.emit('end')
}
})
})
stream.write = function (data) {
this.emit('data', data)
}
return stream
}
| import {Stream} from 'stream'
/**
* This is taken from event-stream npm module.
*
* Merges the given streams into a new stream.
*
* @param {Stream[]) toMerge streams to be merged
*/
export default function mergeStream(toMerge) {
const stream = new Stream()
stream.setMaxListeners(0) // allow adding more than 11 streams
let endCount = 0
stream.writable = stream.readable = true
toMerge.forEach(e => {
e.pipe(stream, {end: false})
let ended = false
e.on('end', () => {
if (ended) { return }
ended = true
endCount++
if (endCount === toMerge.length) {
stream.emit('end')
}
})
})
stream.write = function (data) {
this.emit('data', data)
}
return stream
}
|
Set system notification sound to silent | import React, { Component, PropTypes } from 'react'
import { playAudio } from '../utils/audioplayer'
export default class Tap extends Component {
static PropTypes = {
receivedTaps: PropTypes.object,
users: PropTypes.object,
}
shouldComponentUpdate(nextProps, nextState) {
console.log(this.props.receivedTaps)
const render = this.props.receivedTaps.length !== 0 && !Object.is(this.props.receivedTaps, nextProps.receivedTaps)
return render
}
render() {
const {receivedTaps, users} = this.props
const displayName =
users && receivedTaps && receivedTaps.length > 0 ?
users[receivedTaps[receivedTaps.length - 1].from].displayName
:
null
if (displayName) {
const notificationText = `You received a tap from ${displayName}`
new Notification(notificationText, {silent: true})
playAudio()
console.log('ping')
}
return null
}
}
| import React, { Component, PropTypes } from 'react'
import { playAudio } from '../utils/audioplayer'
export default class Tap extends Component {
static PropTypes = {
receivedTaps: PropTypes.object,
users: PropTypes.object,
}
shouldComponentUpdate(nextProps, nextState) {
console.log(this.props.receivedTaps)
const render = this.props.receivedTaps.length !== 0 && !Object.is(this.props.receivedTaps, nextProps.receivedTaps)
return render
}
render() {
const {receivedTaps, users} = this.props
const displayName =
users && receivedTaps && receivedTaps.length > 0 ?
users[receivedTaps[receivedTaps.length - 1].from].displayName
:
null
if (displayName) {
const notificationText = `You received a tap from ${displayName}`
new Notification(notificationText)
playAudio()
console.log('ping')
}
return null
}
}
|
Revert "remove pandas from requirements"
This reverts commit b44d6a76eded00aa7ae03774548987c7c36455ac. | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 17 14:03 2013
@author: Mabel Calim Costa
"""
import os
from setuptools import setup
#from distutils.core import setup
for line in open('lib/waipy/__init__.py').readlines():
if line.startswith('__version__'):
exec(line.strip())
setup(
name = "waipy",
description = ("Wavelet Analysis in Python"),
version=__version__,
author='Mabel Calim Costa',
author_email='mabelcalim@gmail.com',
#url='https://wavelet-analysis.readthedocs.org/en/latest/index.html',
url = 'https://bitbucket.org/mabel/waipy/overview',
long_description="""
This guide includes a Continuous Wavelet Transform (CWT), significance
tests from based on Torrence and Compo (1998) and Cross Wavelet Analysis
(CWA) based on Maraun and Kurths(2004).""",
packages=['waipy', 'waipy.cwt', 'waipy.cwa' ],
package_dir={'':'lib'},
classifiers=['License :: OSI Approved :: BSD License'],
install_requires=['numpy', 'scipy', 'pandas', 'matplotlib'],
extras_require= {
'all': ["netCDF4", "jupyter"],
'load_netcdf': ["netCDF4"],
'jupyer': ["jupyter"],
},
)
| # -*- coding: utf-8 -*-
"""
Created on Mon Jun 17 14:03 2013
@author: Mabel Calim Costa
"""
import os
from setuptools import setup
#from distutils.core import setup
for line in open('lib/waipy/__init__.py').readlines():
if line.startswith('__version__'):
exec(line.strip())
setup(
name = "waipy",
description = ("Wavelet Analysis in Python"),
version=__version__,
author='Mabel Calim Costa',
author_email='mabelcalim@gmail.com',
#url='https://wavelet-analysis.readthedocs.org/en/latest/index.html',
url = 'https://bitbucket.org/mabel/waipy/overview',
long_description="""
This guide includes a Continuous Wavelet Transform (CWT), significance
tests from based on Torrence and Compo (1998) and Cross Wavelet Analysis
(CWA) based on Maraun and Kurths(2004).""",
packages=['waipy', 'waipy.cwt', 'waipy.cwa' ],
package_dir={'':'lib'},
classifiers=['License :: OSI Approved :: BSD License'],
install_requires=['numpy', 'scipy', 'matplotlib'],
extras_require= {
'all': ["netCDF4", "jupyter"],
'load_netcdf': ["netCDF4"],
'jupyer': ["jupyter"],
},
)
|
Add project URL to the distribution info | import codecs
import os
from setuptools import setup, find_packages
def read(filename):
filepath = os.path.join(os.path.dirname(__file__), filename)
return codecs.open(filepath, encoding='utf-8').read()
setup(
name='lemon-robots',
version='0.1.dev',
license='BSD',
description='robots.txt simple app for Django',
long_description=read('README.rst'),
url='https://github.com/trilan/lemon-robots',
author='Mike Yumatov',
author_email='mike@yumatov.org',
packages=find_packages(),
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
],
)
| import codecs
import os
from setuptools import setup, find_packages
def read(filename):
filepath = os.path.join(os.path.dirname(__file__), filename)
return codecs.open(filepath, encoding='utf-8').read()
setup(
name='lemon-robots',
version='0.1.dev',
license='BSD',
description='robots.txt simple app for Django',
long_description=read('README.rst'),
author='Mike Yumatov',
author_email='mike@yumatov.org',
packages=find_packages(),
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
],
)
|
Fix bug for API 404 error | const Router = require('express').Router(),
Util = require('../common/util.js');
// 导航栏菜单
Router.route('/navigation/menuTree')
.get(function(request, response) {
let protocal = Util.protocal();
protocal.head.status = 200;
protocal.head.message = 'http response sucess';
protocal.body = Util.json('/frame/data/navigation-menuTree.json');
response.json(protocal);
});
// 注销当前用户
Router.route('/logout')
.post(function(request, response) {
let protocal = Util.protocal();
protocal.head.status = 200;
protocal.head.message = '温馨提示:您已经退出系统!';
response.json(protocal);
});
module.exports = Router;
| const Router = require('express').Router(),
Util = require('../common/util.js');
// 导航栏菜单
Router.route('/navigation/menuTree')
.get(function(request, response) {
let protocal = Util.protocal();
protocal.head.status = 200;
protocal.head.message = 'http response sucess';
protocal.body = Util.json('/frame/data/navigation-menuTree.json');
response.json(protocal);
});
// 注销当前用户
Router.route('/logout')
.get(function(request, response) {
let protocal = Util.Protocal();
protocal.head.status = 200;
protocal.head.message = 'http response sucess';
response.json(protocal);
});
module.exports = Router;
|
Update the version before pushing to pypi | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='sophiabus230',
version='0.2',
description='Module to get the timetable of the Sophia Antipolis bus line 230',
url='http://github.com/paraita/sophiabus230',
author='Paraita Wohler',
author_email='paraita.wohler@gmail.com',
license='MIT',
packages=['sophiabus230'],
install_requires=[
'beautifulsoup4',
'python-dateutil'
],
test_suite='nose.collector',
tests_require=[
'mock',
'nose',
'coverage',
'coveralls'
],
zip_safe=False)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='sophiabus230',
version='0.1',
description='Module to get the timetable of the Sophia Antipolis bus line 230',
url='http://github.com/paraita/sophiabus230',
author='Paraita Wohler',
author_email='paraita.wohler@gmail.com',
license='MIT',
packages=['sophiabus230'],
install_requires=[
'beautifulsoup4',
'python-dateutil'
],
test_suite='nose.collector',
tests_require=[
'mock',
'nose',
'coverage',
'coveralls'
],
zip_safe=False)
|
Add nose to the requirements, why not? | from setuptools import setup
setup(
name='tattler',
author='Joe Friedl',
author_email='joe@joefriedl.net',
version='0.1',
description='A nose plugin that tattles on functions.',
keywords='nose plugin test testing mock',
url='https://github.com/grampajoe/tattler',
license='MIT',
py_modules=['tattler'],
install_requires=[
'nose',
'mock',
],
entry_points = {
'nose.plugins.0.10': [
'tattler = tattler:Tattler',
],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Plugins',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: Testing',
],
)
| from setuptools import setup
setup(
name='tattler',
author='Joe Friedl',
author_email='joe@joefriedl.net',
version='0.1',
description='A nose plugin that tattles on functions.',
keywords='nose plugin test testing mock',
url='https://github.com/grampajoe/tattler',
license='MIT',
py_modules=['tattler'],
install_requires=[
'mock',
],
entry_points = {
'nose.plugins.0.10': [
'tattler = tattler:Tattler',
],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Plugins',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: Testing',
],
)
|
Include utm_reader in stripped parameters | chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
var queryStringIndex = tab.url.indexOf('?');
if (tab.url.indexOf('utm_') > queryStringIndex) {
var stripped = tab.url.replace(
/([\?\&]utm_(source|medium|term|campaign|content|cid|reader)=[^&#]+)/ig,
'');
if (stripped.charAt(queryStringIndex) === '&') {
stripped = stripped.substr(0, queryStringIndex) + '?' +
stripped.substr(queryStringIndex + 1)
}
if (stripped != tab.url) {
chrome.tabs.update(tab.id, {url: stripped});
}
}
});
| chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
var queryStringIndex = tab.url.indexOf('?');
if (tab.url.indexOf('utm_') > queryStringIndex) {
var stripped = tab.url.replace(
/([\?\&]utm_(source|medium|term|campaign|content|cid)=[^&#]+)/ig,
'');
if (stripped.charAt(queryStringIndex) === '&') {
stripped = stripped.substr(0, queryStringIndex) + '?' +
stripped.substr(queryStringIndex + 1)
}
if (stripped != tab.url) {
chrome.tabs.update(tab.id, {url: stripped});
}
}
});
|
Fix the enable coverage issue | # -*- coding: utf-8 -*-
from mamba import settings, formatters, reporter, runners, example_collector
class ApplicationFactory(object):
def __init__(self, arguments):
self._instances = {}
self.arguments = arguments
def create_settings(self):
settings_ = settings.Settings()
settings_.slow_test_threshold = self.arguments.slow
settings_.enable_code_coverage = self.arguments.enable_coverage
return settings_
def create_formatter(self):
return formatters.DocumentationFormatter(self.create_settings())
def create_example_collector(self):
return example_collector.ExampleCollector(self.arguments.specs)
def create_reporter(self):
return reporter.Reporter(self.create_formatter())
def create_runner(self):
settings = self.create_settings()
if settings.enable_code_coverage:
return runners.CodeCoverageRunner(self.create_example_collector(), self.create_reporter())
return runners.Runner(self.create_example_collector(), self.create_reporter())
| # -*- coding: utf-8 -*-
from mamba import settings, formatters, reporter, runners, example_collector
class ApplicationFactory(object):
def __init__(self, arguments):
self._instances = {}
self.arguments = arguments
def create_settings(self):
settings_ = settings.Settings()
settings_.slow_test_threshold = self.arguments.slow
settings_.enable_coverage = self.arguments.enable_coverage
return settings_
def create_formatter(self):
return formatters.DocumentationFormatter(self.create_settings())
def create_example_collector(self):
return example_collector.ExampleCollector(self.arguments.specs)
def create_reporter(self):
return reporter.Reporter(self.create_formatter())
def create_runner(self):
settings = self.create_settings()
if settings.enable_coverage:
return runners.CodeCoverageRunner(self.create_example_collector(), self.create_reporter())
return runners.Runner(self.create_example_collector(), self.create_reporter())
|
Fix direct gulp - since node_modules are in path only when run with npm - direct gulp command was failing because of nodemon not in path | import bg from 'gulp-bg';
import eslint from 'gulp-eslint';
import gulp from 'gulp';
import runSequence from 'run-sequence';
import webpackBuild from './webpack/build';
const runEslint = () => {
return gulp.src([
'gulpfile.babel.js',
'src/**/*.js',
'webpack/*.js'
// '!**/__tests__/*.*'
])
.pipe(eslint())
.pipe(eslint.format());
};
// Always use Gulp only in development
gulp.task('set-dev-environment', () => {
process.env.NODE_ENV = 'development'; // eslint-disable-line no-undef
});
gulp.task('build', webpackBuild);
gulp.task('eslint', () => {
return runEslint();
});
gulp.task('eslint-ci', () => {
// Exit process with an error code (1) on lint error for CI build.
return runEslint().pipe(eslint.failAfterError());
});
gulp.task('test', (done) => {
runSequence('eslint-ci', 'build', done);
});
gulp.task('server-hot', bg('node', './webpack/server'));
gulp.task('server', ['set-dev-environment', 'server-hot'], bg('./node_modules/.bin/nodemon', './src/server'));
gulp.task('default', ['server']);
| import bg from 'gulp-bg';
import eslint from 'gulp-eslint';
import gulp from 'gulp';
import runSequence from 'run-sequence';
import webpackBuild from './webpack/build';
const runEslint = () => {
return gulp.src([
'gulpfile.babel.js',
'src/**/*.js',
'webpack/*.js'
// '!**/__tests__/*.*'
])
.pipe(eslint())
.pipe(eslint.format());
};
// Always use Gulp only in development
gulp.task('set-dev-environment', () => {
process.env.NODE_ENV = 'development'; // eslint-disable-line no-undef
});
gulp.task('build', webpackBuild);
gulp.task('eslint', () => {
return runEslint();
});
gulp.task('eslint-ci', () => {
// Exit process with an error code (1) on lint error for CI build.
return runEslint().pipe(eslint.failAfterError());
});
gulp.task('test', (done) => {
runSequence('eslint-ci', 'build', done);
});
gulp.task('server-hot', bg('node', './webpack/server'));
gulp.task('server', ['set-dev-environment', 'server-hot'], bg('nodemon', './src/server'));
gulp.task('default', ['server']);
|
Resolve promise before setting JSON | import * as React from "react";
import {BuildSnapshot} from "./BuildSnapshot";
/**
* Container Component for BuildSnapshots.
*
* @param {*} props input property containing an array of build data to be
* rendered through BuildSnapshot.
*/
export const BuildSnapshotContainer = React.memo((props) =>
{
const SOURCE = '/builders';
const [data, setData] = React.useState([]);
/**
* Fetch data when component is mounted.
* Pass in empty array as second paramater to prevent
* infinite callbacks as component refreshes.
* @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a>
*/
React.useEffect(() => {
fetch(SOURCE)
.then(res => res.json())
.then(json => setData(json))
.catch(setData([]));
}, []);
return (
<div>
{data.map(snapshotData => <BuildSnapshot buildData={snapshotData}/>)}
</div>
);
}
);
| import * as React from "react";
import {BuildSnapshot} from "./BuildSnapshot";
/**
* Container Component for BuildSnapshots.
*
* @param {*} props input property containing an array of build data to be
* rendered through BuildSnapshot.
*/
export const BuildSnapshotContainer = React.memo((props) =>
{
const SOURCE = '/builders';
const [data, setData] = React.useState([]);
/**
* Fetch data when component is mounted.
* Pass in empty array as second paramater to prevent
* infinite callbacks as component refreshes.
* @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a>
*/
React.useEffect(() => {
fetch(SOURCE).then(res => setData(res.json())).catch(setData([]));
}, []);
return (
<div>
{data.map(snapshotData => <BuildSnapshot buildData={snapshotData}/>)}
</div>
);
}
);
|
Fix an invalid coordinate in SpriteSheet | 'use strict';
import Sprite from './sprite';
export default class SpriteSheet {
constructor(texture, width, height) {
this.texture = texture;
this.width = width;
this.height = height;
this.spriteCoordinates = {};
}
register(name, x, y, width, height) {
this.spriteCoordinates[name] = {
x: x,
y: y,
width: width,
height: height
};
}
registerMany(map) {
for (var name in map) {
var coords = map[name];
this.register(name, coords[0], coords[1], coords[2], coords[3]);
}
}
createSprite(name) {
let info = this.spriteCoordinates[name];
let sprite = new Sprite(info.width, info.height, this.texture);
sprite.setTextureCoordinates(
info.x / this.width,
info.y / this.height,
(info.x + info.width) / this.width,
(info.y + info.height) / this.height
);
return sprite;
}
}
| 'use strict';
import Sprite from './sprite';
export default class SpriteSheet {
constructor(texture, width, height) {
this.texture = texture;
this.width = width;
this.height = height;
this.spriteCoordinates = {};
}
register(name, x, y, width, height) {
this.spriteCoordinates[name] = {
x: x,
y: y,
width: width,
height: height
};
}
registerMany(map) {
for (var name in map) {
var coords = map[name];
this.register(name, coords[0], coords[1], coords[2], coords[3]);
}
}
createSprite(name) {
let info = this.spriteCoordinates[name];
let sprite = new Sprite(info.width, info.height, this.texture);
sprite.setTextureCoordinates(
info.x / this.width,
info.y / this.height,
(info.x + info.width) / this.width,
(info.x + info.height) / this.height
);
return sprite;
}
}
|
Remove anchor and increase wait time for desk_intelwiki.skp
No-Try: true
Bug: skia:11804
Change-Id: Ib30df7f233bd3c2bcbfdf5c62e803be187a4ff01
Reviewed-on: https://skia-review.googlesource.com/c/skia/+/389712
Commit-Queue: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.com>
Reviewed-by: Robert Phillips <95e8ac5504948c7bf91b22c16a8dbb7ae7c66bfd@google.com> | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=W0401,W0614
from telemetry import story
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
class SkiaBuildbotDesktopPage(page_module.Page):
def __init__(self, url, page_set):
super(SkiaBuildbotDesktopPage, self).__init__(
url=url,
name=url,
page_set=page_set,
shared_page_state_class=shared_page_state.SharedDesktopPageState)
self.archive_data_file = 'data/skia_intelwiki_desktop.json'
def RunNavigateSteps(self, action_runner):
action_runner.Navigate(self.url)
action_runner.Wait(120)
class SkiaIntelwikiDesktopPageSet(story.StorySet):
""" Pages designed to represent the median, not highly optimized web """
def __init__(self):
super(SkiaIntelwikiDesktopPageSet, self).__init__(
archive_data_file='data/skia_intelwiki_desktop.json')
urls_list = [
# go/skia-skps-3-19
'https://en.wikipedia.org/wiki/Intel_Graphics_Technology',
]
for url in urls_list:
self.AddStory(SkiaBuildbotDesktopPage(url, self))
| # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=W0401,W0614
from telemetry import story
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
class SkiaBuildbotDesktopPage(page_module.Page):
def __init__(self, url, page_set):
super(SkiaBuildbotDesktopPage, self).__init__(
url=url,
name=url,
page_set=page_set,
shared_page_state_class=shared_page_state.SharedDesktopPageState)
self.archive_data_file = 'data/skia_intelwiki_desktop.json'
def RunNavigateSteps(self, action_runner):
action_runner.Navigate(self.url)
action_runner.Wait(30)
class SkiaIntelwikiDesktopPageSet(story.StorySet):
""" Pages designed to represent the median, not highly optimized web """
def __init__(self):
super(SkiaIntelwikiDesktopPageSet, self).__init__(
archive_data_file='data/skia_intelwiki_desktop.json')
urls_list = [
# go/skia-skps-3-19
'https://en.wikipedia.org/wiki/Intel_Graphics_Technology#Capabilities_(GPU_hardware)',
]
for url in urls_list:
self.AddStory(SkiaBuildbotDesktopPage(url, self))
|
Add scope_types to token revocation policies
This doesn't seem useful since the API will return an empty list
regardless because PKI support has been removed.
More or less doing this for consistency.
Change-Id: Iaa2925119fa6c9e2324546ed44aa54bac51dba05 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_policy import policy
from keystone.common.policies import base
token_revocation_policies = [
policy.DocumentedRuleDefault(
name=base.IDENTITY % 'revocation_list',
check_str=base.RULE_SERVICE_OR_ADMIN,
# NOTE(lbragstad): Documenting scope_types here doesn't really make a
# difference since this API is going to return an empty list regardless
# of the token scope used in the API call. More-or-less just doing this
# for consistency with other policies.
scope_types=['system', 'project'],
description='List revoked PKI tokens.',
operations=[{'path': '/v3/auth/tokens/OS-PKI/revoked',
'method': 'GET'}])
]
def list_rules():
return token_revocation_policies
| # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_policy import policy
from keystone.common.policies import base
token_revocation_policies = [
policy.DocumentedRuleDefault(
name=base.IDENTITY % 'revocation_list',
check_str=base.RULE_SERVICE_OR_ADMIN,
description='List revoked PKI tokens.',
operations=[{'path': '/v3/auth/tokens/OS-PKI/revoked',
'method': 'GET'}])
]
def list_rules():
return token_revocation_policies
|
Fix test so that it works with both CMS and LMS settings | from django.test import TestCase
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from django.conf import settings
from mitxmako.shortcuts import marketing_link
from mock import patch
class ShortcutsTests(TestCase):
"""
Test the mitxmako shortcuts file
"""
@override_settings(MKTG_URLS={'ROOT': 'dummy-root', 'ABOUT': '/about-us'})
@override_settings(MKTG_URL_LINK_MAP={'ABOUT': 'login'})
def test_marketing_link(self):
# test marketing site on
with patch.dict('django.conf.settings.MITX_FEATURES', {'ENABLE_MKTG_SITE': True}):
expected_link = 'dummy-root/about-us'
link = marketing_link('ABOUT')
self.assertEquals(link, expected_link)
# test marketing site off
with patch.dict('django.conf.settings.MITX_FEATURES', {'ENABLE_MKTG_SITE': False}):
# we are using login because it is common across both cms and lms
expected_link = reverse('login')
link = marketing_link('ABOUT')
self.assertEquals(link, expected_link)
| from django.test import TestCase
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from django.conf import settings
from mitxmako.shortcuts import marketing_link
from mock import patch
class ShortcutsTests(TestCase):
"""
Test the mitxmako shortcuts file
"""
@override_settings(MKTG_URLS={'ROOT': 'dummy-root', 'ABOUT': '/about-us'})
@override_settings(MKTG_URL_LINK_MAP={'ABOUT': 'about_edx'})
def test_marketing_link(self):
# test marketing site on
with patch.dict('django.conf.settings.MITX_FEATURES', {'ENABLE_MKTG_SITE': True}):
expected_link = 'dummy-root/about-us'
link = marketing_link('ABOUT')
self.assertEquals(link, expected_link)
# test marketing site off
with patch.dict('django.conf.settings.MITX_FEATURES', {'ENABLE_MKTG_SITE': False}):
expected_link = reverse('about_edx')
link = marketing_link('ABOUT')
self.assertEquals(link, expected_link)
|
Allow player to be defined from TMX file | window.addEventListener('load',function() {
var Q = Quintus({
development: true,
//audioPath: "assets/audio/",
imagePath: "assets/images/",
dataPath: "assets/data/"
})
.include("Sprites, Scenes, Input, TMX, Anim, 2D, Touch, UI, Audio")
.setup("quintusContainer")
.controls()
.touch()
.enableSound();
Q.gravityX = 0;
Q.gravityY = 0;
initComponents(Q);
initSprites(Q);
Q.scene("start",function(stage) {
Q.stageTMX('stage1.tmx', stage);
var spawner = stage.insert(new Q.EnemySpawner({
x: 15 * Q.DEFAULT_CELL_WIDTH,
y: 490 * Q.DEFAULT_CELL_HEIGHT,
}));
var player = stage.detect(function() { return this.p.team === 'players' });
stage.add('viewport').follow(player);
});
Q.loadTMX(
'stage1.tmx, tiles.png, ' +
'sprites/coder.png, ' +
'sprites/bug.png',
function() {
// Start the show
Q.stageScene("start");
// Turn on default keyboard controls
Q.input.keyboardControls();
});
});
| window.addEventListener('load',function() {
var Q = Quintus({
development: true,
//audioPath: "assets/audio/",
imagePath: "assets/images/",
dataPath: "assets/data/"
})
.include("Sprites, Scenes, Input, TMX, Anim, 2D, Touch, UI, Audio")
.setup("quintusContainer")
.controls()
.touch()
.enableSound();
Q.gravityX = 0;
Q.gravityY = 0;
initComponents(Q);
initSprites(Q);
Q.scene("start",function(stage) {
Q.stageTMX('stage1.tmx', stage);
// A basic sprite shape a asset as the image
var player = stage.insert(new Q.Player({ x: 10*Q.DEFAULT_CELL_WIDTH, y: 498*Q.DEFAULT_CELL_HEIGHT}));
var spawner = stage.insert(new Q.EnemySpawner({
x: 15 * Q.DEFAULT_CELL_WIDTH,
y: 490 * Q.DEFAULT_CELL_HEIGHT,
}));
stage.add('viewport').follow(player);
console.log("added player");
});
Q.loadTMX(
'stage1.tmx, tiles.png, ' +
'sprites/coder.png, ' +
'sprites/bug.png',
function() {
// Start the show
Q.stageScene("start");
// Turn on default keyboard controls
Q.input.keyboardControls();
});
});
|
Fix wrong value assignment for CertSubject in the return statement of ParseCert() function | #!/usr/bin/env python3
import datetime
import ssl
import OpenSSL
def GetCert(SiteName, Port):
return ssl.get_server_certificate((SiteName, Port))
def ParseCert(CertRaw):
Cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM, CertRaw)
CertSubject = str(Cert.get_subject())[18:-2]
CertStartDate = datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1],
'%Y%m%d%H%M%SZ')
CertEndDate = datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1],
'%Y%m%d%H%M%SZ')
CertIssuer = str(Cert.get_issuer())[18:-2]
return {'CertSubject': CertSubject, 'CertStartDate': CertStartDate,
'CertEndDate': CertEndDate, 'CertIssuer': CertIssuer}
CertRaw = GetCert('some.domain.tld', 443)
print(CertRaw)
Out = ParseCert(CertRaw)
print(Out)
print(Out['CertSubject'])
print(Out['CertStartDate'])
| #!/usr/bin/env python3
import datetime
import ssl
import OpenSSL
def GetCert(SiteName, Port):
return ssl.get_server_certificate((SiteName, Port))
def ParseCert(CertRaw):
Cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM, CertRaw)
CertSubject = str(Cert.get_subject())[18:-2]
CertStartDate = datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1],
'%Y%m%d%H%M%SZ')
CertEndDate = datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1],
'%Y%m%d%H%M%SZ')
CertIssuer = str(Cert.get_issuer())[18:-2]
return {'CertSubject': CertIssuer, 'CertStartDate': CertStartDate,
'CertEndDate': CertEndDate, 'CertIssuer': CertIssuer}
CertRaw = GetCert('some.domain.tld', 443)
print(CertRaw)
Out = ParseCert(CertRaw)
print(Out)
print(Out['CertSubject'])
print(Out['CertStartDate'])
|
Remove unnecessary import of util | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman,,,
# Copyright (c) 2014 Ethan Zimmerman,,,
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 0.2.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman,,,
# Copyright (c) 2014 Ethan Zimmerman,,,
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter, util
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 0.2.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
|
Fix BOM issue with latest strings | """
Hearthstone Strings file
File format: TSV. Lines starting with `#` are ignored.
Key is always `TAG`
"""
import csv
from typing import Dict
import hearthstone_data
StringsRow = Dict[str, str]
StringsDict = Dict[str, StringsRow]
_cache: Dict[str, StringsDict] = {}
def load(fp) -> StringsDict:
reader = csv.DictReader(
filter(lambda row: row.strip() and not row.startswith("#"), fp),
delimiter="\t"
)
stripped_rows = [{k: v for k, v in row.items() if v} for row in reader]
return {stripped_row.pop("TAG"): stripped_row for stripped_row in stripped_rows}
def load_globalstrings(locale="enUS") -> StringsDict:
path: str = hearthstone_data.get_strings_file(locale, filename="GLOBAL.txt")
if path not in _cache:
with open(path, "r", encoding="utf-8-sig") as f:
_cache[path] = load(f)
return _cache[path]
if __name__ == "__main__":
import json
import sys
for path in sys.argv[1:]:
with open(path, "r") as f:
print(json.dumps(load(f)))
| """
Hearthstone Strings file
File format: TSV. Lines starting with `#` are ignored.
Key is always `TAG`
"""
import csv
from typing import Dict
import hearthstone_data
StringsRow = Dict[str, str]
StringsDict = Dict[str, StringsRow]
_cache: Dict[str, StringsDict] = {}
def load(fp) -> StringsDict:
reader = csv.DictReader(
filter(lambda row: row.strip() and not row.startswith("#"), fp),
delimiter="\t"
)
stripped_rows = [{k: v for k, v in row.items() if v} for row in reader]
return {stripped_row.pop("TAG"): stripped_row for stripped_row in stripped_rows}
def load_globalstrings(locale="enUS") -> StringsDict:
path: str = hearthstone_data.get_strings_file(locale, filename="GLOBAL.txt")
if path not in _cache:
with open(path, "r") as f:
_cache[path] = load(f)
return _cache[path]
if __name__ == "__main__":
import json
import sys
for path in sys.argv[1:]:
with open(path, "r") as f:
print(json.dumps(load(f)))
|
Fix backend theme key in configuration | <?php
/**
* Created by PhpStorm.
* User: Michal
* Date: 8.1.14
* Time: 19:02
*/
namespace AnnotateCms\Themes\DI;
use AnnotateCms\Themes\Loaders\ThemesLoader;
use Kdyby\Events\DI\EventsExtension;
use Nette\DI\CompilerExtension;
class ThemesExtension extends CompilerExtension
{
private $defaults = array(
"frontend" => "Sandbox",
"backend" => "Flatty",
);
public function loadConfiguration()
{
$builder = $this->getContainerBuilder();
$config = $this->getConfig($this->defaults);
$builder->addDefinition($this->prefix("themesLoader"))
->setClass(ThemesLoader::classname)
->addTag(EventsExtension::SUBSCRIBER_TAG)
->addSetup("setFrontendTheme", array("name" => $config["frontend"]))
->addSetup("setBackendTheme", array("name" => $config["backend"]));
}
}
| <?php
/**
* Created by PhpStorm.
* User: Michal
* Date: 8.1.14
* Time: 19:02
*/
namespace AnnotateCms\Themes\DI;
use AnnotateCms\Themes\Loaders\ThemesLoader;
use Kdyby\Events\DI\EventsExtension;
use Nette\DI\CompilerExtension;
class ThemesExtension extends CompilerExtension
{
private $defaults = array(
"frontend" => "Sandbox",
);
public function loadConfiguration()
{
$builder = $this->getContainerBuilder();
$config = $this->getConfig($this->defaults);
$builder->addDefinition($this->prefix("themesLoader"))
->setClass(ThemesLoader::classname)
->addTag(EventsExtension::SUBSCRIBER_TAG)
->addSetup("setFrontendTheme", array("name" => $config["frontend"]))
->addSetup("setBackendTheme", array("name" => $config["backend"]));
}
} |
Use PointerEvent to be check for loading PointerEvents polyfill | /*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
/**
* @module PointerGestures
*/
(function() {
var thisFile = 'pointergestures.js';
var scopeName = 'PointerGestures';
var modules = [
'src/PointerGestureEvent.js',
'src/initialize.js',
'src/sidetable.js',
'src/pointermap.js',
'src/dispatcher.js',
'src/hold.js',
'src/track.js',
'src/flick.js',
'src/tap.js'
];
window[scopeName] = {
entryPointName: thisFile,
modules: modules
};
var script = document.querySelector('script[src $= "' + thisFile + '"]');
var src = script.attributes.src.value;
var basePath = src.slice(0, src.indexOf(thisFile));
if (!window.PointerEvent) {
document.write('<script src="' + basePath + '../PointerEvents/pointerevents.js"></script>');
}
if (!window.Loader) {
var path = basePath + 'tools/loader/loader.js';
document.write('<script src="' + path + '"></script>');
}
document.write('<script>Loader.load("' + scopeName + '")</script>');
})();
| /*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
/**
* @module PointerGestures
*/
(function() {
var thisFile = 'pointergestures.js';
var scopeName = 'PointerGestures';
var modules = [
'src/PointerGestureEvent.js',
'src/initialize.js',
'src/sidetable.js',
'src/pointermap.js',
'src/dispatcher.js',
'src/hold.js',
'src/track.js',
'src/flick.js',
'src/tap.js'
];
window[scopeName] = {
entryPointName: thisFile,
modules: modules
};
var script = document.querySelector('script[src $= "' + thisFile + '"]');
var src = script.attributes.src.value;
var basePath = src.slice(0, src.indexOf(thisFile));
if (!window.PointerEventPolyfill) {
document.write('<script src="' + basePath + '../PointerEvents/pointerevents.js"></script>');
}
if (!window.Loader) {
var path = basePath + 'tools/loader/loader.js';
document.write('<script src="' + path + '"></script>');
}
document.write('<script>Loader.load("' + scopeName + '")</script>');
})();
|
Return the whole user in successful login | from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from .models import User
from .errors import APIException
from .schemas import UserSchema
api = Blueprint('api', __name__)
@api.route('/whoami')
@jwt_required
def protected():
return jsonify(token=get_jwt_identity())
@api.route('/sign_up', methods=['POST'])
def sign_up():
schema = UserSchema().loads(request.data)
if schema.errors:
raise APIException('Fields <username, email, password> are required')
user = schema.data
if not user.exists():
user.save()
return jsonify(UserSchema().dump(user).data)
else:
raise APIException('A user with the email {} already exists. Forgot your password?'.format(user.email))
@api.route('/sign_in', methods=['POST'])
def sign_in():
conditions = [request.json.get('username', None), request.json.get('password', None)]
if not all(conditions):
raise APIException('Fields <username, password> are required.')
user = User.validate_login(conditions[0], conditions[1])
if user:
return jsonify(UserSchema().dump(user).data)
else:
raise APIException('Invalid login credentials', status_code=401)
| from collections import namedtuple
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from .models import User
from .errors import APIException
from .schemas import UserSchema
api = Blueprint('api', __name__)
@api.route('/whoami')
@jwt_required
def protected():
return jsonify(token=get_jwt_identity())
@api.route('/sign_up', methods=['POST'])
def sign_up():
schema = UserSchema().loads(request.data)
if schema.errors:
raise APIException('Fields <username, email, password> are required')
user = schema.data
if not user.exists():
user.save()
return jsonify(UserSchema().dump(user).data)
else:
raise APIException('A user with the email {} already exists. Forgot your password?'.format(user.email))
@api.route('/sign_in', methods=['POST'])
def sign_in():
conditions = [request.json.get('username', None), request.json.get('password', None)]
if not all(conditions):
raise APIException('Fields <username, password> are required.')
user = User.validate_login(conditions[0], conditions[1])
if user:
print(user.token)
return jsonify(token=user.token)
else:
raise APIException('Invalid login credentials', status_code=401)
|
Convert .js files with babel | module.exports = {
entry: ['./app/main.jsx'],
output: {
path: './build',
filename: 'bundle.js',
pathinfo: true
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
},
{
test: /\.scss$/,
exclude: /node_modules/,
loader: 'style!css!sass'
},
{
test: /\.svg$/,
loader: 'file-loader'
}
]
},
devtool: 'source-map',
devServer: {
contentBase: './build',
hot: true,
progress: true,
colors: true,
}
};
| module.exports = {
entry: ['./app/main.jsx'],
output: {
path: './build',
filename: 'bundle.js',
pathinfo: true
},
module: {
loaders: [
{
test: /\.jsx$/,
exclude: /node_modules/,
loader: 'babel'
},
{
test: /\.scss$/,
exclude: /node_modules/,
loader: 'style!css!sass'
},
{
test: /\.svg$/,
loader: 'file-loader'
}
]
},
devtool: 'source-map',
devServer: {
contentBase: './build',
hot: true,
progress: true,
colors: true,
}
};
|
Clean up category index page. | import React from 'react/addons';
import Gallery from './Gallery';
class CategoryIndex extends React.Component {
constructor(props) {
super(props);
// Assign incremental key to candidates
let i = 1;
const candidates = props.candidates.map(function(candidate) {
candidate.key = i++;
return candidate;
});
this.state = {
selectedItem: null,
candidates: candidates
};
this.selectItem = this.selectItem.bind(this);
}
/**
* Set or unset the selected item to show details for.
* @param item
*/
selectItem(item) {
// De-select if trying to select the same item again.
if(this.state.selectedItem === item.props.candidate) {
this.setState({selectedItem: null});
return;
}
this.setState({selectedItem: item.props.candidate});
}
/**
* Render component.
* @returns {XML}
*/
render() {
return (
<Gallery name={this.props.name} items={this.props.candidates} selectItem={this.selectItem} selectedItem={this.state.selectedItem} />
);
}
}
export default CategoryIndex;
| import React from 'react/addons';
import Gallery from './Gallery';
class CategoryIndex extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedItem: null
};
this.selectItem = this.selectItem.bind(this);
}
/**
* Set or unset the selected item to show details for.
* @param query
*/
selectItem(item) {
// De-select if trying to select the same item again.
if(this.state.selectedItem === item.props.candidate) {
this.setState({selectedItem: null});
return;
}
this.setState({selectedItem: item.props.candidate});
}
/**
* Render component.
* @returns {XML}
*/
render() {
return (
<div className='category'>
<h2 className='gallery-heading'>{this.props.name}</h2>
<Gallery items={this.props.candidates} selectItem={this.selectItem} selectedItem={this.state.selectedItem} />
</div>
);
}
}
export default CategoryIndex;
|
Add wrapper element to licenses acct page | <?php do_action( 'it_exchange_content_licenses_before_wrap' ); ?>
<div id="it-exchange-licenses" class="it-exchange-wrap it-exchange-account">
<?php do_action( 'it_exchange_content_licenses_begin_wrap' ); ?>
<?php it_exchange_get_template_part( 'messages' ); ?>
<?php it_exchange( 'customer', 'menu' ); ?>
<div class="it-exchange-licensing-container">
<?php if ( it_exchange( 'licenses', 'has-licenses' ) ) : ?>
<div class="it-exchange-licenses-list">
<div class="it-exchange-licenses-list-header">
<?php it_exchange_get_template_part( 'content-licenses/elements/licenses-list-header' ); ?>
</div>
<div class="it-exchange-licenses-list-body">
<?php it_exchange_get_template_part( 'content-licenses/loops/licenses' ); ?>
</div>
</div>
<?php else : ?>
<?php it_exchange_get_template_part( 'content-licenses/elements/no-licenses-found' ); ?>
<?php endif; ?>
</div>
<?php do_action( 'it_exchange_content_licenses_end_wrap' ); ?>
</div>
<?php do_action( 'it_exchange_content_licenses_after_wrap' ); ?> | <?php do_action( 'it_exchange_content_licenses_before_wrap' ); ?>
<div id="it-exchange-licenses" class="it-exchange-wrap it-exchange-account">
<?php do_action( 'it_exchange_content_licenses_begin_wrap' ); ?>
<?php it_exchange_get_template_part( 'messages' ); ?>
<?php it_exchange( 'customer', 'menu' ); ?>
<?php if ( it_exchange( 'licenses', 'has-licenses' ) ) : ?>
<div class="it-exchange-licenses-list">
<div class="it-exchange-licenses-list-header">
<?php it_exchange_get_template_part( 'content-licenses/elements/licenses-list-header' ); ?>
</div>
<div class="it-exchange-licenses-list-body">
<?php it_exchange_get_template_part( 'content-licenses/loops/licenses' ); ?>
</div>
</div>
<?php else : ?>
<?php it_exchange_get_template_part( 'content-licenses/elements/no-licenses-found' ); ?>
<?php endif; ?>
<?php do_action( 'it_exchange_content_licenses_end_wrap' ); ?>
</div>
<?php do_action( 'it_exchange_content_licenses_after_wrap' ); ?> |
Create parent directories before writing a file | #!/usr/bin/env node
const fs = require('fs')
const path = require('path')
const compile = require('../src/index')
const command = {
name: process.argv[2],
input: process.argv[3],
output: process.argv[4]
}
const build = (input, output) => {
compile(fs.readFileSync(input, 'utf8')).then(css => {
// Create all the parent directories if required
fs.mkdirSync(path.dirname(output), { recursive: true })
// Write the CSS
fs.writeFile(output, css, err => {
if (err) throw err
console.log(`File written: ${output}\nFrom: ${input}`);
})
});
};
const watch = path => {
console.log(`Currently watching for changes in: ${path}`);
fs.watch(path, {recursive: true}, (eventType, filename) => {
console.log(`${eventType.charAt(0).toUpperCase() + eventType.slice(1)} in: ${filename}`);
build();
});
};
switch (command.name) {
case 'compile':
build(command.input, command.output);
break
case 'watch':
build(command.input, command.output);
watch(path.dirname(command.input));
break
default:
console.log('Unknown command')
break
}
| #!/usr/bin/env node
// TODO: Create parent directories if they don't exist when compiling
const fs = require('fs')
const path = require('path')
const compile = require('../src/index')
const command = {
name: process.argv[2],
input: process.argv[3],
output: process.argv[4]
}
const build = (input, output) => {
compile(fs.readFileSync(input, 'utf8')).then(css => {
fs.writeFile(output, css, err => {
if (err) throw err
console.log(`File written: ${output}\nFrom: ${input}`);
})
});
};
const watch = path => {
console.log(`Currently watching for changes in: ${path}`);
fs.watch(path, {recursive: true}, (eventType, filename) => {
console.log(`${eventType.charAt(0).toUpperCase() + eventType.slice(1)} in: ${filename}`);
build();
});
};
switch (command.name) {
case 'compile':
build(command.input, command.output);
break
case 'watch':
build(command.input, command.output);
watch(path.dirname(command.input));
break
default:
console.log('Unknown command')
break
}
|
Remove reference to deprecated 'EXT' constant. | <?php if ( ! defined('BASEPATH')) exit('Invalid file request.');
/**
* OmniLog module tests.
*
* @author Stephen Lewis <stephen@experienceinternet.co.uk>
* @copyright Experience Internet
* @package Omnilog
*/
require_once PATH_THIRD .'omnilog/mcp.omnilog.php';
require_once PATH_THIRD .'omnilog/tests/mocks/mock.omnilog_model.php';
class Test_omnilog extends Testee_unit_test_case {
private $_model;
private $_subject;
/* --------------------------------------------------------------
* PUBLIC METHODS
* ------------------------------------------------------------ */
/**
* Constructor.
*
* @access public
* @return void
*/
public function setUp()
{
parent::setUp();
Mock::generate('Mock_omnilog_model', get_class($this) .'_mock_model');
$this->_ee->omnilog_model = $this->_get_mock('model');
$this->_model = $this->_ee->omnilog_model;
$this->_subject = new Omnilog();
}
}
/* End of file : test.mod_omnilog.php */
/* File location : third_party/omnilog/tests/test.mod_omnilog.php */
| <?php if ( ! defined('EXT')) exit('Invalid file request.');
/**
* OmniLog module tests.
*
* @author Stephen Lewis <stephen@experienceinternet.co.uk>
* @copyright Experience Internet
* @package Omnilog
*/
require_once PATH_THIRD .'omnilog/mcp.omnilog' .EXT;
require_once PATH_THIRD .'omnilog/tests/mocks/mock.omnilog_model' .EXT;
class Test_omnilog extends Testee_unit_test_case {
private $_model;
private $_subject;
/* --------------------------------------------------------------
* PUBLIC METHODS
* ------------------------------------------------------------ */
/**
* Constructor.
*
* @access public
* @return void
*/
public function setUp()
{
parent::setUp();
Mock::generate('Mock_omnilog_model', get_class($this) .'_mock_model');
$this->_ee->omnilog_model = $this->_get_mock('model');
$this->_model = $this->_ee->omnilog_model;
$this->_subject = new Omnilog();
}
}
/* End of file : test.mod_omnilog.php */
/* File location : third_party/omnilog/tests/test.mod_omnilog.php */
|
Update back to dev tag | # Copyright 2022 The KerasCV Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from keras_cv import layers
from keras_cv import metrics
from keras_cv import utils
from keras_cv import version_check
from keras_cv.core import ConstantFactorSampler
from keras_cv.core import FactorSampler
from keras_cv.core import NormalFactorSampler
from keras_cv.core import UniformFactorSampler
version_check.check_tf_version()
__version__ = "0.2.0dev"
| # Copyright 2022 The KerasCV Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from keras_cv import layers
from keras_cv import metrics
from keras_cv import utils
from keras_cv import version_check
from keras_cv.core import ConstantFactorSampler
from keras_cv.core import FactorSampler
from keras_cv.core import NormalFactorSampler
from keras_cv.core import UniformFactorSampler
version_check.check_tf_version()
__version__ = "0.2.0"
|
Include Python 3.4 and 3.5 | from distutils.core import setup
from jsonref import __version__
with open("README.rst") as readme:
long_description = readme.read()
classifiers = [
"Development Status :: 1 - Planning",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.1",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
]
setup(
name="jsonref",
version=__version__,
py_modules=["jsonref", "proxytypes"],
author="Chase Sterling",
author_email="chase.sterling@gmail.com",
classifiers=classifiers,
description="An implementation of JSON Reference for Python",
license="MIT",
long_description=long_description,
url="http://github.com/gazpachoking/jsonref",
)
| from distutils.core import setup
from jsonref import __version__
with open("README.rst") as readme:
long_description = readme.read()
classifiers = [
"Development Status :: 1 - Planning",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.1",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
]
setup(
name="jsonref",
version=__version__,
py_modules=["jsonref", "proxytypes"],
author="Chase Sterling",
author_email="chase.sterling@gmail.com",
classifiers=classifiers,
description="An implementation of JSON Reference for Python",
license="MIT",
long_description=long_description,
url="http://github.com/gazpachoking/jsonref",
)
|
BUGFIX: Disable the require prop-types rule since we create them automatically via flow annotations | module.exports = {
parser: 'babel-eslint',
extends: [
'standard',
'standard-react',
'plugin:flowtype/recommended',
'plugin:jsx-a11y/recommended',
'plugin:promise/recommended',
'plugin:react/recommended',
'prettier',
'prettier/flowtype',
'prettier/react'
],
plugins: ['compat', 'flowtype', 'promise', 'babel', 'react', 'jsx-a11y'],
env: {
node: true,
browser: true,
jest: true
},
globals: {
analytics: true,
Generator: true,
Iterator: true
},
settings: {
polyfills: ['fetch']
},
rules: {
'import/first': 0,
'compat/compat': 2,
'react/jsx-boolean-value': 0,
'react/prop-types': 0,
'react/require-default-props': 0,
'react/forbid-component-props': 0,
'promise/avoid-new': 0
}
};
| module.exports = {
parser: 'babel-eslint',
extends: [
'standard',
'standard-react',
'plugin:flowtype/recommended',
'plugin:jsx-a11y/recommended',
'plugin:promise/recommended',
'plugin:react/recommended',
'prettier',
'prettier/flowtype',
'prettier/react'
],
plugins: ['compat', 'flowtype', 'promise', 'babel', 'react', 'jsx-a11y'],
env: {
node: true,
browser: true,
jest: true
},
globals: {
analytics: true,
Generator: true,
Iterator: true
},
settings: {
polyfills: ['fetch']
},
rules: {
'import/first': 0,
'compat/compat': 2,
'react/jsx-boolean-value': 0,
'react/require-default-props': 0,
'react/forbid-component-props': 0,
'promise/avoid-new': 0
}
};
|
Remove sourcemaps setting.
It gets applied automatically. | const webpack = require('@cypress/webpack-preprocessor')
module.exports = (on) => {
on('file:preprocessor', webpack({
webpackOptions: {
resolve: {
extensions: ['.ts', '.js']
},
node: { fs: 'empty', child_process: 'empty', readline: 'empty' },
module: {
rules: [
{ test: /\.ts$/, exclude: [/node_modules/], use: [{ loader: 'ts-loader' }] },
{ test: /\.feature$/, use: [{ loader: 'cypress-cucumber-preprocessor/loader' }] },
{ test: /\.features$/, use: [{ loader: 'cypress-cucumber-preprocessor/lib/featuresLoader' }] }
]
}
}
}))
}
| const webpack = require('@cypress/webpack-preprocessor')
module.exports = (on) => {
on('file:preprocessor', webpack({
webpackOptions: {
resolve: {
extensions: ['.ts', '.js']
},
node: { fs: 'empty', child_process: 'empty', readline: 'empty' },
module: {
rules: [
{ test: /\.ts$/, exclude: [/node_modules/], use: [{ loader: 'ts-loader' }] },
{ test: /\.feature$/, use: [{ loader: 'cypress-cucumber-preprocessor/loader' }] },
{ test: /\.features$/, use: [{ loader: 'cypress-cucumber-preprocessor/lib/featuresLoader' }] }
]
},
devtool: 'source-map'
}
}))
}
|
Fix some bugs in handling of settings | (function(Pebble, window) {
var settings = {};
Pebble.addEventListener("ready", function(e) {
settings = window.localStorage.getItem("settings");
if(settings !== "") {
var options = JSON.parse(settings);
Pebble.sendAppMessage(options);
}
});
Pebble.addEventListener("showConfiguration", function() {
settings = window.localStorage.getItem("settings");
if(!settings) {
settings = "{}";
}
Pebble.openURL("http://rexmac.com/projects/pebble/chronocode/settings.html#" + encodeURIComponent(JSON.stringify(settings)));
});
Pebble.addEventListener("webviewclosed", function(e) {
var rt = typeof e.response,
options = (rt === "undefined" ? {} : JSON.parse(decodeURIComponent(e.response)));
if(Object.keys(options).length > 0) {
window.localStorage.setItem("settings", JSON.stringify(options));
Pebble.sendAppMessage(options);
}
})
})(Pebble, window);
| (function(Pebble, window) {
var settings = {};
Pebble.addEventListener("ready", function(e) {
settings = window.localStorage.getItem("settings");
if(settings !== "") {
var options = JSON.parse(settings);
Pebble.sendAppMessage(options);
}
});
Pebble.addEventListener("showConfiguration", function() {
settings = window.localStorage.getItem("settings");
if(!settings) {
settings = {};
}
Pebble.openURL("http://rexmac.com/projects/pebble/chronocode/settings.html#" + encodeURIComponent(JSON.stringify(settings)));
});
Pebble.addEventListener("webviewclosed", function(e) {
var options = JSON.parse(decodeURIComponent(e.response));
if(Object.keys(options).length > 0) {
window.localStorage.setItem("settings", JSON.stringify(options));
Pebble.sendAppMessage(options);
}
})
})(Pebble, window);
|
Add description to custom-scalar types | <?php
namespace Overblog\GraphQLBundle\Config;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
class CustomScalarTypeDefinition extends TypeDefinition
{
public function getDefinition()
{
$builder = new TreeBuilder();
$node = $builder->root('_custom_scalar_config');
$node
->children()
->append($this->nameSection())
->append($this->descriptionSection())
->variableNode('serialize')->isRequired()->end()
->variableNode('parseValue')->isRequired()->end()
->variableNode('parseLiteral')->isRequired()->end()
->end();
return $node;
}
}
| <?php
namespace Overblog\GraphQLBundle\Config;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
class CustomScalarTypeDefinition extends TypeDefinition
{
public function getDefinition()
{
$builder = new TreeBuilder();
$node = $builder->root('_custom_scalar_config');
$node
->children()
->append($this->nameSection())
->variableNode('serialize')->isRequired()->end()
->variableNode('parseValue')->isRequired()->end()
->variableNode('parseLiteral')->isRequired()->end()
->end();
return $node;
}
}
|
Refactor level navigation into event. | import { store } from './index';
export const tileUpClicked = clicked_tile => event => {
let current_level = store.getState().current_level();
let down_clicked_tile = current_level.board[current_level.currently_selected];
if (event.button === 0 && (clicked_tile.will_change || down_clicked_tile === clicked_tile)) {
store.dispatch({ type: 'ADVANCE_TILE_COLOR', tile: down_clicked_tile });
}
else if (event.button === 2 && (clicked_tile.will_change || down_clicked_tile === clicked_tile)) {
store.dispatch({ type: 'PREVIOUS_TILE_COLOR', tile: clicked_tile });
}
store.dispatch({ type: 'CLEAR_HIGHLIGHTS' });
}
export const tileDownClicked = clicked_tile => event => {
store.dispatch({ type: 'HIGHLIGHT_TILES', tile: clicked_tile });
}
export const newGameButtonClicked = event => {
let interval = setInterval(function() {
store.dispatch({ type: 'SHUFFLE_COLORS' })
}, 50);
setTimeout(function() { clearInterval(interval) }, 800);
}
export const navigateLevelButtonClicked = level_index => event => {
store.dispatch({ type: 'NAVIGATE_LEVEL', level: level_index });
let current_level = store.getState().current_level();
if (current_level.in_winning_state() && current_level.best_score === 'N/A') {
store.dispatch({ type: 'SHUFFLE_COLORS' });
}
} | import { store } from './index';
export const tileUpClicked = clicked_tile => event => {
let current_level = store.getState().current_level();
let down_clicked_tile = current_level.board[current_level.currently_selected];
if (event.button === 0 && (clicked_tile.will_change || down_clicked_tile === clicked_tile)) {
store.dispatch({ type: 'ADVANCE_TILE_COLOR', tile: down_clicked_tile });
}
else if (event.button === 2 && (clicked_tile.will_change || down_clicked_tile === clicked_tile)) {
store.dispatch({ type: 'PREVIOUS_TILE_COLOR', tile: clicked_tile });
}
store.dispatch({ type: 'CLEAR_HIGHLIGHTS' });
}
export const tileDownClicked = clicked_tile => event => {
store.dispatch({ type: 'HIGHLIGHT_TILES', tile: clicked_tile });
}
export const newGameButtonClicked = event => {
let interval = setInterval(function() {
store.dispatch({ type: 'SHUFFLE_COLORS' })
}, 50);
setTimeout(function() { clearInterval(interval) }, 800);
}
|
Make quill editor variable global
So visitors can easily try out the API | var quill; // Expose as global so people can easily try out the API
$(document).ready(function() {
quill = new Quill('#editor', {
modules: {
'toolbar': { container: '#toolbar' },
'image-tooltip': true,
'link-tooltip': true
},
theme: 'snow'
});
$('.quill-wrapper').tooltip({ trigger: 'manual' });
var tooltipTimer = setTimeout(function() {
$('.quill-wrapper').tooltip('show');
}, 2500);
quill.once('selection-change', function(hasFocus) {
$('#editor').toggleClass('focus', hasFocus);
// Hack for inability to scroll on mobile
if (/mobile/i.test(navigator.userAgent)) {
$('#editor').css('height', quill.root.scrollHeight + 30) // 30 for padding
}
$('.quill-wrapper').tooltip('destroy');
clearTimeout(tooltipTimer);
});
});
| $(document).ready(function() {
var editor = new Quill('#editor', {
modules: {
'toolbar': { container: '#toolbar' },
'image-tooltip': true,
'link-tooltip': true
},
theme: 'snow'
});
$('.quill-wrapper').tooltip({ trigger: 'manual' });
var tooltipTimer = setTimeout(function() {
$('.quill-wrapper').tooltip('show');
}, 2500);
editor.once('selection-change', function(hasFocus) {
$('#editor').toggleClass('focus', hasFocus);
// Hack for inability to scroll on mobile
if (/mobile/i.test(navigator.userAgent)) {
$('#editor').css('height', editor.root.scrollHeight + 30) // 30 for padding
}
$('.quill-wrapper').tooltip('destroy');
clearTimeout(tooltipTimer);
});
});
|
Fix Enum returning invalid elements | from __future__ import absolute_import, unicode_literals
# http://stackoverflow.com/a/22723724/1798491
class Enum(object):
def __init__(self, tuple_list):
self.tuple_list = tuple_list
def __getattr__(self, name):
if name not in self.tuple_list:
raise AttributeError("'Enum' has no attribute '{}'".format(name))
return name
# https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js
class BLOCK_TYPES:
UNSTYLED = 'unstyled'
HEADER_ONE = 'header-one'
HEADER_TWO = 'header-two'
HEADER_THREE = 'header-three'
HEADER_FOUR = 'header-four'
HEADER_FIVE = 'header-five'
HEADER_SIX = 'header-six'
UNORDERED_LIST_ITEM = 'unordered-list-item'
ORDERED_LIST_ITEM = 'ordered-list-item'
BLOCKQUOTE = 'blockquote'
PULLQUOTE = 'pullquote'
CODE = 'code-block'
ATOMIC = 'atomic'
HORIZONTAL_RULE = 'horizontal-rule'
ENTITY_TYPES = Enum(('LINK', 'IMAGE', 'TOKEN'))
INLINE_STYLES = Enum(('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE'))
| from __future__ import absolute_import, unicode_literals
# http://stackoverflow.com/a/22723724/1798491
class Enum(object):
def __init__(self, tuple_list):
self.tuple_list = tuple_list
def __getattr__(self, name):
return name
# https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js
class BLOCK_TYPES:
UNSTYLED = 'unstyled'
HEADER_ONE = 'header-one'
HEADER_TWO = 'header-two'
HEADER_THREE = 'header-three'
HEADER_FOUR = 'header-four'
HEADER_FIVE = 'header-five'
HEADER_SIX = 'header-six'
UNORDERED_LIST_ITEM = 'unordered-list-item'
ORDERED_LIST_ITEM = 'ordered-list-item'
BLOCKQUOTE = 'blockquote'
PULLQUOTE = 'pullquote'
CODE = 'code-block'
ATOMIC = 'atomic'
HORIZONTAL_RULE = 'horizontal-rule'
ENTITY_TYPES = Enum(('LINK', 'IMAGE', 'TOKEN'))
INLINE_STYLES = Enum(('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE'))
|
Fix invalid end point projects/p/tiny-project/iterations/i/1/r/hello | var config = require('./js/configure-server')
server = config.server,
getJSON = require('./js/get-json')(__dirname + '/mocks');
var endpoints = [
'/projects',
'/projects/p/tiny-project',
'/projects/p/tiny-project/iterations/i/1',
'/projects/p/tiny-project/iterations/i/1/r',
'/projects/p/tiny-project/iterations/i/1/r/hello.txt',
'/projects/p/tiny-project/iterations/i/1/locales',
'/stats/proj/tiny-project/iter/1/doc/hello.txt'
]
endpoints.forEach(createPathWithMockFile);
server.listen(config.port);
console.log();
config.logDetails();
/**
* Create a GET endpoint using a JSON file as the body.
*
* The path of the JSON file in the mock directory must be the same as
* the path of the resource on the REST endpoint.
*/
function createPathWithMockFile(path) {
server.get(path)
.body(getJSON(path))
.delay(config.latency);
console.log('registered path %s', path);
}
| var config = require('./js/configure-server')
server = config.server,
getJSON = require('./js/get-json')(__dirname + '/mocks');
var endpoints = [
'/projects',
'/projects/p/tiny-project',
'/projects/p/tiny-project/iterations/i/1',
'/projects/p/tiny-project/iterations/i/1/r',
'/projects/p/tiny-project/iterations/i/1/r/hello',
'/projects/p/tiny-project/iterations/i/1/locales',
'/stats/proj/tiny-project/iter/1/doc/hello.txt'
]
endpoints.forEach(createPathWithMockFile);
server.listen(config.port);
console.log();
config.logDetails();
/**
* Create a GET endpoint using a JSON file as the body.
*
* The path of the JSON file in the mock directory must be the same as
* the path of the resource on the REST endpoint.
*/
function createPathWithMockFile(path) {
server.get(path)
.body(getJSON(path))
.delay(config.latency);
console.log('registered path %s', path);
}
|
Add type of variable budget | from django.db import models
class Budget(models.Model):
number = models.CharField(max_length=100, unique=True)
initial_date = models.DateTimeField()
final_date = models.DateTimeField(blank=True)
hub = models.ForeignKey('hubs.Hubs')
def __str__(self):
return self.number
class BudgetElement(models.Model):
FIXED = 'f'
VARIABLE = 'v'
TYPE_CHOICES = (
(FIXED, 'Fixed'),
(VARIABLE, 'Variable'),
)
budget_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=FIXED)
amount = models.DecimalField(decimal_places=2, max_digits=19, default=0)
number = models.ForeignKey(Budget)
currency = models.ForeignKey('accounts.Currency')
category = models.ForeignKey('transactions.Category')
subcategory = models.ForeignKey('transactions.Subcategory')
"""
If the element is variable
"""
FIRST_W = 'f'
OTHER_W = 'o'
V_TYPE_CHOICES = (
(FIRST_W, 'First Week'),
(OTHER_W, 'Other Week'),
)
variable_type = models.CharField(max_length=5, choices=V_TYPE_CHOICES, default=OTHER_W)
def __str__(self):
return self.amount + self.number.number
| from django.db import models
class Budget(models.Model):
number = models.CharField(max_length=100, unique=True)
initial_date = models.DateTimeField()
final_date = models.DateTimeField(blank=True)
hub = models.ForeignKey('hubs.Hubs')
def __str__(self):
return self.number
class BudgetElement(models.Model):
FIXED = 'f'
VARIABLE = 'v'
TYPE_CHOICES = (
(FIXED, 'Fixed'),
(VARIABLE, 'Variable'),
)
budget_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=FIXED)
amount = models.DecimalField(decimal_places=2, max_digits=19, default=0)
number = models.ForeignKey(Budget)
currency = models.ForeignKey('accounts.Currency')
category = models.ForeignKey('transactions.Category')
subcategory = models.ForeignKey('transactions.Subcategory')
def __str__(self):
return self.amount + self.number.number
|
:paperclip: Add positioning for the canvas. | /*
* This file is part of the three playground.
*
* (c) Magnus Bergman <hello@magnus.sexy>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import THREE from 'three';
export default class WebGLRenderer extends THREE.WebGLRenderer {
/**
* Create WebGLRenderer.
*
* @return {void}
*/
constructor(options) {
const { innerWidth: width, innerHeight: height, devicePixelRatio: pixelRatio } = window;
const opts = {
container: document.body,
alpha: true,
antialias: true,
...options,
};
super({ alpha: opts.alpha, antialias: opts.antialias });
this.setSize(width, height);
this.setPixelRatio(pixelRatio);
this.shadowMap.enabled = true;
this.shadowMapSoft = true;
this.domElement.style.position = 'fixed';
this.domElement.style.top = 0;
this.domElement.style.left = 0;
opts.container.appendChild(this.domElement);
}
}
| /*
* This file is part of the three playground.
*
* (c) Magnus Bergman <hello@magnus.sexy>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import THREE from 'three';
export default class WebGLRenderer extends THREE.WebGLRenderer {
/**
* Create WebGLRenderer.
*
* @return {void}
*/
constructor(options) {
const { innerWidth: width, innerHeight: height, devicePixelRatio: pixelRatio } = window;
const opts = {
container: document.body,
alpha: true,
antialias: true,
...options,
};
super({ alpha: opts.alpha, antialias: opts.antialias });
this.setSize(width, height);
this.setPixelRatio(pixelRatio);
this.shadowMap.enabled = true;
this.shadowMapSoft = true;
opts.container.appendChild(this.domElement);
}
}
|
Use config method from plugin class | <?php
/**
* This file is part of Herbie.
*
* (c) Thomas Breuss <www.tebe.ch>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace herbie\plugin\feed;
use Herbie;
use Herbie\Loader\FrontMatterLoader;
use Herbie\Menu\Page\Item;
class FeedPlugin extends Herbie\Plugin
{
/**
* @var Herbie\Menu\Page
*/
private $menu;
/**
* @param Herbie\Event $event
*/
public function onPluginsInitialized(Herbie\Event $event)
{
if($this->config->isEmpty('plugins.config.feed.no_page')) {
$this->config->push('pages.extra_paths', '@plugin/feed/pages');
}
}
}
| <?php
/**
* This file is part of Herbie.
*
* (c) Thomas Breuss <www.tebe.ch>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace herbie\plugin\feed;
use Herbie;
use Herbie\Loader\FrontMatterLoader;
use Herbie\Menu\Page\Item;
class FeedPlugin extends Herbie\Plugin
{
/**
* @var Herbie\Menu\Page
*/
private $menu;
/**
* @param Herbie\Event $event
*/
public function onPluginsInitialized(Herbie\Event $event)
{
if($this->app['config']->isEmpty('plugins.config.feed.no_page')) {
$this->app['config']->push('pages.extra_paths', '@plugin/feed/pages');
}
}
}
|
Remove stray console.logs that were totally there on purpose | exercism.views.ListNotifications = Backbone.View.extend({
template: JST["app/templates/list_notifications.us"],
id: "list-notifications",
initialize: function(options) {
this.listenTo(this.collection, 'add', this.addOne);
},
render: function() {
this.$el.html(this.template());
return this;
},
toggle: function() {
this.$el.toggleClass("reveal-notifications");
$("body").toggleClass("reveal-notifications");
},
addAll: function() {
this.collection.each(this.addOne, this);
},
addOne: function(model) {
view = new exercism.views.Notification({model: model});
view.render();
this.$("#contains-notifications").append(view.el);
model.on('remove', view.remove, view);
}
});
| exercism.views.ListNotifications = Backbone.View.extend({
template: JST["app/templates/list_notifications.us"],
id: "list-notifications",
initialize: function(options) {
this.listenTo(this.collection, 'add', this.addOne);
},
render: function() {
this.$el.html(this.template());
return this;
},
toggle: function() {
console.log("toggle");
this.$el.toggleClass("reveal-notifications");
$("body").toggleClass("reveal-notifications");
},
addAll: function() {
this.collection.each(this.addOne, this);
},
addOne: function(model) {
console.log(model);
view = new exercism.views.Notification({model: model});
view.render();
this.$("#contains-notifications").append(view.el);
model.on('remove', view.remove, view);
}
});
|
Add theme support for Responsive Videos. | <?php
/**
* Jetpack Compatibility File.
*
* @link https://jetpack.me/
*
* @package _s
*/
function _s_jetpack_setup() {
/**
* Add theme support for Infinite Scroll.
* See: https://jetpack.me/support/infinite-scroll/
*/
add_theme_support( 'infinite-scroll', array(
'container' => 'main',
'render' => '_s_infinite_scroll_render',
'footer' => 'page',
) );
/**
* Add theme support for Responsive Videos.
* See: https://jetpack.me/support/responsive-videos/
*/
add_theme_support( 'jetpack-responsive-videos' );
} // end function _s_jetpack_setup
add_action( 'after_setup_theme', '_s_jetpack_setup' );
/**
* Custom render function for Infinite Scroll.
*/
function _s_infinite_scroll_render() {
while ( have_posts() ) {
the_post();
get_template_part( 'template-parts/content', get_post_format() );
}
} // end function _s_infinite_scroll_render
| <?php
/**
* Jetpack Compatibility File.
*
* @link https://jetpack.me/
*
* @package _s
*/
/**
* Add theme support for Infinite Scroll.
* See: https://jetpack.me/support/infinite-scroll/
*/
function _s_jetpack_setup() {
add_theme_support( 'infinite-scroll', array(
'container' => 'main',
'render' => '_s_infinite_scroll_render',
'footer' => 'page',
) );
} // end function _s_jetpack_setup
add_action( 'after_setup_theme', '_s_jetpack_setup' );
/**
* Custom render function for Infinite Scroll.
*/
function _s_infinite_scroll_render() {
while ( have_posts() ) {
the_post();
get_template_part( 'template-parts/content', get_post_format() );
}
} // end function _s_infinite_scroll_render
|
Change checkbox values using prop()
* With `.prop()` we can pass in true or false, rather than a “checked”
string | $(document).ready(function() {
$.each(["business_size", "business_type", "location", "purpose", "sector", "stage", "support_type"], function(idx, facet) {
$("#business_support_" + facet + "_check_all").click(function(e) {
var $el = $(e.target);
$.each($el.parent().parent().find(":checkbox"), function(sidx, chkbx) {
$(chkbx).prop("checked", $el.is(":checked"));
});
});
});
/*
* Checks all child regions when a country is checked.
*/
var allLabels = $('#location').find('label');
var countries = allLabels.filter(function () {
return $(this).text().trim().match(/^England|Northern Ireland|Scotland|Wales$/);
});
countries.each (function (index, country) {
$(country).children(":checkbox").on("click", function () {
var countryLabel = $(country).text().trim();
var countryMatch = (countryLabel == "England" ? /England|London|Yorkshire/ : countryLabel);
var matches = allLabels.filter(function() {
var matchText = $(this).text().trim();
return matchText.match(countryMatch) && matchText != countryLabel;
});
var value = $(this).is(":checked");
matches.each (function (index, match) {
var checkbox = $(match).children(":checkbox");
checkbox.prop("checked", value);
});
});
});
});
| $(document).ready(function() {
$.each(["business_size", "business_type", "location", "purpose", "sector", "stage", "support_type"], function(idx, facet) {
$("#business_support_" + facet + "_check_all").click(function(e) {
var $el = $(e.target);
$.each($el.parent().parent().find(":checkbox"), function(sidx, chkbx) {
$(chkbx).attr("checked", $el.is(":checked"));
});
});
});
/*
* Checks all child regions when a country is checked.
*/
var allLabels = $('#location').find('label');
var countries = allLabels.filter(function () {
return $(this).text().trim().match(/^England|Northern Ireland|Scotland|Wales$/);
});
countries.each (function (index, country) {
$(country).children(":checkbox").on("click", function () {
var countryLabel = $(country).text().trim();
var countryMatch = (countryLabel == "England" ? /England|London|Yorkshire/ : countryLabel);
var matches = allLabels.filter(function() {
var matchText = $(this).text().trim();
return matchText.match(countryMatch) && matchText != countryLabel;
});
var value = $(this).prop("checked");
matches.each (function (index, match) {
var checkbox = $(match).children(":checkbox");
checkbox.attr("checked", value);
});
});
});
});
|
Remove edited API for sending binary
(should pass message object instead) | <?php
namespace Ratchet\WebSocket;
use Ratchet\AbstractConnectionDecorator;
use Ratchet\RFC6455\Messaging\DataInterface;
use Ratchet\RFC6455\Messaging\Frame;
/**
* {@inheritdoc}
* @property \StdClass $WebSocket
*/
class WsConnection extends AbstractConnectionDecorator {
/**
* {@inheritdoc}
*/
public function send($msg) {
if (!$this->WebSocket->closing) {
if (!($msg instanceof DataInterface)) {
$msg = new Frame($msg);
}
$this->getConnection()->send($msg->getContents());
}
return $this;
}
/**
* @param int|\Ratchet\RFC6455\Messaging\DataInterface
*/
public function close($code = 1000) {
if ($this->WebSocket->closing) {
return;
}
if ($code instanceof DataInterface) {
$this->send($code);
} else {
$this->send(new Frame(pack('n', $code), true, Frame::OP_CLOSE));
}
$this->getConnection()->close();
$this->WebSocket->closing = true;
}
}
| <?php
namespace Ratchet\WebSocket;
use Ratchet\AbstractConnectionDecorator;
use Ratchet\RFC6455\Messaging\DataInterface;
use Ratchet\RFC6455\Messaging\Frame;
/**
* {@inheritdoc}
* @property \StdClass $WebSocket
*/
class WsConnection extends AbstractConnectionDecorator {
/**
* {@inheritdoc}
*/
public function send($msg, $isBinary = false) {
if (!$this->WebSocket->closing) {
if (!($msg instanceof DataInterface)) {
$msg = new Frame($msg, true, ((boolean)$isBinary ? Frame::OP_BINARY : Frame::OP_TEXT));
}
$this->getConnection()->send($msg->getContents());
}
return $this;
}
/**
* @param int|\Ratchet\RFC6455\Messaging\DataInterface
*/
public function close($code = 1000) {
if ($this->WebSocket->closing) {
return;
}
if ($code instanceof DataInterface) {
$this->send($code);
} else {
$this->send(new Frame(pack('n', $code), true, Frame::OP_CLOSE));
}
$this->getConnection()->close();
$this->WebSocket->closing = true;
}
}
|
Change id for variants image testing | import { test } from 'qunit';
import moduleForAcceptance from 'leibniz-frontend/tests/helpers/module-for-acceptance';
moduleForAcceptance('Acceptance | toggle variants test');
// TODO: Make this test more elaborate
test('toggle variants', function(assert) {
assert.expect(3);
// Make sure this letter actually has variants with formulas and images
visit('/letter/l37134');
var variantsCount = 0
var highlightsCount = 0
andThen(function() {
variantsCount = find('.variants .variant:visible').length;
});
// Highlight all variants
click('.variants .variant');
andThen(function () {
highlightsCount = find('.transcript .reference.-highlight').length;
});
click('.variants .variants_button');
andThen(function() {
var visibleVariantsCount = find('.variants .variant:visible').length;
var lessHighlightsCount = find('.transcript .reference.-highlight').length;
assert.ok(visibleVariantsCount < variantsCount, 'less variants should be visible');
assert.ok(lessHighlightsCount < highlightsCount, 'less references should be highlighted')
});
// Restore all variants, check images
// NOTE: MathJax is disabled in test environment for performance reasons, so MathJax-rendered
// content cannot checked. Yet, if SVG is present, so should MathJax.
click('.variants .variants_button');
andThen(function() {
var imagesCount = find('.variants .reference.-image svg').length;
assert.ok(imagesCount > 0, 'SVG images should still be present');
});
});
| import { test } from 'qunit';
import moduleForAcceptance from 'leibniz-frontend/tests/helpers/module-for-acceptance';
moduleForAcceptance('Acceptance | toggle variants test');
// TODO: Make this test more elaborate
test('toggle variants', function(assert) {
assert.expect(3);
// Make sure this letter actually has variants with formulas and images
visit('/letter/l36137');
var variantsCount = 0
var highlightsCount = 0
andThen(function() {
variantsCount = find('.variants .variant:visible').length;
});
// Highlight all variants
click('.variants .variant');
andThen(function () {
highlightsCount = find('.transcript .reference.-highlight').length;
});
click('.variants .variants_button');
andThen(function() {
var visibleVariantsCount = find('.variants .variant:visible').length;
var lessHighlightsCount = find('.transcript .reference.-highlight').length;
assert.ok(visibleVariantsCount < variantsCount, 'less variants should be visible');
assert.ok(lessHighlightsCount < highlightsCount, 'less references should be highlighted')
});
// Restore all variants, check images
// NOTE: MathJax is disabled in test environment for performance reasons, so MathJax-rendered
// content cannot checked. Yet, if SVG is present, so should MathJax.
click('.variants .variants_button');
andThen(function() {
var imagesCount = find('.variants .reference.-image svg').length;
assert.ok(imagesCount > 0, 'SVG images should still be present');
});
});
|
Change of repo name. Update effected paths | import json
import matplotlib
import numpy as np
import pymc as pm
from matplotlib import pyplot as plt
def main():
tau = pm.rdiscrete_uniform(0, 80)
print tau
alpha = 1. / 20.
lambda_1, lambda_2 = pm.rexponential(alpha, 2)
print lambda_1, lambda_2
data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)]
def plot_artificial_sms_dataset():
tau = pm.rdiscrete_uniform(0, 80)
alpha = 1. / 20.
lambda_1, lambda_2 = pm.rexponential(alpha, 2)
data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)]
plt.bar(np.arange(80), data, color="#348ABD")
plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed")
plt.xlim(0, 80)
plt.title("More example of artificial datasets")
for i in range(1, 5):
plt.subplot(4, 1, i)
plot_artificial_sms_dataset()
plt.show()
if __name__ == '__main__':
main()
| import json
import matplotlib
import numpy as np
import pymc as pm
from matplotlib import pyplot as plt
def main():
matplotlibrc_path = '/home/noel/repo/playground/matplotlibrc.json'
matplotlib.rcParams.update(json.load(open(matplotlibrc_path)))
tau = pm.rdiscrete_uniform(0, 80)
print tau
alpha = 1. / 20.
lambda_1, lambda_2 = pm.rexponential(alpha, 2)
print lambda_1, lambda_2
data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)]
def plot_artificial_sms_dataset():
tau = pm.rdiscrete_uniform(0, 80)
alpha = 1. / 20.
lambda_1, lambda_2 = pm.rexponential(alpha, 2)
data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)]
plt.bar(np.arange(80), data, color="#348ABD")
plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed")
plt.xlim(0, 80)
plt.title("More example of artificial datasets")
for i in range(1, 5):
plt.subplot(4, 1, i)
plot_artificial_sms_dataset()
plt.show()
if __name__ == '__main__':
main()
|
Disable indentpadding test, note why | package org.spoofax.jsglr2.integrationtest.languages;
import java.io.IOException;
import java.util.stream.Stream;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.jsglr2.integrationtest.BaseTestWithParseTableFromTermWithJSGLR1;
import org.spoofax.terms.ParseError;
public class StrategoTest extends BaseTestWithParseTableFromTermWithJSGLR1 {
public StrategoTest() throws Exception {
setupParseTable("Stratego");
}
@TestFactory public Stream<DynamicTest> testAmbByExpectedAST() throws ParseError, IOException {
String sampleProgram = getFileAsString("Stratego/ambiguity-issue.str");
IStrategoTerm expectedAST = getFileAsAST("Stratego/ambiguity-issue.aterm");
return testSuccessByAstString(sampleProgram, expectedAST.toString());
}
@Disabled("The {indentpadding} attribute is not supported by JSGLR2 imploding due to concerns around incremental parsing")
@TestFactory public Stream<DynamicTest> testIndentPadding() throws ParseError, IOException {
String sampleProgram = getFileAsString("Stratego/test112.str");
IStrategoTerm expectedAST = getFileAsAST("Stratego/test112.aterm");
return testSuccessByAstString(sampleProgram, expectedAST.toString());
}
} | package org.spoofax.jsglr2.integrationtest.languages;
import java.io.IOException;
import java.util.stream.Stream;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.jsglr2.integrationtest.BaseTestWithParseTableFromTermWithJSGLR1;
import org.spoofax.terms.ParseError;
public class StrategoTest extends BaseTestWithParseTableFromTermWithJSGLR1 {
public StrategoTest() throws Exception {
setupParseTable("Stratego");
}
@TestFactory public Stream<DynamicTest> testAmbByExpectedAST() throws ParseError, IOException {
String sampleProgram = getFileAsString("Stratego/ambiguity-issue.str");
IStrategoTerm expectedAST = getFileAsAST("Stratego/ambiguity-issue.aterm");
return testSuccessByAstString(sampleProgram, expectedAST.toString());
}
@TestFactory public Stream<DynamicTest> testIndentPadding() throws ParseError, IOException {
String sampleProgram = getFileAsString("Stratego/test112.str");
IStrategoTerm expectedAST = getFileAsAST("Stratego/test112.aterm");
return testSuccessByAstString(sampleProgram, expectedAST.toString());
}
} |
Add Flask-Restfull dependency to python package | # -*- coding: utf-8 -*-
from setuptools import setup
project = "gastosabertos"
setup(
name=project,
version='0.0.1',
url='https://github.com/okfn-brasil/gastos_abertos',
description='Visualization of public spending in Sao Paulo city for Gastos Abertos project',
author='Edgar Zanella Alvarenga',
author_email='e@vaz.io',
packages=["gastosabertos"],
include_package_data=True,
zip_safe=False,
install_requires=[
'Flask>=0.10.1',
'Flask-SQLAlchemy',
'Flask-WTF',
'Flask-Script',
'Flask-Babel',
'Flask-Testing',
'Flask-Restful',
'fabric',
'pandas'
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries'
]
)
| # -*- coding: utf-8 -*-
from setuptools import setup
project = "gastosabertos"
setup(
name=project,
version='0.0.1',
url='https://github.com/okfn-brasil/gastos_abertos',
description='Visualization of public spending in Sao Paulo city for Gastos Abertos project',
author='Edgar Zanella Alvarenga',
author_email='e@vaz.io',
packages=["gastosabertos"],
include_package_data=True,
zip_safe=False,
install_requires=[
'Flask>=0.10.1',
'Flask-SQLAlchemy',
'Flask-WTF',
'Flask-Script',
'Flask-Babel',
'Flask-Testing',
'fabric',
'pandas'
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries'
]
)
|
Add sender config file to fix bug | var express = require('express');
var bodyParser = require('body-parser');
var log4js = require('log4js');
var fs = require('fs');
var nconf = require('nconf');
nconf.file('bots', __dirname + '/config/bots.json')
.file('senders', __dirname + '/config/senders.json')
.file('receviers', __dirname + '/config/receivers.json')
.file('config', __dirname + '/config/config.json');
var access_log_path = nconf.get('access_log').path;
var app_log_path = nconf.get('app_log').path;
log4js.clearAppenders();
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file(access_log_path), 'ACCESS_LOG');
log4js.addAppender(log4js.appenders.file(app_log_path), 'APP_LOG');
var logger = log4js.getLogger('APP_LOG');
var app = new express();
var router = require('./route.js');
var server = require('./server.js');
app.set('views', __dirname + '/views');
app.use(bodyParser.json());
app.use(log4js.connectLogger(log4js.getLogger('ACCESS_LOG'),{level:'auto'}));
app.use(bodyParser.urlencoded({
extended: false
}));
app.use('/', router);
server.startServer(app);
module.exports = app;
| var express = require('express');
var bodyParser = require('body-parser');
var log4js = require('log4js');
var fs = require('fs');
var nconf = require('nconf');
nconf.file('bots', __dirname + '/config/bots.json')
.file('receviers', __dirname + '/config/receivers.json')
.file('testconfig', __dirname + '/config/config.json');
var access_log_path = nconf.get('access_log').path;
var app_log_path = nconf.get('app_log').path;
log4js.clearAppenders();
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file(access_log_path), 'ACCESS_LOG');
log4js.addAppender(log4js.appenders.file(app_log_path), 'APP_LOG');
var logger = log4js.getLogger('APP_LOG');
var app = new express();
var router = require('./route.js');
var server = require('./server.js');
app.set('views', __dirname + '/views');
app.use(bodyParser.json());
app.use(log4js.connectLogger(log4js.getLogger('ACCESS_LOG'),{level:'auto'}));
app.use(bodyParser.urlencoded({
extended: false
}));
app.use('/', router);
server.startServer(app);
module.exports = app;
|
Convert to autonomous script (from grunt task) | var lunr = require('lunr'),
fs = require('fs'),
views = require('./views'),
textNodes = require('./textNodeProcessor'),
config = require('../config'),
path = require('path');
var nodeMetaData;
views.loadAllViews(function(fileContentMap) {
textNodes.process(fileContentMap, function(nodes) {
var documents = nodes;
var index = lunr(function() {
this.field('body');
this.ref('id');
});
var id = 0;
var indexedDocs = [];
Object.keys(documents).forEach(function(pageName) {
var textNodes = documents[pageName];
textNodes.forEach(function(node) {
node.id = id;
indexedDocs.push(node);
++id;
});
});
indexedDocs.forEach(function(doc) {
index.add(doc);
});
fs.writeFileSync(path.join(config.dataDir, 'lunr-docs.json'), JSON.stringify(indexedDocs));
fs.writeFileSync(path.join(config.dataDir, 'lunr-index.json'), JSON.stringify(index.toJSON()));
console.log('Index successfully generated!');
});
});
| var lunr = require('lunr'),
fs = require('fs'),
views = require('./views'),
textNodes = require('./textNodeProcessor'),
config = require('../config'),
path = require('path');
module.exports.create = function(callback) {
var nodeMetaData;
views.loadAllViews(function(fileContentMap) {
textNodes.process(fileContentMap, function(nodes) {
var documents = nodes;
var index = lunr(function() {
this.field('body');
this.ref('id');
});
var id = 0;
var indexedDocs = [];
Object.keys(documents).forEach(function(pageName) {
var textNodes = documents[pageName];
textNodes.forEach(function(node) {
node.id = id;
indexedDocs.push(node);
++id;
});
});
indexedDocs.forEach(function(doc) {
index.add(doc);
});
fs.writeFileSync(path.join(config.dataDir, 'lunr-docs.json'), JSON.stringify(indexedDocs));
fs.writeFileSync(path.join(config.dataDir, 'lunr-index.json'), JSON.stringify(index.toJSON()));
callback('Index successfully generated!');
});
});
}; |
Move to html template string | var model = new falcor.Model({
cache: {
user: {
name: "Frank",
surname: "Underwood",
address: "1600 Pennsylvania Avenue, Washington, DC"
}
}
});
model
.getValue('user.surname')
.then(function(surname) {
console.log(surname);
});
renderTiles([{
title: 'falcor',
src: 'https://zemanifesto.files.wordpress.com/2014/07/bravecor1.jpg?w=590&h=442'
}]);
function renderTiles(tiles) {
const contentDiv = document.querySelector('#content');
contentDiv.innerHTML = '';
tiles
.map(tile => tileToHtml(tile))
.forEach(tileHtml => contentDiv.insertAdjacentHTML('afterend', tileHtml))
}
function tileToHtml(tile) {
return `<h2>${tile.title}</h2><img src="${tile.src} alt=${tile.title}"/>`;
}
| var model = new falcor.Model({
cache: {
user: {
name: "Frank",
surname: "Underwood",
address: "1600 Pennsylvania Avenue, Washington, DC"
}
}
});
model
.getValue('user.surname')
.then(function(surname) {
console.log(surname);
});
renderTiles([{
title: 'falcor',
src: 'https://zemanifesto.files.wordpress.com/2014/07/bravecor1.jpg?w=590&h=442'
}]);
function renderTiles(tiles) {
const contentDiv = document.querySelector('#content');
tiles
.map(tile => tileToDom(tile))
.forEach(domTile => contentDiv.appendChild(domTile))
}
function tileToDom(tile) {
const header = document.createElement('h2');
header.appendChild(document.createTextNode(tile.title));
const img = document.createElement('img');
img.src = tile.src;
img.alt = tile.title;
const tileDom = document.createElement('div');
tileDom.appendChild(header);
tileDom.appendChild(img);
return tileDom;
}
|
Replace dummy code for flight case with flight component | import React from 'react'
import Flight from './Flight'
export default function TravelObject(props) {
let content = null;
switch(props.type) {
case 'event':
content = <div>Event!</div>;
break;
case 'flight':
content = <Flight />
break;
case 'hotel':
content = <div>Hotel!</div>
break;
default:
console.log("Invalid type");
break;
}
return (
<div>
{content}
<button onClick={() => console.log("editing")}>Edit</button>
<button onClick={() => console.log("deleting")}>Delete</button>
</div>
)
} | import React from 'react'
export default function TravelObject(props) {
let content = null;
switch(props.type) {
case 'event':
content = <div>Event!</div>;
break;
case 'flight':
content = <div>Flight!</div>
break;
case 'hotel':
content = <div>Hotel!</div>
break;
default:
console.log("Invalid type");
break;
}
return (
<div>
{content}
<button onClick={() => console.log("editing")}>Edit</button>
<button onClick={() => console.log("deleting")}>Delete</button>
</div>
)
} |
Put proper path to project tests | const path = require('path')
module.exports = {
globals: {
'ts-jest': {
tsConfig: '<rootDir>/src/tsconfig.test.json'
}
},
setupFiles: ['<rootDir>/src/bp/jest-before.ts'],
globalSetup: '<rootDir>/src/bp/jest-rewire.ts',
setupFilesAfterEnv: [],
collectCoverage: false,
resetModules: true,
verbose: true,
modulePaths: ['<rootDir>/src/bp/'],
moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx'],
transform: {
'^.+\\.(ts|tsx|js)$': 'ts-jest'
},
resolver: '<rootDir>/src/bp/jest-resolver.js',
moduleNameMapper: {
'^botpress/sdk$': '<rootDir>/src/bp/core/sdk_impl'
},
testMatch: ['**/(src|test)/**/*.test.(ts|js)'],
testPathIgnorePatterns: ['out', 'build', 'node_modules'],
testEnvironment: 'node',
rootDir: '.',
preset: 'ts-jest',
testResultsProcessor: './node_modules/jest-html-reporter'
}
| const path = require('path')
module.exports = {
globals: {
'ts-jest': {
tsConfig: '<rootDir>/src/tsconfig.test.json'
}
},
setupFiles: ['<rootDir>/src/bp/jest-before.ts'],
globalSetup: '<rootDir>/src/bp/jest-rewire.ts',
setupFilesAfterEnv: [],
collectCoverage: false,
resetModules: true,
verbose: true,
modulePaths: ['<rootDir>/src/bp/'],
moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx'],
transform: {
'^.+\\.(ts|tsx|js)$': 'ts-jest'
},
resolver: '<rootDir>/src/bp/jest-resolver.js',
moduleNameMapper: {
'^botpress/sdk$': '<rootDir>/src/bp/core/sdk_impl'
},
testMatch: ['**/modules/nlu/(src|test)/**/*.test.(ts|js)'],
testPathIgnorePatterns: ['out', 'build', 'node_modules'],
testEnvironment: 'node',
rootDir: '.',
preset: 'ts-jest',
testResultsProcessor: './node_modules/jest-html-reporter'
}
|
[CS] Fix invalid inheritdoc tags in many places | <?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\Payment\Factory;
use Sylius\Component\Payment\Model\PaymentInterface;
use Sylius\Component\Resource\Factory\FactoryInterface;
/**
* @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
*/
final class PaymentFactory implements PaymentFactoryInterface
{
/**
* @var FactoryInterface
*/
private $factory;
/**
* @param FactoryInterface $factory
*/
public function __construct(FactoryInterface $factory)
{
$this->factory = $factory;
}
/**
* {@inheritdoc}
*/
public function createNew()
{
return $this->factory->createNew();
}
/**
* {@inheritdoc}
*/
public function createWithAmountAndCurrencyCode($amount, $currencyCode)
{
/** @var PaymentInterface $payment */
$payment = $this->factory->createNew();
$payment->setAmount($amount);
$payment->setCurrencyCode($currencyCode);
return $payment;
}
}
| <?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\Payment\Factory;
use Sylius\Component\Payment\Model\PaymentInterface;
use Sylius\Component\Resource\Factory\FactoryInterface;
/**
* @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
*/
final class PaymentFactory implements PaymentFactoryInterface
{
/**
* @var FactoryInterface
*/
private $factory;
/**
* @param FactoryInterface $factory
*/
public function __construct(FactoryInterface $factory)
{
$this->factory = $factory;
}
/**
* {@inheritDoc}
*/
public function createNew()
{
return $this->factory->createNew();
}
/**
* {@inheritdoc}
*/
public function createWithAmountAndCurrencyCode($amount, $currencyCode)
{
/** @var PaymentInterface $payment */
$payment = $this->factory->createNew();
$payment->setAmount($amount);
$payment->setCurrencyCode($currencyCode);
return $payment;
}
}
|
Refactor to take out form logic into its own function | 'use strict';
const choo = require('choo');
const html = require('choo/html');
const app = choo();
app.model({
state: {
todos: [],
},
reducers: {
addTodo: (state, data) => {
const newTodos = state.todos.slice();
newTodos.push(data);
return {
todos: newTodos,
};
},
},
});
const hTodoLi = (todo) => html`<li>${todo.title}</li>`;
const view = (state, prevState, send) => {
const onTaskSubmition = (e) => {
const userInput = e.target.children[0];
send('addTodo', { title: userInput.value });
userInput.value = '';
e.preventDefault();
};
return html`
<div>
<h1>ChooDo</h1>
<form onsubmit=${onTaskSubmition}>
<input type="text" placeholder="Write your next task here..." id="title" autofocus>
</form>
<ul>
${state.todos.map(hTodoLi)}
</ul>
</div>
`;
}
app.router([
['/', view],
]);
const tree = app.start();
document.body.appendChild(tree);
| 'use strict';
const choo = require('choo');
const html = require('choo/html');
const app = choo();
app.model({
state: {
todos: [],
},
reducers: {
addTodo: (state, data) => {
const newTodos = state.todos.slice();
newTodos.push(data);
return {
todos: newTodos,
};
},
},
});
const hTodoLi = (todo) => html`<li>${todo.title}</li>`;
const view = (state, prevState, send) => {
return html`
<div>
<h1>ChooDo</h1>
<form onsubmit=${(e) => {
const userInput = e.target.children[0]
send('addTodo', { title: userInput.value })
userInput.value = ''
e.preventDefault()
}}>
<input type="text" placeholder="Write your next task here..." id="title" autofocus>
</form>
<ul>
${state.todos.map(hTodoLi)}
</ul>
</div>
`;
}
app.router([
['/', view],
]);
const tree = app.start();
document.body.appendChild(tree);
|
Fix flow errors for Relay export
Reviewed By: yuzhi
Differential Revision: D4728271
fbshipit-source-id: a95d2d60de466738961c770dfad34fc049ea8683 | /**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule createRelayQuery
* @flow
*/
'use strict';
const RelayMetaRoute = require('RelayMetaRoute');
const RelayQuery = require('RelayQuery');
const invariant = require('invariant');
import type {RelayConcreteNode} from 'RelayQL';
import type {Variables} from 'RelayTypes';
function createRelayQuery(
node: RelayConcreteNode,
variables: Variables
): RelayQuery.Root {
invariant(
typeof variables === 'object' &&
variables != null &&
!Array.isArray(variables),
'Relay.Query: Expected `variables` to be an object.'
);
return RelayQuery.Root.create(
node,
RelayMetaRoute.get('$createRelayQuery'),
variables
);
}
module.exports = createRelayQuery;
| /**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule createRelayQuery
* @flow
*/
'use strict';
const RelayMetaRoute = require('RelayMetaRoute');
const RelayQuery = require('RelayQuery');
const invariant = require('invariant');
function createRelayQuery(
node: Object,
variables: {[key: string]: mixed}
): RelayQuery.Root {
invariant(
typeof variables === 'object' &&
variables != null &&
!Array.isArray(variables),
'Relay.Query: Expected `variables` to be an object.'
);
return RelayQuery.Root.create(
node,
RelayMetaRoute.get('$createRelayQuery'),
variables
);
}
module.exports = createRelayQuery;
|
Use lowercase when property on tools for things like "1980s" | import styled from 'styled-components';
import React from 'react';
import LanguageThemeProvider from 'components/LanguageThemeProvider';
import ContentBlock from 'components/ContentBlock';
const WhereWhenContainer = styled(ContentBlock)`
font-weight: 800;
color: white;
@media(max-width: 1320px) {
font-size: 8px;
line-height: 8px;
}
`;
const WhereContent = styled.span`
text-transform: uppercase;
`;
function WhereWhen(props) {
const where = props.where !== undefined ? props.where : '';
const when = props.when !== undefined ? props.when : '';
return (
<LanguageThemeProvider>
<WhereWhenContainer>
<WhereContent>{where}</WhereContent> {when}
</WhereWhenContainer>
</LanguageThemeProvider>
);
}
WhereWhen.propTypes = {
where: React.PropTypes.string,
when: React.PropTypes.string,
};
export default WhereWhen;
| import styled from 'styled-components';
import React from 'react';
import LanguageThemeProvider from 'components/LanguageThemeProvider';
import ContentBlock from 'components/ContentBlock';
const WhereWhenContainer = styled.div`
font-weight: 800;
color: white;
text-transform: uppercase;
`;
const WhereWhenContent = styled(ContentBlock)`
@media(max-width: 1320px) {
font-size: 8px;
line-height: 8px;
}
`;
function WhereWhen(props) {
const where = props.where !== undefined ? props.where : '';
const when = props.when !== undefined ? props.when : '';
return (
<WhereWhenContainer>
<LanguageThemeProvider>
<WhereWhenContent>
{`${where} ${when}`}
</WhereWhenContent>
</LanguageThemeProvider>
</WhereWhenContainer>
)
}
WhereWhen.propTypes = {
where: React.PropTypes.string,
when: React.PropTypes.string,
};
export default WhereWhen;
|
Delete the unzipped cache file | <?php
/**
* Spigot Timings Parser
*
* Written by Aikar <aikar@aikar.co>
*
* @license MIT
*/
class Cache {
private static $base = '/tmp/timings_';
public static function get($key) {
$file = self::getFile($key);
if (file_exists("$file.gz")) {
return trim(gzdecode(file_get_contents("$file.gz")));
} else if (file_exists($file)) {
$data = trim(file_get_contents($file));
self::put($key, $data);
unlink($file);
}
return null;
}
public static function put($key, $data) {
if (strlen($data) < MAX_CACHE_BYTES) {
file_put_contents(self::getFile($key).".gz", gzencode($data));
}
}
private static function getFile($key) {
return self::$base . md5($key);
}
}
| <?php
/**
* Spigot Timings Parser
*
* Written by Aikar <aikar@aikar.co>
*
* @license MIT
*/
class Cache {
private static $base = '/tmp/timings_';
public static function get($key) {
$file = self::getFile($key);
if (file_exists("$file.gz")) {
return trim(gzdecode(file_get_contents("$file.gz")));
} else if (file_exists($file)) {
$data = trim(file_get_contents($file));
self::put($key, $data);
//unlink($file); // Disabled for now while legacy code is the primary code
}
return null;
}
public static function put($key, $data) {
if (strlen($data) < MAX_CACHE_BYTES) {
file_put_contents(self::getFile($key).".gz", gzencode($data));
}
}
private static function getFile($key) {
return self::$base . md5($key);
}
}
|
Change mongodb uri to be an env var. | // Main starting point of the application
const express = require('express');
const path = require('path')
const http = require('http');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const app = express();
const router = require('./router');
const mongoose = require('mongoose');
const cors = require('cors');
// DB Setup
mongoose.connect(process.env.MONGODB_URI);
// App Setup
app.use(morgan('combined'));
app.use(cors());
app.use(express.static(path.resolve(__dirname, '..', 'build')));
app.use(bodyParser.json({ limit: '5mb' }));
app.use(bodyParser.urlencoded({ limit: '5mb', extended: true }));
router(app);
// Server Setup
const port = process.env.PORT || 3090;
const server = http.createServer(app);
server.listen(port);
console.log('Server listening on:', port);
| // Main starting point of the application
const express = require('express');
const path = require('path')
const http = require('http');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const app = express();
const router = require('./router');
const mongoose = require('mongoose');
const cors = require('cors');
// DB Setup
mongoose.connect('mongodb://localhost:auth/auth');
// App Setup
app.use(morgan('combined'));
app.use(cors());
app.use(express.static(path.resolve(__dirname, '..', 'build')));
app.use(bodyParser.json({ limit: '5mb' }));
app.use(bodyParser.urlencoded({ limit: '5mb', extended: true }));
router(app);
// Server Setup
const port = process.env.PORT || 3090;
const server = http.createServer(app);
server.listen(port);
console.log('Server listening on:', port);
|
Use a new instance of Filesystem | <?php namespace Algorit\Synchronizer;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\ServiceProvider;
use Algorit\Synchronizer\Request\Config;
use Algorit\Synchronizer\Storage\Sync;
use Algorit\Synchronizer\Storage\SyncEloquentRepository as SyncRepository;
class SynchronizerServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('algorit/synchronizer');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['synchronizer'] = $this->app->share(function()
{
$sync = new SyncRepository(new Sync);
$builder = new Builder(new Sender, new Receiver, $sync);
return new Loader(new Container, $builder, new Config(new Filesystem));
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array();
}
} | <?php namespace Algorit\Synchronizer;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\ServiceProvider;
use Algorit\Synchronizer\Request\Config;
use Algorit\Synchronizer\Storage\Sync;
use Algorit\Synchronizer\Storage\SyncEloquentRepository as SyncRepository;
class SynchronizerServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('algorit/synchronizer');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['synchronizer'] = $this->app->share(function($app)
{
$sync = new SyncRepository(new Sync);
$builder = new Builder(new Sender, new Receiver, $sync);
return new Loader(new Container, $builder, new Config($app['files']));
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array();
}
} |
Use __DIR__ as PHP < 5.3 is not supported | <?php
require __DIR__ . '/../vendor/autoload.php';
class JadePHPTest extends PHPUnit_Framework_TestCase {
static private $skipped = array(
// Here is the remain to implement list
'inheritance.extend.mixins',
'mixin.attrs',
'mixin.block-tag-behaviour',
'mixin.blocks',
'mixin.merge',
'tag.interpolation'
);
public function caseProvider() {
static $rawResults = null;
if(is_null($rawResults)) {
$rawResults = get_tests_results();
$rawResults = $rawResults['results'];
}
return $rawResults;
}
/**
* @dataProvider caseProvider
*/
public function testStringGeneration($name, $input, $expected) {
if(! in_array($name, static::$skipped)) {
$this->assertSame($input, $expected, $name);
}
}
}
| <?php
require dirname(__FILE__) . '/../vendor/autoload.php';
class JadePHPTest extends PHPUnit_Framework_TestCase {
static private $skipped = array(
// Here is the remain to implement list
'inheritance.extend.mixins',
'mixin.attrs',
'mixin.block-tag-behaviour',
'mixin.blocks',
'mixin.merge',
'tag.interpolation'
);
public function caseProvider() {
static $rawResults = null;
if(is_null($rawResults)) {
$rawResults = get_tests_results();
$rawResults = $rawResults['results'];
}
return $rawResults;
}
/**
* @dataProvider caseProvider
*/
public function testStringGeneration($name, $input, $expected) {
if(! in_array($name, static::$skipped)) {
$this->assertSame($input, $expected, $name);
}
}
}
|
Fix order of operations issues | __version__ = '0.10.0'
version = __version__
DEBUG = False
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
| __version__ = '0.10.0'
version = __version__
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
DEBUG = False
|
Fix a bug which prepend the header to NA sequence | # -*- coding: utf-8 -*-
def load(fp):
sequences = []
header = None
curseq = ''
for line in fp:
if line.startswith('>'):
if header and curseq:
sequences.append({
'header': header,
'sequence': curseq
})
header = line[1:].strip()
curseq = ''
elif line.startswith('#'):
continue
else:
curseq += line.strip()
if header and curseq:
sequences.append({
'header': header,
'sequence': curseq
})
return sequences
| # -*- coding: utf-8 -*-
def load(fp):
sequences = []
header = None
curseq = ''
for line in fp:
if line.startswith('>'):
if header and curseq:
sequences.append({
'header': header,
'sequence': curseq
})
header = line[1:].strip()
curseq = ''
if line.startswith('#'):
continue
else:
curseq += line.strip()
if header and curseq:
sequences.append({
'header': header,
'sequence': curseq
})
return sequences
|
Fix the name of the test | import { expect } from 'chai';
import { updateCellSource, executeCell } from '../../../src/notebook/actions';
import { liveStore, dispatchQueuePromise, waitForOutputs } from '../../utils';
describe('agendas', function() {
describe('executeCell', function() {
this.timeout(5000);
it('produces the right output', () => {
return liveStore((kernel, dispatch, store) => {
const cellId = store.getState().notebook.getIn(['cellOrder', 0]);
const source = 'print("a")';
dispatch(updateCellSource(cellId, source));
// TODO: Remove hack
// HACK: Wait 100ms before executing a cell because kernel ready and idle
// aren't enough. There must be another signal that we need to listen to.
return (new Promise(resolve => setTimeout(resolve, 100)))
.then(() => dispatch(executeCell(kernel.channels, cellId, source)))
.then(() => dispatchQueuePromise(dispatch))
.then(() => waitForOutputs(store, cellId))
.then(() => {
const output = store.getState().notebook.getIn(['cellMap', cellId, 'outputs', 0]).toJS();
expect(output.name).to.equal('stdout');
expect(output.text).to.equal('a\n');
expect(output.output_type).to.equal('stream');
});
});
});
});
});
| import { expect } from 'chai';
import { updateCellSource, executeCell } from '../../../src/notebook/actions';
import { liveStore, dispatchQueuePromise, waitForOutputs } from '../../utils';
describe('agendas', function() {
describe('executeCell', function() {
this.timeout(5000);
it('is within acceptable', () => {
return liveStore((kernel, dispatch, store) => {
const cellId = store.getState().notebook.getIn(['cellOrder', 0]);
const source = 'print("a")';
dispatch(updateCellSource(cellId, source));
// TODO: Remove hack
// HACK: Wait 100ms before executing a cell because kernel ready and idle
// aren't enough. There must be another signal that we need to listen to.
return (new Promise(resolve => setTimeout(resolve, 100)))
.then(() => dispatch(executeCell(kernel.channels, cellId, source)))
.then(() => dispatchQueuePromise(dispatch))
.then(() => waitForOutputs(store, cellId))
.then(() => {
const output = store.getState().notebook.getIn(['cellMap', cellId, 'outputs', 0]).toJS();
expect(output.name).to.equal('stdout');
expect(output.text).to.equal('a\n');
expect(output.output_type).to.equal('stream');
});
});
});
});
});
|
Fix test to use new findSrcPaths | package rev
import (
"path"
"path/filepath"
"testing"
)
func TestContentTypeByFilename(t *testing.T) {
testCases := map[string]string{
"xyz.jpg": "image/jpeg",
"helloworld.c": "text/x-c; charset=utf-8",
"helloworld.": "application/octet-stream",
"helloworld": "application/octet-stream",
"hello.world.c": "text/x-c; charset=utf-8",
}
srcPath, _ := findSrcPaths(REVEL_IMPORT_PATH)
ConfPaths = []string{path.Join(
srcPath,
filepath.FromSlash(REVEL_IMPORT_PATH),
"conf"),
}
loadMimeConfig()
for filename, expected := range testCases {
actual := ContentTypeByFilename(filename)
if actual != expected {
t.Errorf("%s: %s, Expected %s", filename, actual, expected)
}
}
}
| package rev
import (
"path"
"path/filepath"
"testing"
)
func TestContentTypeByFilename(t *testing.T) {
testCases := map[string]string{
"xyz.jpg": "image/jpeg",
"helloworld.c": "text/x-c; charset=utf-8",
"helloworld.": "application/octet-stream",
"helloworld": "application/octet-stream",
"hello.world.c": "text/x-c; charset=utf-8",
}
ConfPaths = []string{path.Join(
findSrcPath(REVEL_IMPORT_PATH),
filepath.FromSlash(REVEL_IMPORT_PATH),
"conf"),
}
loadMimeConfig()
for filename, expected := range testCases {
actual := ContentTypeByFilename(filename)
if actual != expected {
t.Errorf("%s: %s, Expected %s", filename, actual, expected)
}
}
}
|
Fix for creating paygroup without tax rule |
/**
* Order Types Schema
*/
Core.Schemas.PayGroup = new SimpleSchema({
_id: {
type: String,
optional: true
},
code: {
type: String
},
name: {
type: String
},
businessId: {
type: String
},
tax: {
type: String,
optional: true
},
pension: {
type: String,
optional: true
},
status: {
type: String,
defaultValue: "Active"
},
createdAt: {
type: Date,
autoValue: function () {
if (this.isInsert) {
return new Date;
} else if (this.isUpsert) {
return {
$setOnInsert: new Date
};
}
},
denyUpdate: true,
optional: true
}
});
|
/**
* Order Types Schema
*/
Core.Schemas.PayGroup = new SimpleSchema({
_id: {
type: String,
optional: true
},
code: {
type: String
},
name: {
type: String
},
businessId: {
type: String
},
tax: {
type: String
},
pension: {
type: String,
optional: true
},
status: {
type: String,
defaultValue: "Active"
},
createdAt: {
type: Date,
autoValue: function () {
if (this.isInsert) {
return new Date;
} else if (this.isUpsert) {
return {
$setOnInsert: new Date
};
}
},
denyUpdate: true,
optional: true
}
});
|
Stop to use the __future__ module.
The __future__ module [1] was used in this context to ensure compatibility
between python 2 and python 3.
We previously dropped the support of python 2.7 [2] and now we only support
python 3 so we don't need to continue to use this module and the imports
listed below.
Imports commonly used and their related PEPs:
- `division` is related to PEP 238 [3]
- `print_function` is related to PEP 3105 [4]
- `unicode_literals` is related to PEP 3112 [5]
- `with_statement` is related to PEP 343 [6]
- `absolute_import` is related to PEP 328 [7]
[1] https://docs.python.org/3/library/__future__.html
[2] https://governance.openstack.org/tc/goals/selected/ussuri/drop-py27.html
[3] https://www.python.org/dev/peps/pep-0238
[4] https://www.python.org/dev/peps/pep-3105
[5] https://www.python.org/dev/peps/pep-3112
[6] https://www.python.org/dev/peps/pep-0343
[7] https://www.python.org/dev/peps/pep-0328
Change-Id: I2b2f006e0ec145730bec843add4147345797b920 | # -*- coding: utf-8 -*-
# Copyright (C) 2015 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import fixtures
from debtcollector import _utils
class DisableFixture(fixtures.Fixture):
"""Fixture that disables debtcollector triggered warnings.
This does **not** disable warnings calls emitted by other libraries.
This can be used like::
from debtcollector.fixtures import disable
with disable.DisableFixture():
<some code that calls into depreciated code>
"""
def _setUp(self):
self.addCleanup(setattr, _utils, "_enabled", True)
_utils._enabled = False
| # -*- coding: utf-8 -*-
# Copyright (C) 2015 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import
import fixtures
from debtcollector import _utils
class DisableFixture(fixtures.Fixture):
"""Fixture that disables debtcollector triggered warnings.
This does **not** disable warnings calls emitted by other libraries.
This can be used like::
from debtcollector.fixtures import disable
with disable.DisableFixture():
<some code that calls into depreciated code>
"""
def _setUp(self):
self.addCleanup(setattr, _utils, "_enabled", True)
_utils._enabled = False
|
Fix tests config for invitation system | import Enzyme, { shallow, render, mount } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import React from 'react'
import 'isomorphic-fetch'
import 'fetch-mock'
global.React = React
// React 16 Enzyme adapter
Enzyme.configure({ adapter: new Adapter() })
// Configure global env variables
process.env.HTTP_API_URL = 'http://test'
process.env.INVITATION_SYSTEM = 'off'
// Make Enzyme functions available in all test files without importing
global.shallow = shallow
global.render = render
global.mount = mount
// Add a helper to register snapshot
global.snapshot = element => expect(element).toMatchSnapshot()
// Shallow then snapshot component
global.snapshotComponent = component => snapshot(shallow(component))
/**
* Apply all actions to given reducer and make a snapshot at each step.
*/
global.snapshotReducer = ((reducer, initialState, ...actions) => {
snapshot(initialState)
return actions.reduce((state, action) => {
const newState = reducer(state, action)
snapshot(newState)
return newState
}, initialState)
})
| import Enzyme, { shallow, render, mount } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import React from 'react'
import 'isomorphic-fetch'
import 'fetch-mock'
global.React = React
// React 16 Enzyme adapter
Enzyme.configure({ adapter: new Adapter() })
// Configure global env variables
process.env.HTTP_API_URL = 'http://test'
// Make Enzyme functions available in all test files without importing
global.shallow = shallow
global.render = render
global.mount = mount
// Add a helper to register snapshot
global.snapshot = element => expect(element).toMatchSnapshot()
// Shallow then snapshot component
global.snapshotComponent = component => snapshot(shallow(component))
/**
* Apply all actions to given reducer and make a snapshot at each step.
*/
global.snapshotReducer = ((reducer, initialState, ...actions) => {
snapshot(initialState)
return actions.reduce((state, action) => {
const newState = reducer(state, action)
snapshot(newState)
return newState
}, initialState)
})
|
Use CONTACT_EMAIL als default from address | from django.contrib.sites.models import Site
from django.template.loader import get_template
from django.utils import translation
from bluebottle.clients.context import ClientContext
from bluebottle.clients.mail import EmailMultiAlternatives
from bluebottle.clients import properties
def send_mail(template_name, subject, to, **kwargs):
if hasattr(to, 'primary_language') and to.primary_language:
translation.activate(to.primary_language)
kwargs.update({
'receiver': to,
'site': 'https://{0}'.format(Site.objects.get_current().domain)
})
context = ClientContext(kwargs)
subject = unicode(subject) # Unlazy the translatable string subject within activated language.
text_content = get_template('{0}.txt'.format(template_name)).render(context)
html_content = get_template('{0}.html'.format(template_name)).render(context)
if hasattr(to, 'primary_language') and to.primary_language:
translation.deactivate()
from_email = properties.CONTACT_EMAIL
msg = EmailMultiAlternatives(subject=subject, from_email=from_email, body=text_content, to=[to.email])
msg.attach_alternative(html_content, "text/html")
return msg.send()
| from django.contrib.sites.models import Site
from django.template.loader import get_template
from django.utils import translation
from bluebottle.clients.context import ClientContext
from bluebottle.clients.mail import EmailMultiAlternatives
def send_mail(template_name, subject, to, **kwargs):
if hasattr(to, 'primary_language') and to.primary_language:
translation.activate(to.primary_language)
kwargs.update({
'receiver': to,
'site': 'https://{0}'.format(Site.objects.get_current().domain)
})
context = ClientContext(kwargs)
subject = unicode(subject) # Unlazy the translatable string subject within activated language.
text_content = get_template('{0}.txt'.format(template_name)).render(context)
html_content = get_template('{0}.html'.format(template_name)).render(context)
if hasattr(to, 'primary_language') and to.primary_language:
translation.deactivate()
msg = EmailMultiAlternatives(subject=subject, body=text_content, to=[to.email])
msg.attach_alternative(html_content, "text/html")
return msg.send()
|
Add category as category page variable
This data will be available in the layouts.
Built from 6b3249e82a8954febf35b9f92a98b4643893c2ec. | var pagination = require('hexo-pagination');
var _ = require('lodash');
hexo.extend.generator.register('category', function(locals){
var config = this.config;
var categories = locals.data.categories;
if (config.category_generator) {
var perPage = config.category_generator.per_page;
} else {
var perPage = 10;
}
var paginationDir = config.pagination_dir || 'page';
var result = [];
_.each(categories, function(data, title) {
_.each(data, function(data, lang) {
result = result.concat(
pagination(lang + '/' + data.slug, getCategoryByName(locals.categories, data.category).posts, {
perPage: perPage,
layout: ['category', 'archive', 'index'],
format: paginationDir + '/%d/',
data: {
lang: lang,
title: data.name,
category: data.category
}
})
);
});
});
return result;
});
function getCategoryByName(categories, name) {
return categories.toArray().filter(function(category){
return category.name == name;
})[0];
}
| var pagination = require('hexo-pagination');
var _ = require('lodash');
hexo.extend.generator.register('category', function(locals){
var config = this.config;
var categories = locals.data.categories;
if (config.category_generator) {
var perPage = config.category_generator.per_page;
} else {
var perPage = 10;
}
var paginationDir = config.pagination_dir || 'page';
var result = [];
_.each(categories, function(data, title) {
_.each(data, function(data, lang) {
result = result.concat(
pagination(lang + '/' + data.slug, getCategoryByName(locals.categories, data.category).posts, {
perPage: perPage,
layout: ['category', 'archive', 'index'],
format: paginationDir + '/%d/',
data: {
lang: lang,
title: data.name
}
})
);
});
});
return result;
});
function getCategoryByName(categories, name) {
return categories.toArray().filter(function(category){
return category.name == name;
})[0];
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.