text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
[AC-9046] Fix the query for updating the people and mentor urls to community url
|
# Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
SiteRedirectPage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url)).update(new_url=community_url)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0073_auto_20210909_1706'),
]
operations = [
migrations.RunPython(update_url_to_community,
migrations.RunPython.noop)
]
|
# Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
for siteredirectpage in SiteRedirectPage.objects.all():
has_old_url = siteredirectpage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url))
if has_old_url.exists():
has_old_url.update(new_url=community_url)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0073_auto_20210909_1706'),
]
operations = [
migrations.RunPython(update_url_to_community,
migrations.RunPython.noop)
]
|
Allow specifying custom host and port when starting app
|
"""Task functions for use with Invoke."""
from invoke import task
@task
def clean(context):
cmd = '$(npm bin)/gulp clean'
context.run(cmd)
@task
def requirements(context):
steps = [
'pip install -r requirements.txt',
'npm install',
'$(npm bin)/bower install',
]
cmd = ' && '.join(steps)
context.run(cmd)
@task
def run(context, host='127.0.0.1', port='5000'):
steps = [
'open http://{host}:{port}/',
'FLASK_APP=typesetter/typesetter.py FLASK_DEBUG=1 flask run --host={host} --port={port}',
]
steps = [step.format(host=host, port=port) for step in steps]
cmd = ' && '.join(steps)
context.run(cmd)
@task
def static(context):
cmd = '$(npm bin)/gulp'
context.run(cmd)
|
"""Task functions for use with Invoke."""
from invoke import task
@task
def clean(context):
cmd = '$(npm bin)/gulp clean'
context.run(cmd)
@task
def requirements(context):
steps = [
'pip install -r requirements.txt',
'npm install',
'$(npm bin)/bower install',
]
cmd = ' && '.join(steps)
context.run(cmd)
@task
def run(context):
steps = [
'open http://127.0.0.1:5000/',
'FLASK_APP=typesetter/typesetter.py FLASK_DEBUG=1 flask run',
]
cmd = ' && '.join(steps)
context.run(cmd)
@task
def static(context):
cmd = '$(npm bin)/gulp'
context.run(cmd)
|
Fix broken path for destination
|
/* eslint-env node */
/** global: Buffer */
'use strict';
const gutil = require('gulp-util');
const through = require('through2');
const wpPot = require('wp-pot');
const PluginError = gutil.PluginError;
/**
* Determine if `obj` is a object or not.
*
* @param {object} obj
*
* @return {boolean}
*/
function isObject (obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
/**
* Run the wp pot generator.
*
* @param {object} options
*
* @return {object}
*/
function gulpWPpot (options) {
if (options !== undefined && !isObject(options)) {
throw new PluginError('gulp-wp-pot', 'Require a argument of type object.');
}
let files = [];
const stream = through.obj(function (file, enc, cb) {
if (file.isStream()) {
throw new PluginError('gulp-wp-pot', 'Streams are not supported.');
}
files.push(file.path);
cb();
}, function (cb) {
if (!options) {
options = {};
}
options.src = files;
options.writeFile = false;
const potContents = wpPot(options);
const potFile = new gutil.File({
contents: new Buffer(potContents),
path: '.'
});
this.push(potFile);
cb();
});
return stream;
}
module.exports = gulpWPpot;
|
/* eslint-env node */
/** global: Buffer */
'use strict';
const gutil = require('gulp-util');
const through = require('through2');
const wpPot = require('wp-pot');
const PluginError = gutil.PluginError;
/**
* Determine if `obj` is a object or not.
*
* @param {object} obj
*
* @return {boolean}
*/
function isObject (obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
/**
* Run the wp pot generator.
*
* @param {object} options
*
* @return {object}
*/
function gulpWPpot (options) {
if (options !== undefined && !isObject(options)) {
throw new PluginError('gulp-wp-pot', 'Require a argument of type object.');
}
let files = [];
const stream = through.obj(function (file, enc, cb) {
if (file.isStream()) {
throw new PluginError('gulp-wp-pot', 'Streams are not supported.');
}
files.push(file.path);
cb();
}, function (cb) {
if (!options) {
options = {};
}
options.src = files;
options.writeFile = false;
const potContents = wpPot(options);
const potFile = new gutil.File({
contents: new Buffer(potContents)
});
this.push(potFile);
cb();
});
return stream;
}
module.exports = gulpWPpot;
|
Add space character after code element
|
import React, { PropTypes } from 'react'
export default function Counter({
increment,
incrementIfOdd,
decrement,
counter,
}) {
return (
<section>
<p className="intro">
To get started, edit <code>src/routes/index.js </code>
and save to reload.
</p>
<p>
Clicked: {counter} times
{' '}
<button onClick={increment}>+</button>
{' '}
<button onClick={decrement}>-</button>
{' '}
<button onClick={incrementIfOdd}>Increment if odd</button>
</p>
</section>
)
}
Counter.propTypes = {
increment: PropTypes.func.isRequired,
incrementIfOdd: PropTypes.func.isRequired,
decrement: PropTypes.func.isRequired,
counter: PropTypes.number.isRequired,
}
|
import React, { PropTypes } from 'react'
export default function Counter({
increment,
incrementIfOdd,
decrement,
counter,
}) {
return (
<section>
<p className="intro">
To get started, edit <code>src/routes/index.js</code>
and save to reload.
</p>
<p>
Clicked: {counter} times
{' '}
<button onClick={increment}>+</button>
{' '}
<button onClick={decrement}>-</button>
{' '}
<button onClick={incrementIfOdd}>Increment if odd</button>
</p>
</section>
)
}
Counter.propTypes = {
increment: PropTypes.func.isRequired,
incrementIfOdd: PropTypes.func.isRequired,
decrement: PropTypes.func.isRequired,
counter: PropTypes.number.isRequired,
}
|
Update tests for new redirect-after-create stream.
|
from tornado.httpclient import HTTPRequest
from nose.tools import eq_, ok_
import json
import faker
from astral.api.tests import BaseTest
from astral.models import Stream
from astral.models.tests.factories import StreamFactory
class StreamsHandlerTest(BaseTest):
def test_get_streams(self):
[StreamFactory() for _ in range(3)]
response = self.fetch('/streams')
eq_(response.code, 200)
result = json.loads(response.body)
ok_('streams' in result)
for stream in result['streams']:
ok_(Stream.get_by(name=stream['name']))
def test_create_stream(self):
data = {'name': faker.lorem.sentence()}
eq_(Stream.get_by(name=data['name']), None)
self.http_client.fetch(HTTPRequest(
self.get_url('/streams'), 'POST', body=json.dumps(data),
follow_redirects=False), self.stop)
response = self.wait()
eq_(response.code, 302)
ok_(Stream.get_by(name=data['name']))
|
from tornado.httpclient import HTTPRequest
from nose.tools import eq_, ok_
import json
import faker
from astral.api.tests import BaseTest
from astral.models import Stream
from astral.models.tests.factories import StreamFactory
class StreamsHandlerTest(BaseTest):
def test_get_streams(self):
[StreamFactory() for _ in range(3)]
response = self.fetch('/streams')
eq_(response.code, 200)
result = json.loads(response.body)
ok_('streams' in result)
for stream in result['streams']:
ok_(Stream.get_by(name=stream['name']))
def test_create_stream(self):
data = {'name': faker.lorem.sentence()}
eq_(Stream.get_by(name=data['name']), None)
self.http_client.fetch(HTTPRequest(
self.get_url('/streams'), 'POST', body=json.dumps(data)), self.stop)
response = self.wait()
eq_(response.code, 200)
ok_(Stream.get_by(name=data['name']))
|
:fire: Remove unused function and import in tests
|
import expect from 'expect.js'
import {fix} from '../../../src/typography-fixer'
import rules from '../../../src/rules/en-UK/html'
const fixString = fix(rules)
describe('en-UK html rules', () => {
it('includes fraction rules', () => {
expect(rules.some((r) => {
return r.name.indexOf('html.common') >= 0
})).to.be(true)
})
it('wraps ordinal number suffix in a ord span', () => {
expect(fixString('1st')).to.eql('1<span class="ord">st</span>')
expect(fixString('2nd')).to.eql('2<span class="ord">nd</span>')
expect(fixString('3rd')).to.eql('3<span class="ord">rd</span>')
expect(fixString('4th')).to.eql('4<span class="ord">th</span>')
expect(fixString('10th')).to.eql('10<span class="ord">th</span>')
expect(fixString('21st')).to.eql('21<span class="ord">st</span>')
})
})
|
import expect from 'expect.js'
import {fix, check} from '../../../src/typography-fixer'
import rules from '../../../src/rules/en-UK/html'
const fixString = fix(rules)
const checkString = check(rules)
describe('en-UK html rules', () => {
it('includes fraction rules', () => {
expect(rules.some((r) => {
return r.name.indexOf('html.common') >= 0
})).to.be(true)
})
it('wraps ordinal number suffix in a ord span', () => {
expect(fixString('1st')).to.eql('1<span class="ord">st</span>')
expect(fixString('2nd')).to.eql('2<span class="ord">nd</span>')
expect(fixString('3rd')).to.eql('3<span class="ord">rd</span>')
expect(fixString('4th')).to.eql('4<span class="ord">th</span>')
expect(fixString('10th')).to.eql('10<span class="ord">th</span>')
expect(fixString('21st')).to.eql('21<span class="ord">st</span>')
})
})
|
Handle julian leap days separately.
|
from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar == other.calendar and self.date == other.date
class Calendar(object):
def from_date(self, date):
return DateWithCalendar(self.__class__, date)
class ProlepticGregorianCalendar(Calendar):
def date(self, year, month, day):
d = date(year, month, day)
return self.from_date(d)
class JulianCalendar(Calendar):
@staticmethod
def is_julian_leap_year(y):
return (y % 4) == 0
def date(self, year, month, day):
if day == 29 and month == 2 and self.is_julian_leap_year(year):
d = date(year, month, 28)
d = d + timedelta(days=11)
else:
d = date(year, month, day)
d = d + timedelta(days=10)
return self.from_date(d)
|
from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar == other.calendar and self.date == other.date
class Calendar(object):
def from_date(self, date):
return DateWithCalendar(self.__class__, date)
class ProlepticGregorianCalendar(Calendar):
def date(self, year, month, day):
d = date(year, month, day)
return self.from_date(d)
class JulianCalendar(Calendar):
def date(self, year, month, day):
d = date(year, month, day)
d = d + timedelta(days=10)
return self.from_date(d)
|
Add branch tag to saucelabs runs
|
var fs = require('fs');
var specs = JSON.parse(fs.readFileSync('tests/end2end/specs.json'));
var browser_capabilities = JSON.parse(process.env.SELENIUM_BROWSER_CAPABILITIES);
browser_capabilities['name'] = 'GlobaLeaks-E2E';
browser_capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
browser_capabilities['build'] = process.env.TRAVIS_BUILD_NUMBER;
browser_capabilities['tags'] = [process.env.TRAVIS_BRANCH];
exports.config = {
framework: 'jasmine',
baseUrl: 'http://localhost:9000/',
troubleshoot: false,
directConnect: false,
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
capabilities: browser_capabilities,
params: {
'testFileDownload': false,
'verifyFileDownload': false,
'tmpDir': '/tmp/globaleaks-download',
},
specs: specs,
jasmineNodeOpts: {
isVerbose: true,
includeStackTrace: true,
defaultTimeoutInterval: 360000
}
};
|
var fs = require('fs');
var specs = JSON.parse(fs.readFileSync('tests/end2end/specs.json'));
var browser_capabilities = JSON.parse(process.env.SELENIUM_BROWSER_CAPABILITIES);
browser_capabilities['name'] = 'GlobaLeaks-E2E';
browser_capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
browser_capabilities['build'] = process.env.TRAVIS_BUILD_NUMBER;
exports.config = {
framework: 'jasmine',
baseUrl: 'http://localhost:9000/',
troubleshoot: false,
directConnect: false,
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
capabilities: browser_capabilities,
params: {
'testFileDownload': false,
'verifyFileDownload': false,
'tmpDir': '/tmp/globaleaks-download',
},
specs: specs,
jasmineNodeOpts: {
isVerbose: true,
includeStackTrace: true,
defaultTimeoutInterval: 360000
}
};
|
Replace all keys/tokens/passwords by env variables
|
from flask import Flask, request
from flask.ext.sqlalchemy import SQLAlchemy
from twilio import twiml
import subprocess
import os
from cmd import cmds
app = Flask(__name__)
#app.config.from_object('config')
db = SQLAlchemy(app)
ACCOUNT_SID = os.environ['ACCOUNT_SID']
AUTH_TOKEN = os.environ['AUTH_TOKEN']
APP_SID = os.environ['APP_SID']
CALLER_ID = os.environ['CALLER_ID']
@app.route("/")
def index():
return "Hello, world"
@app.route('/sms', methods=['POST'])
def sms():
response = twiml.Response()
user_input = request.form['Body']
if '|' in user_input:
args = user_input.split('|')
for index, arg in enumerate(args):
args[index] = arg.lower().split()
output = cmds['pipe'](args)
else:
args = user_input.lower().split()
output = cmds[args[0]](args)
response.sms(output)
return str(response)
if __name__ == "__main__":
#app.run(debug=True)
app.debug = True
app.run(host='0.0.0.0')
|
from flask import Flask, request
from flask.ext.sqlalchemy import SQLAlchemy
from twilio import twiml
import subprocess
import os
from cmd import cmds
app = Flask(__name__)
#app.config.from_object('config')
db = SQLAlchemy(app)
ACCOUNT_SID = "" #os.environ['ACCOUNT_SID']
AUTH_TOKEN = "" #os.environ['AUTH_TOKEN']
APP_SID = "Twilix" #os.environ['APP_SID']
CALLER_ID = "+14389855700" #os.environ['CALLER_ID']
#CALLER_ID = "+17038955689" #os.environ['CALLER_ID']
#CALLER_ID = "+18175985398" #os.environ['CALLER_ID']
@app.route("/")
def index():
return "Hello, world"
@app.route('/sms', methods=['POST'])
def sms():
response = twiml.Response()
user_input = request.form['Body']
if '|' in user_input:
pass
else:
args = user_input.lower().split()
output = cmds[args[0]](args[1:])
response.sms(output)
return str(response)
if __name__ == "__main__":
#app.run(debug=True)
app.debug = True
app.run(host='0.0.0.0')
|
Write test data as list unless otherwise needed
|
from simulocloud import PointCloud
import json
import numpy as np
_TEST_XYZ = [[10.0, 12.2, 14.4, 16.6, 18.8],
[11.1, 13.3, 15.5, 17.7, 19.9],
[0.1, 2.1, 4.5, 6.7, 8.9]]
_EXPECTED_POINTS = np.array([( 10. , 11.1, 0.1),
( 12.2, 13.3, 2.1),
( 14.4, 15.5, 4.5),
( 16.6, 17.7, 6.7),
( 18.8, 19.9, 8.9)],
dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])
def test_PointCloud_from_lists():
""" Can PointCloud initialisable directly from `[[xs], [ys], [zs]]` ?"""
assert np.all(PointCloud(_TEST_XYZ).points == _EXPECTED_POINTS)
|
from simulocloud import PointCloud
import json
import numpy as np
_TEST_XYZ = """[[10.0, 12.2, 14.4, 16.6, 18.8],
[11.1, 13.3, 15.5, 17.7, 19.9],
[0.1, 2.1, 4.5, 6.7, 8.9]]"""
_EXPECTED_POINTS = np.array([( 10. , 11.1, 0.1),
( 12.2, 13.3, 2.1),
( 14.4, 15.5, 4.5),
( 16.6, 17.7, 6.7),
( 18.8, 19.9, 8.9)],
dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])
def test_PointCloud_from_lists():
""" Can PointCloud initialisable directly from `[[xs], [ys], [zs]]` ?"""
assert np.all(PointCloud(json.loads(_TEST_XYZ)).points == _EXPECTED_POINTS)
|
Correct CSS class for forum view
|
/*
Copyright 2018 Carmilla Mina Jankovic
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.
*/
const ViewWrapper = require('../ViewWrapper');
const ForumList = require('../lists/ForumList');
const ForumPage = require('./ForumPage');
const UserList = require('../lists/UserList');
class ForumView extends ViewWrapper {
constructor({
classes = [],
elementId = `fView-${Date.now()}`,
}) {
const forumList = new ForumList({});
const forumPage = new ForumPage({});
const userList = new UserList({
title: 'Users',
});
super({
elementId,
columns: [
{
components: [
{ component: forumList },
{ component: userList },
],
classes: ['columnList'],
},
{ components: [{ component: forumPage }] },
],
classes: classes.concat(['forumView']),
});
}
}
module.exports = ForumView;
|
/*
Copyright 2018 Carmilla Mina Jankovic
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.
*/
const ViewWrapper = require('../ViewWrapper');
const ForumList = require('../lists/ForumList');
const ForumPage = require('./ForumPage');
const UserList = require('../lists/UserList');
class ForumView extends ViewWrapper {
constructor({
classes = [],
elementId = `fView-${Date.now()}`,
}) {
const forumList = new ForumList({});
const forumPage = new ForumPage({});
const userList = new UserList({
title: 'Users',
});
super({
elementId,
columns: [
{
components: [
{ component: forumList },
{ component: userList },
],
classes: ['columnList'],
},
{ components: [{ component: forumPage }] },
],
classes: classes.concat(['docFileView']),
});
}
}
module.exports = ForumView;
|
Make tests forwards-compatible with new email API
|
from base64 import b64encode
import quopri
from daemail.message import DraftMessage
TEXT = 'àéîøü\n'
# Something in the email module implicitly adds a newline to the body text if
# one isn't present, so we need to include one here lest the base64 encodings
# not match up.
TEXT_ENC = TEXT.encode('utf-8')
def test_7bit_text():
msg = DraftMessage()
msg.addtext(TEXT)
blob = msg.compile()
assert isinstance(blob, bytes)
assert TEXT_ENC not in blob
assert quopri.encodestring(TEXT_ENC) in blob or b64encode(TEXT_ENC) in blob
def test_7bit_multipart():
msg = DraftMessage()
msg.addtext(TEXT)
msg.addmimeblob(b'\0\0\0\0', 'application/octet-stream', 'null.dat')
blob = msg.compile()
assert isinstance(blob, bytes)
assert TEXT_ENC not in blob
assert quopri.encodestring(TEXT_ENC) in blob or b64encode(TEXT_ENC) in blob
|
import quopri
from daemail.message import DraftMessage
TEXT = 'àéîøü'
def test_quopri_text():
msg = DraftMessage()
msg.addtext(TEXT)
blob = msg.compile()
assert isinstance(blob, bytes)
assert TEXT.encode('utf-8') not in blob
assert quopri.encodestring(TEXT.encode('utf-8')) in blob
def test_quopri_multipart():
msg = DraftMessage()
msg.addtext(TEXT)
msg.addmimeblob(b'\0\0\0\0', 'application/octet-stream', 'null.dat')
blob = msg.compile()
assert isinstance(blob, bytes)
assert TEXT.encode('utf-8') not in blob
assert quopri.encodestring(TEXT.encode('utf-8')) in blob
|
Add breadcrumbs to the frontend actions
Fixes #11
|
<?php
/**
* Frontend {{ moduleName }} {{ action }} action
*/
class Frontend{{ moduleName|capitalize }}{{ action|capitalize }} extends FrontendBaseBlock
{
/**
* Execute the extra
*
* @return void
*/
public function execute()
{
parent::execute();
$this->loadTemplate();
$this->getData();
$this->parse();
}
/**
* Load the data, don't forget to validate the incoming data
*
* @return void
*/
protected function getData()
{
}
/**
* Parse the data into the template
*
* @return void
*/
protected function parse()
{
// Breadcrumbs
$this->breadcrumb->addElement(
SpoonFilter::ucfirst(FL::lbl('{{ moduleName|capitalize }}')),
FrontendNavigation::getBackendURLForBlock('index', '{{ moduleName }}')
);
{% if action != 'index' %}
$this->breadcrumb->addElement(
SpoonFilter::ucfirst(FL::lbl('{{ action|capitalize }}')),
FrontendNavigation::getBackendURLForBlock('{{ action }}', '{{ moduleName }}')
);
{% endif %}
}
}
|
<?php
/**
* Frontend {{ moduleName }} {{ action }} action
*/
class Frontend{{ moduleName|capitalize }}{{ action|capitalize }} extends FrontendBaseBlock
{
/**
* Execute the extra
*
* @return void
*/
public function execute()
{
parent::execute();
$this->loadTemplate();
$this->getData();
$this->parse();
}
/**
* Load the data, don't forget to validate the incoming data
*
* @return void
*/
protected function getData()
{
}
/**
* Parse the data into the template
*
* @return void
*/
protected function parse()
{
}
}
|
Make get_build print nice(r) JSON output
BUG=skia:
Review-Url: https://codereview.chromium.org/2183313008
|
package main
import (
"bytes"
"encoding/json"
"flag"
"path"
"github.com/skia-dev/glog"
"go.skia.org/infra/go/auth"
"go.skia.org/infra/go/buildbucket"
"go.skia.org/infra/go/common"
)
var (
id = flag.String("id", "", "ID of the build to retrieve.")
workdir = flag.String("workdir", "workdir", "Working directory to use.")
)
func main() {
defer common.LogPanic()
common.Init()
if *id == "" {
glog.Fatal("ID is required.")
}
// Initialize the BuildBucket client.
c, err := auth.NewClient(true, path.Join(*workdir, "oauth_token_cache"), buildbucket.DEFAULT_SCOPES...)
if err != nil {
glog.Fatal(err)
}
bb := buildbucket.NewClient(c)
// Retrieve the build.
build, err := bb.GetBuild(*id)
if err != nil {
glog.Fatal(err)
}
// Pretty print the build.
b, err := json.Marshal(build)
if err != nil {
glog.Fatal(err)
}
var out bytes.Buffer
if err := json.Indent(&out, b, "", "\t"); err != nil {
glog.Fatal(err)
}
glog.Infof("Build: %s\n%s", build.Url, out.String())
}
|
package main
import (
"flag"
"path"
"github.com/skia-dev/glog"
"go.skia.org/infra/go/auth"
"go.skia.org/infra/go/buildbucket"
"go.skia.org/infra/go/common"
)
var (
id = flag.String("id", "", "ID of the build to retrieve.")
workdir = flag.String("workdir", "workdir", "Working directory to use.")
)
func main() {
defer common.LogPanic()
common.Init()
if *id == "" {
glog.Fatal("ID is required.")
}
// Initialize the BuildBucket client.
c, err := auth.NewClient(true, path.Join(*workdir, "oauth_token_cache"), buildbucket.DEFAULT_SCOPES...)
if err != nil {
glog.Fatal(err)
}
bb := buildbucket.NewClient(c)
// Retrieve the build.
build, err := bb.GetBuild(*id)
if err != nil {
glog.Fatal(err)
}
glog.Infof("Build: %s\n%v", build.Url, build)
}
|
Change of domain name to api.socketlabs.com
|
<?php
//prints each recipient email addresses associated for delivery failures
//
//replace the following constant **** values with your own
define("ACCOUNT_ID", "9999");
define("API_USER", "user");
define("API_PASSWORD", "3150ebe08f4c66a3ba3f");
//calls messagesFailed
$service_url = 'https://api.socketlabs.com/messagesFailed?accountId=' . ACCOUNT_ID . '&type=xml';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERPWD, API_USER . ':' . API_PASSWORD);
$curl_response = curl_exec($curl);
curl_close($curl);
//parses XML response and outputs the email addresses of associated with each failure
$xml = new SimpleXMLElement($curl_response);
echo $xml->count[0] . ' records returned:<br/>';
echo $xml->collection->item[0]->ToAddress;
foreach($xml->collection->item as $item) {
echo $item->ToAddress . '<br/>';
}
print_r($xml);
//see https://www.socketlabs.com/od/api for complete API documentation
?>
|
<?php
//prints each recipient email addresses associated for delivery failures
//
//replace the following constant **** values with your own
define("ACCOUNT_ID", "9999");
define("API_USER", "user");
define("API_PASSWORD", "3150ebe08f4c66a3ba3f");
//calls messagesFailed
$service_url = 'https://api.email-od.com/messagesFailed?accountId=' . ACCOUNT_ID . '&type=xml';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERPWD, API_USER . ':' . API_PASSWORD);
$curl_response = curl_exec($curl);
curl_close($curl);
//parses XML response and outputs the email addresses of associated with each failure
$xml = new SimpleXMLElement($curl_response);
echo $xml->count[0] . ' records returned:<br/>';
echo $xml->collection->item[0]->ToAddress;
foreach($xml->collection->item as $item) {
echo $item->ToAddress . '<br/>';
}
print_r($xml);
//see https://www.socketlabs.com/od/api for complete API documentation
?>
|
Use relative imports, Python 2.6 style
|
__author__ = 'Daniel Greenfeld, Chris Adams'
VERSION = (0, 5, 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
return version
__version__ = get_version()
def clean_html():
raise ImportError("clean_html requires html5lib or pytidylib")
def sanitize_html():
raise ImportError("sanitize_html requires html5lib")
try:
import html5lib
from .utils import clean_html5lib as clean_html
from .utils import sanitize_html5lib as sanitize_html
except ImportError:
try:
import tidylib
from .utils import clean_tidylib as clean_html
except ImportError:
pass
|
__author__ = 'Daniel Greenfeld, Chris Adams'
VERSION = (0, 5, 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
return version
__version__ = get_version()
def clean_html():
raise ImportError("clean_html requires html5lib or pytidylib")
def sanitize_html():
raise ImportError("sanitize_html requires html5lib")
try:
import html5lib
from utils import clean_html5lib as clean_html
from utils import sanitize_html5lib as sanitize_html
except ImportError:
try:
import tidylib
from utils import clean_tidylib as clean_html
except ImportError:
pass
|
Rename data prop to initial
|
/* @flow */
export const inMemory = (initial : Object, transition : Function) => {
let rootState = initial;
const read = () => rootState;
const write = (fn : Function) => {
const oldState = read();
const newState = fn(oldState);
transition(oldState, newState);
rootState = newState;
return read();
};
return { read, write };
};
export const webStorage = (
{ type, key } : Object,
initial : Object,
transition : Function
) => {
const store = window[`${type}Storage`];
const read = () => JSON.parse(store.getItem(key));
const write = (fn : Function) => {
const oldState = read();
const newState = fn(oldState);
transition(oldState, newState);
store.setItem(key, JSON.stringify(newState));
return read();
};
return { read, write };
};
|
/* @flow */
export const inMemory = (data : Object, transition : Function) => {
let rootState = data;
const read = () => rootState;
const write = (fn : Function) => {
const oldState = read();
const newState = fn(oldState);
transition(oldState, newState);
rootState = newState;
return read();
};
return { read, write };
};
export const webStorage = (
{ type, key } : Object,
data : Object,
transition : Function
) => {
const store = window[`${type}Storage`];
const read = () => JSON.parse(store.getItem(key));
const write = (fn : Function) => {
const oldState = read();
const newState = fn(oldState);
transition(oldState, newState);
store.setItem(key, JSON.stringify(newState));
return read();
};
return { read, write };
};
|
Update login api changes for steemconnect-v2
|
import Promise from 'bluebird';
import steemConnect from 'sc2-sdk';
import Cookie from 'js-cookie';
import request from 'superagent';
import { getFollowing } from '../user/userActions';
import { initPushpad } from './pushpadHelper';
Promise.promisifyAll(steemConnect);
Promise.promisifyAll(request.Request.prototype);
export const LOGIN = '@auth/LOGIN';
export const LOGIN_REQUEST = '@auth/LOGIN_START';
export const LOGIN_SUCCESS = '@auth/LOGIN_SUCCESS';
export const LOGIN_FAILURE = '@auth/LOGIN_ERROR';
export const LOGOUT = '@auth/LOGOUT';
export const LOGOUT_START = '@auth/LOGOUT_START';
export const LOGOUT_ERROR = '@auth/LOGOUT_ERROR';
export const LOGOUT_SUCCESS = '@auth/LOGOUT_SUCCESS';
const requestLogin = () => ({ type: LOGIN_REQUEST });
const loginSuccess = (user, token) =>
({
type: LOGIN_SUCCESS,
user,
token,
});
const loginFail = () => ({ type: LOGIN_FAILURE });
export const login = () =>
(dispatch) => {
dispatch(requestLogin());
steemConnect.me((err, result) => {
if (err || !result || !result.user) {
dispatch(loginFail());
return;
}
dispatch(getFollowing(result.user));
const accessToken = Cookie.get('access_token');
dispatch(loginSuccess(result.account, accessToken));
// init pushpad
initPushpad(result.user, accessToken);
});
};
|
import Promise from 'bluebird';
import steemConnect from 'sc2-sdk';
import Cookie from 'js-cookie';
import request from 'superagent';
import { getFollowing } from '../user/userActions';
import { initPushpad } from './pushpadHelper';
Promise.promisifyAll(steemConnect);
Promise.promisifyAll(request.Request.prototype);
export const LOGIN = '@auth/LOGIN';
export const LOGIN_REQUEST = '@auth/LOGIN_START';
export const LOGIN_SUCCESS = '@auth/LOGIN_SUCCESS';
export const LOGIN_FAILURE = '@auth/LOGIN_ERROR';
export const LOGOUT = '@auth/LOGOUT';
export const LOGOUT_START = '@auth/LOGOUT_START';
export const LOGOUT_ERROR = '@auth/LOGOUT_ERROR';
export const LOGOUT_SUCCESS = '@auth/LOGOUT_SUCCESS';
const requestLogin = () => ({ type: LOGIN_REQUEST });
const loginSuccess = (user, token) =>
({
type: LOGIN_SUCCESS,
user,
token,
});
const loginFail = () => ({ type: LOGIN_FAILURE });
export const login = () =>
(dispatch) => {
dispatch(requestLogin());
steemConnect.me((err, result) => {
if (err || !result || !result.name) {
dispatch(loginFail());
return;
}
dispatch(getFollowing(result.name));
const accessToken = Cookie.get('access_token');
dispatch(loginSuccess(result, accessToken));
// init pushpad
initPushpad(result.name, accessToken);
});
};
|
Add disableDraggingForSnapshotTest to CreateGroups to workaround react-beautiful-dnd / snapshot renderer mismatch
|
import PropTypes from 'prop-types';
import React from 'react';
// A visual UI element for horizontal dots indicating "more"
// See https://material.io/icons/#ic_more_horiz
function MoreDots({color = '#ccc'}) {
return (
<svg className="MoreDots" fill={color} height="18" viewBox="0 0 24 24" width="18" xmlns="http://www.w3.org/2000/svg">
<path d="M0 0h24v24H0z" fill="none"/>
<path d="M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/>
</svg>
);
}
MoreDots.propTypes = {
color: PropTypes.string
};
export default MoreDots;
|
import PropTypes from 'prop-types';
import React from 'react';
// A visual UI element for horizontal dots indicating "more"
// See https://material.io/icons/#ic_more_horiz
function MoreDots({color = '#ccc'}) {
return (
<svg fill={color} height="18" viewBox="0 0 24 24" width="18" xmlns="http://www.w3.org/2000/svg">
<path d="M0 0h24v24H0z" fill="none"/>
<path d="M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/>
</svg>
);
}
MoreDots.propTypes = {
color: PropTypes.string
};
export default MoreDots;
|
Fix Chrome exiting when running `ember-test`
|
module.exports = {
test_page: 'tests/index.html?hidepassed',
disable_watching: true,
launch_in_ci: [
'Chrome'
],
launch_in_dev: [
'Chrome'
],
browser_args: {
Chrome: {
ci: [
// --no-sandbox is needed when running Chrome inside a container
process.env.CI ? '--no-sandbox' : null,
'--headless',
// '--disable-gpu', https://github.com/testem/testem/issues/1117
'--disable-dev-shm-usage',
'--disable-software-rasterizer',
'--mute-audio',
'--remote-debugging-port=0',
'--window-size=1440,900'
].filter(Boolean)
}
}
};
|
module.exports = {
test_page: 'tests/index.html?hidepassed',
disable_watching: true,
launch_in_ci: [
'Chrome'
],
launch_in_dev: [
'Chrome'
],
browser_args: {
Chrome: {
ci: [
// --no-sandbox is needed when running Chrome inside a container
process.env.CI ? '--no-sandbox' : null,
'--headless',
'--disable-gpu',
'--disable-dev-shm-usage',
'--disable-software-rasterizer',
'--mute-audio',
'--remote-debugging-port=0',
'--window-size=1440,900'
].filter(Boolean)
}
}
};
|
Add foursquare/swarm token and new cron job setting
|
module.exports = {
authToken: process.env.AUTH_TOKEN || 'secret',
env: process.env.NODE_ENV,
flickr: {
key: process.env.FLICKR_KEY || '123abc',
secret: process.env.FLICKR_SECRET || 'secret',
userId: process.env.FLICKR_USER_ID || 'user'
},
host: process.env.HOST || 'localhost',
github: {
apiUrl: 'https://api.github.com',
username: process.env.GITHUB_USERNAME || 'username',
accessToken: process.env.GITHUB_ACCESS_TOKEN || '123abc'
},
google: {
apiKey: process.env.GOOGLE_API_KEY || '123abc',
nearbySearchApiUrl: 'https://maps.googleapis.com/maps/api/place/nearbysearch/json'
},
foursquare: {
token: process.env.FOURSQUARE_TOKEN || 'token'
},
jobs: {
frequency: {
githubActivity: process.env.JOBS_FREQUENCY_GITHUB || '00 */1 * * * *',
swarmPlaces: process.env.JOBS_FREQUENCY_SWARM || '00 */1 * * * *',
updateCache: process.env.JOBS_FREQUENCY_CACHE || '00 */1 * * * *'
}
},
mongo: {
url: process.env.MONGO_URL || 'mongodb://localhost:27017/FranVarney'
},
port: process.env.PORT || 8000
}
|
module.exports = {
authToken: process.env.AUTH_TOKEN || 'secret',
env: process.env.NODE_ENV,
flickr: {
key: process.env.FLICKR_KEY || '123abc',
secret: process.env.FLICKR_SECRET || 'secret',
userId: process.env.FLICKR_USER_ID || 'user'
},
host: process.env.HOST || 'localhost',
github: {
apiUrl: 'https://api.github.com',
username: process.env.GITHUB_USERNAME || 'username',
accessToken: process.env.GITHUB_ACCESS_TOKEN || '123abc'
},
google: {
apiKey: process.env.GOOGLE_API_KEY || '123abc',
nearbySearchApiUrl: 'https://maps.googleapis.com/maps/api/place/nearbysearch/json'
},
jobs: {
frequency: {
githubActivity: process.env.JOBS_FREQUENCY_GITHUB || '00 */1 * * * *',
updateCache: process.env.JOBS_FREQUENCY_CACHE || '00 */1 * * * *'
}
},
mongo: {
url: process.env.MONGO_URL || 'mongodb://localhost:27017/FranVarney'
},
port: process.env.PORT || 8000
}
|
Refactor for using the new Response class
|
<?php
namespace PhpWatson\Sdk\Tests\Language\RetrieveAndRank;
use PhpWatson\Sdk\Tests\AbstractTestCase;
use PhpWatson\Sdk\Language\RetrieveAndRank\V1\RetrieveAndRankService;
class RetrieveAndRankV1Test extends AbstractTestCase
{
/**
* @var RetrieveAndRankService
*/
public $service;
public function setUp()
{
parent::setUp();
$this->service = new RetrieveAndRankService();
}
public function test_if_url_is_set()
{
$this->assertEquals(
'https://watson-api-explorer.mybluemix.net/retrieve-and-rank/api',
$this->service->getUrl()
);
}
public function test_if_version_is_set()
{
$this->assertEquals(
'v1',
$this->service->getVersion()
);
}
public function test_can_list_solr_clusters()
{
$response = $this->service->listSolrClusters();
$this->assertArrayHasKey('clusters', json_decode($response->getContent(), true));
}
}
|
<?php
namespace PhpWatson\Sdk\Tests\Language\RetrieveAndRank;
use PhpWatson\Sdk\Tests\AbstractTestCase;
use PhpWatson\Sdk\Language\RetrieveAndRank\V1\RetrieveAndRankService;
class RetrieveAndRankV1Test extends AbstractTestCase
{
/**
* @var RetrieveAndRankService
*/
public $service;
public function setUp()
{
parent::setUp();
$this->service = new RetrieveAndRankService();
}
public function test_if_url_is_set()
{
$this->assertEquals(
'https://watson-api-explorer.mybluemix.net/retrieve-and-rank/api',
$this->service->getUrl()
);
}
public function test_if_version_is_set()
{
$this->assertEquals(
'v1',
$this->service->getVersion()
);
}
public function test_can_list_solr_clusters()
{
$response = $this->service->listSolrClusters();
$this->assertArrayHasKey('clusters', json_decode($response->getBody()->getContents(), true));
}
}
|
Fix patterns for Django > 1.10
Pike requires Django 1.11 so fix the template pattern import which was
not compatible with that version. This fixes:
File
"/srv/www/openstack-dashboard/openstack_dashboard/dashboards/help/guides/\
urls.py", line 15, in <module>
from django.conf.urls import patterns, url
ImportError: cannot import name patterns
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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 django.conf.urls import url
from django.contrib.auth.decorators import login_required
from .views import GuidesView
urlpatterns = [
url(r'^$', login_required(GuidesView.as_view()), name='index'),
]
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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 django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required
from .views import GuidesView
urlpatterns = patterns('',
url(r'^$', login_required(GuidesView.as_view()), name='index'))
|
Use the TTF version of the font in Java.
Windows (XP anyway) seems not to support OpenType fonts. Yay!
|
/**
* Copyright 2010 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.showcase.java;
import playn.core.PlayN;
import playn.java.JavaPlatform;
import playn.showcase.core.Showcase;
public class ShowcaseJava {
public static void main(String[] args) {
JavaPlatform platform = JavaPlatform.register();
platform.assets().setPathPrefix("playn/showcase/resources");
platform.graphics().registerFont("Museo-300", "text/Museo.ttf");
PlayN.run(new Showcase());
}
}
|
/**
* Copyright 2010 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.showcase.java;
import playn.core.PlayN;
import playn.java.JavaPlatform;
import playn.showcase.core.Showcase;
public class ShowcaseJava {
public static void main(String[] args) {
JavaPlatform platform = JavaPlatform.register();
platform.assets().setPathPrefix("playn/showcase/resources");
platform.graphics().registerFont("Museo-300", "text/Museo.otf");
PlayN.run(new Showcase());
}
}
|
Add enabled() static function to check if site is enabled
Signed-off-by: Kirtan Gajjar <dda7ffca0822762c3fa90dba716be1cac57d994e@gmail.com>
|
<?php
namespace EE\Model;
use EE;
/**
* Site model class.
*/
class Site extends Base {
/**
* @var string Table of the model from where it will be stored/retrived
*/
protected static $table = 'sites';
/**
* @var string Primary/Unique key of the table
*/
protected static $primary_key = 'site_url';
/**
* Saves current model into database
*
* @throws \Exception
*
* @return bool Model saved successfully
*/
public function save() {
$fields = array_merge( $this->fields, [
'modified_on' => date( 'Y-m-d H:i:s' ),
] );
$primary_key_column = static::$primary_key;
return EE::db()
->table( static::$table )
->where( $primary_key_column, $this->$primary_key_column )
->update( $fields );
}
/**
* Returns if site is enabled
*
* @param string $site_url Name of site to check
*
* @throws \Exception
*
* @return bool Site enabled
*/
public static function enabled( string $site_url ) : bool {
$site = static::find( $site_url, [ 'site_enabled' ] );
if ( $site && $site->site_enabled ) {
return true;
}
return false;
}
}
|
<?php
namespace EE\Model;
use EE;
/**
* Site model class.
*/
class Site extends Base {
/**
* @var string Table of the model from where it will be stored/retrived
*/
protected static $table = 'sites';
/**
* @var string Primary/Unique key of the table
*/
protected static $primary_key = 'site_url';
/**
* Saves current model into database
*
* @throws \Exception
*
* @return bool Model saved successfully
*/
public function save() {
$fields = array_merge( $this->fields, [
'modified_on' => date( 'Y-m-d H:i:s' ),
] );
$primary_key_column = static::$primary_key;
return EE::db()
->table( static::$table )
->where( $primary_key_column, $this->$primary_key_column )
->update( $fields );
}
}
|
Add default test db name to travis local.py
|
# -*- coding: utf-8 -*-
'''Example settings/local.py file.
These settings override what's in website/settings/defaults.py
NOTE: local.py will not be added to source control.
'''
from . import defaults
DB_PORT = 27017
DEV_MODE = True
DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc.
SEARCH_ENGINE = 'elastic'
USE_EMAIL = False
USE_CELERY = False
USE_GNUPG = False
# Email
MAIL_SERVER = 'localhost:1025' # For local testing
MAIL_USERNAME = 'osf-smtp'
MAIL_PASSWORD = 'CHANGEME'
# Session
COOKIE_NAME = 'osf'
SECRET_KEY = "CHANGEME"
##### Celery #####
## Default RabbitMQ broker
BROKER_URL = 'amqp://'
# Default RabbitMQ backend
CELERY_RESULT_BACKEND = 'amqp://'
USE_CDN_FOR_CLIENT_LIBS = False
SENTRY_DSN = None
TEST_DB_NAME = DB_NAME = 'osf_test'
|
# -*- coding: utf-8 -*-
'''Example settings/local.py file.
These settings override what's in website/settings/defaults.py
NOTE: local.py will not be added to source control.
'''
from . import defaults
DB_PORT = 27017
DEV_MODE = True
DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc.
SEARCH_ENGINE = 'elastic'
USE_EMAIL = False
USE_CELERY = False
USE_GNUPG = False
# Email
MAIL_SERVER = 'localhost:1025' # For local testing
MAIL_USERNAME = 'osf-smtp'
MAIL_PASSWORD = 'CHANGEME'
# Session
COOKIE_NAME = 'osf'
SECRET_KEY = "CHANGEME"
##### Celery #####
## Default RabbitMQ broker
BROKER_URL = 'amqp://'
# Default RabbitMQ backend
CELERY_RESULT_BACKEND = 'amqp://'
USE_CDN_FOR_CLIENT_LIBS = False
SENTRY_DSN = None
|
Fix positionFromTop when scrolling window after window resize
|
/**
* Gets the height of the element, accounting for API differences between
* `window` and other DOM elements.
*/
export function getHeight (element) {
return element === window
? window.innerHeight
: element.getBoundingClientRect().height
}
/**
* Gets the vertical position of an element within its scroll container.
* Elements that have been “scrolled past” return negative values.
* Handles edge-case where a user is navigating back (history) from an already-scrolled page.
* In this case the body’s top position will be a negative number and this element’s top will be increased (by that amount).
*/
export function getPositionFromTop (element, container) {
const offset = container === window ? 0 : getScrollTop(container)
const containerElement = container === window
? document.documentElement
: container
return (
element.getBoundingClientRect().top +
offset -
containerElement.getBoundingClientRect().top
)
}
/**
* Gets the vertical scroll amount of the element, accounting for IE compatibility
* and API differences between `window` and other DOM elements.
*/
export function getScrollTop (element) {
if (element === window) {
return ('scrollY' in window)
? window.scrollY
: document.documentElement.scrollTop
} else {
return element.scrollTop
}
}
|
/**
* Gets the height of the element, accounting for API differences between
* `window` and other DOM elements.
*/
export function getHeight (element) {
return element === window
? window.innerHeight
: element.getBoundingClientRect().height
}
/**
* Gets the vertical position of an element within its scroll container.
* Elements that have been “scrolled past” return negative values.
* Handles edge-case where a user is navigating back (history) from an already-scrolled page.
* In this case the body’s top position will be a negative number and this element’s top will be increased (by that amount).
*/
export function getPositionFromTop (element, container) {
const containerElement = container === window
? document.documentElement
: container
return (
element.getBoundingClientRect().top +
getScrollTop(container) -
containerElement.getBoundingClientRect().top
)
}
/**
* Gets the vertical scroll amount of the element, accounting for IE compatibility
* and API differences between `window` and other DOM elements.
*/
export function getScrollTop (element) {
if (element === window) {
return ('scrollY' in window)
? window.scrollY
: document.documentElement.scrollTop
} else {
return element.scrollTop
}
}
|
Edit path and external evaluation
|
from pygraphc.misc.IPLoM import *
from pygraphc.evaluation.ExternalEvaluation import *
# set input path
dataset_path = '/home/hudan/Git/labeled-authlog/dataset/Hofstede2014/dataset1_perday/'
groundtruth_file = dataset_path + 'Dec 1.log.labeled'
analyzed_file = 'Dec 1.log'
OutputPath = '/home/hudan/Git/pygraphc/result/misc/'
prediction_file = OutputPath + 'Dec 1.log.perline'
para = Para(path=dataset_path, logname=analyzed_file, save_path=OutputPath)
# call IPLoM and get clusters
myparser = IPLoM(para)
time = myparser.main_process()
clusters = myparser.get_clusters()
original_logs = myparser.logs
# set cluster label to get evaluation metrics
ExternalEvaluation.set_cluster_label_id(None, clusters, original_logs, prediction_file)
# get evaluation of clustering performance
ar = ExternalEvaluation.get_adjusted_rand(groundtruth_file, prediction_file)
ami = ExternalEvaluation.get_adjusted_mutual_info(groundtruth_file, prediction_file)
nmi = ExternalEvaluation.get_normalized_mutual_info(groundtruth_file, prediction_file)
h = ExternalEvaluation.get_homogeneity(groundtruth_file, prediction_file)
c = ExternalEvaluation.get_completeness(groundtruth_file, prediction_file)
v = ExternalEvaluation.get_vmeasure(groundtruth_file, prediction_file)
# print evaluation result
print ar, ami, nmi, h, c, v
print ('The running time of IPLoM is', time)
|
from pygraphc.misc.IPLoM import *
from pygraphc.evaluation.ExternalEvaluation import *
# set input path
ip_address = '161.166.232.17'
standard_path = '/home/hudan/Git/labeled-authlog/dataset/Hofstede2014/dataset1/' + ip_address
standard_file = standard_path + 'auth.log.anon.labeled'
analyzed_file = 'auth.log.anon'
prediction_file = 'iplom-result-' + ip_address + '.txt'
OutputPath = './result'
para = Para(path=standard_path, logname=analyzed_file, save_path=OutputPath)
# call IPLoM and get clusters
myparser = IPLoM(para)
time = myparser.main_process()
clusters = myparser.get_clusters()
original_logs = myparser.logs
# set cluster label to get evaluation metrics
ExternalEvaluation.set_cluster_label_id(None, clusters, original_logs, prediction_file)
homogeneity_completeness_vmeasure = ExternalEvaluation.get_homogeneity_completeness_vmeasure(standard_file,
prediction_file)
# print evaluation result
print homogeneity_completeness_vmeasure
print ('The running time of IPLoM is', time)
|
Allow normal traces in dev
|
<?php
namespace Outlandish\Wpackagist\EventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExceptionListener
{
public function onKernelException(ExceptionEvent $event)
{
// Let Symfony's default error tracing happen in dev.
if (getenv('APP_ENV') === 'dev') {
return;
}
$message = 'Something went wrong.';
$exception = $event->getThrowable();
$response = new Response();
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
if ($exception->getStatusCode() === 404) {
$message = 'The requested page could not be found.';
}
} else {
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}
$response->setContent($message);
$event->setResponse($response);
}
}
|
<?php
namespace Outlandish\Wpackagist\EventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExceptionListener
{
public function onKernelException(ExceptionEvent $event)
{
$message = 'Something went wrong.';
$exception = $event->getThrowable();
$response = new Response();
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
if ($exception->getStatusCode() === 404) {
$message = 'The requested page could not be found.';
}
} else {
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}
$response->setContent($message);
$event->setResponse($response);
}
}
|
Fix drawer width double / int issues
|
package com.reactnativenavigation.params.parsers;
import android.os.Bundle;
import android.support.annotation.Nullable;
import com.reactnativenavigation.params.NavigationParams;
import com.reactnativenavigation.params.SideMenuParams;
import com.reactnativenavigation.views.SideMenu.Side;
class SideMenuParamsParser extends Parser {
public static SideMenuParams[] parse(Bundle sideMenues) {
SideMenuParams[] result = new SideMenuParams[2];
result[Side.Left.ordinal()] = parseSideMenu(sideMenues.getBundle("left"), Side.Left);
result[Side.Right.ordinal()] = parseSideMenu(sideMenues.getBundle("right"), Side.Right);
return result;
}
private static SideMenuParams parseSideMenu(@Nullable Bundle sideMenu, Side side) {
if (sideMenu == null || sideMenu.isEmpty()) {
return null;
}
SideMenuParams result = new SideMenuParams();
result.screenId = sideMenu.getString("screenId");
result.navigationParams = new NavigationParams(sideMenu.getBundle("navigationParams"));
result.disableOpenGesture = sideMenu.getBoolean("disableOpenGesture", false);
result.drawerWidth = (int)Math.ceil(sideMenu.getDouble("drawerWidth", sideMenu.getInt("drawerWidth", -1)));
result.side = side;
return result;
}
}
|
package com.reactnativenavigation.params.parsers;
import android.os.Bundle;
import android.support.annotation.Nullable;
import com.reactnativenavigation.params.NavigationParams;
import com.reactnativenavigation.params.SideMenuParams;
import com.reactnativenavigation.views.SideMenu.Side;
class SideMenuParamsParser extends Parser {
public static SideMenuParams[] parse(Bundle sideMenues) {
SideMenuParams[] result = new SideMenuParams[2];
result[Side.Left.ordinal()] = parseSideMenu(sideMenues.getBundle("left"), Side.Left);
result[Side.Right.ordinal()] = parseSideMenu(sideMenues.getBundle("right"), Side.Right);
return result;
}
private static SideMenuParams parseSideMenu(@Nullable Bundle sideMenu, Side side) {
if (sideMenu == null || sideMenu.isEmpty()) {
return null;
}
SideMenuParams result = new SideMenuParams();
result.screenId = sideMenu.getString("screenId");
result.navigationParams = new NavigationParams(sideMenu.getBundle("navigationParams"));
result.disableOpenGesture = sideMenu.getBoolean("disableOpenGesture", false);
result.drawerWidth = (int)Math.ceil(sideMenu.getDouble("drawerWidth", -1));
result.side = side;
return result;
}
}
|
Use react and react-dom as global packages (reduce plugins packages size)
|
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import store from './store'
import Search from './containers/Search'
import './css/global.css'
import { initializePlugins } from 'lib/rpc/functions'
import { on } from 'lib/rpc/events'
import { updateTerm } from './actions/search'
import config from '../lib/config'
require('fix-path')()
window.React = React
window.ReactDOM = ReactDOM
/**
* Change current theme
*
* @param {String} src Absolute path to new theme css file
*/
const changeTheme = (src) => {
document.getElementById('cerebro-theme').href = src
}
// Set theme from config
changeTheme(config.get('theme'))
// Render main container
ReactDOM.render(
<Provider store={store}>
<Search />
</Provider>,
document.getElementById('root')
)
// Initialize plugins
initializePlugins()
// Handle `showTerm` rpc event and replace search term with payload
on('showTerm', (term) => store.dispatch(updateTerm(term)))
on('update-downloaded', () => (
new Notification('Cerebro: update is ready to install', {
body: 'New version is downloaded and will be automatically installed on quit'
})
))
// Handle `updateTheme` rpc event and change current theme
on('updateTheme', changeTheme)
// Handle `reload` rpc event and reload window
on('reload', () => location.reload())
|
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import store from './store'
import Search from './containers/Search'
import './css/global.css'
import { initializePlugins } from 'lib/rpc/functions'
import { on } from 'lib/rpc/events'
import { updateTerm } from './actions/search'
import config from '../lib/config'
require('fix-path')()
/**
* Change current theme
*
* @param {String} src Absolute path to new theme css file
*/
const changeTheme = (src) => {
document.getElementById('cerebro-theme').href = src
}
// Set theme from config
changeTheme(config.get('theme'))
// Render main container
render(
<Provider store={store}>
<Search />
</Provider>,
document.getElementById('root')
)
// Initialize plugins
initializePlugins()
// Handle `showTerm` rpc event and replace search term with payload
on('showTerm', (term) => store.dispatch(updateTerm(term)))
on('update-downloaded', () => (
new Notification('Cerebro: update is ready to install', {
body: 'New version is downloaded and will be automatically installed on quit'
})
))
// Handle `updateTheme` rpc event and change current theme
on('updateTheme', changeTheme)
// Handle `reload` rpc event and reload window
on('reload', () => location.reload())
|
Change to JS event to click buttons
|
'use strict';
/**
* Class to fetch the feed list and draw the aside
*/
var Feeds = new Class({
feeds: [],
initialize: function () {
this.loadFeeds();
},
/** Load feeds from API and trigger the drawing function */
loadFeeds: function () {
new Request.JSON({
method: 'get',
url: window.ZerobRSS.apiUri + '/v1/feeds',
onComplete: function (response) {
window.ZerobRSS.Feeds.feeds = response;
window.ZerobRSS.Feeds.drawAside();
}
}).send();
},
drawAside: function () {
var template = Handlebars.compile($('feed-menu-template').get('html'));
this.feeds.each(function(feed) {
var a = new Element('a');
a.set('html', template(feed));
a.addEvent('click', (function () {
window.ZerobRSS.Router.nav('/feed/' + feed.id)
}));
a.inject($$('#aside-menu nav')[0]);
});
}
});
window.ZerobRSS.Feeds = new Feeds();
|
'use strict';
/**
* Class to fetch the feed list and draw the aside
*/
var Feeds = new Class({
feeds: [],
initialize: function () {
this.loadFeeds();
},
/** Load feeds from API and trigger the drawing function */
loadFeeds: function () {
new Request.JSON({
method: 'get',
url: window.ZerobRSS.apiUri + '/v1/feeds',
onComplete: function (response) {
window.ZerobRSS.Feeds.feeds = response;
window.ZerobRSS.Feeds.drawAside();
}
}).send();
},
drawAside: function () {
var template = Handlebars.compile($('feed-menu-template').get('html'));
this.feeds.each(function(feed) {
var a = new Element('a');
a.set('href', '#!/feeds/' + feed.id);
a.set('html', template(feed));
a.inject($$('#aside-menu nav')[0]);
});
}
});
window.ZerobRSS.Feeds = new Feeds();
|
Remove bug that was generating invalid XML
|
'use strict';
var fs = require('fs');
function reset() {
exports.out = [];
exports.xmlEmitter = null;
exports.opts = {};
} reset();
/**
* Load a formatter
* @param {String} formatterPath
* @return
*/
function loadFormatter(formatterPath) {
return require('./lib/' + formatterPath + '_emitter');
}
/**
* Write out a XML file for the encountered results
* @param {Array} results
* @param {Array} data
* @param {Object} opts
*/
exports.reporter = function (results) {
exports.out.push(results);
};
exports.writeFile = function (opts) {
opts = opts || {};
opts.filePath = opts.filePath || 'jshint.xml';
opts.format = opts.format || 'checkstyle';
exports.xmlEmitter = loadFormatter(opts.format);
return function () {
if (!exports.out.length) {
reset();
return;
}
var outStream = fs.createWriteStream(opts.filePath);
outStream.write(exports.xmlEmitter.getHeader());
exports.out.forEach(function (item) {
outStream.write(exports.xmlEmitter.formatContent(item));
});
outStream.write(exports.xmlEmitter.getFooter());
reset();
};
};
|
'use strict';
var fs = require('fs');
function reset() {
exports.out = [];
exports.xmlEmitter = null;
exports.opts = {};
} reset();
/**
* Load a formatter
* @param {String} formatterPath
* @return
*/
function loadFormatter(formatterPath) {
return require('./lib/' + formatterPath + '_emitter');
}
/**
* Write out a XML file for the encountered results
* @param {Array} results
* @param {Array} data
* @param {Object} opts
*/
exports.reporter = function (results) {
exports.out.push(results);
};
exports.writeFile = function (opts) {
opts = opts || {};
opts.filePath = opts.filePath || 'jshint.xml';
opts.format = opts.format || 'checkstyle';
exports.xmlEmitter = loadFormatter(opts.format);
return function () {
if (!exports.out.length) {
reset();
return;
}
var outStream = fs.createWriteStream(opts.filePath);
outStream.write(exports.xmlEmitter.getHeader());
exports.out.forEach(function (item) {
outStream.write(exports.xmlEmitter.formatContent(item));
});
outStream.write(exports.out.join('\n'));
outStream.write(exports.xmlEmitter.getFooter());
reset();
};
};
|
Improve log message when no CSRF token found
Closes gh-10436
|
/*
* Copyright 2002-2021 the original author or 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.
*/
package org.springframework.security.web.csrf;
/**
* Thrown when no expected {@link CsrfToken} is found but is required.
*
* @author Rob Winch
* @since 3.2
*/
@SuppressWarnings("serial")
public class MissingCsrfTokenException extends CsrfException {
public MissingCsrfTokenException(String actualToken) {
super("Could not verify the provided CSRF token because no token was found to compare.");
}
}
|
/*
* Copyright 2002-2013 the original author or 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.
*/
package org.springframework.security.web.csrf;
/**
* Thrown when no expected {@link CsrfToken} is found but is required.
*
* @author Rob Winch
* @since 3.2
*/
@SuppressWarnings("serial")
public class MissingCsrfTokenException extends CsrfException {
public MissingCsrfTokenException(String actualToken) {
super("Could not verify the provided CSRF token because your session was not found.");
}
}
|
Add auth details if session_id is not provided in the request
|
<?php
namespace Jwpage\Clickatell;
use Guzzle\Common\Collection;
use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;
class ClickatellClient extends Client
{
public static function factory($config = array())
{
$default = array(
'base_url' => 'http://api.clickatell.com/',
);
$required = array('api_id', 'user', 'password', 'base_url');
$config = Collection::fromConfig($config, $default, $required);
$description = ServiceDescription::factory(__DIR__.'/service.json');
$client = new self($config->get('base_url'), $config);
$client->setDescription($description);
return $client;
}
public function createRequest($method = RequestInterface::GET, $uri = null, $headers = null, $body = null)
{
$request = parent::createRequest($method, $uri, $headers, $body);
if (!$request->getPostField("session_id")) {
$config = $this->getConfig();
$request->addPostFields($config->getAll(array('api_id', 'user', 'password')));
}
return $request;
}
}
|
<?php
namespace Jwpage\Clickatell;
use Guzzle\Common\Collection;
use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;
class ClickatellClient extends Client
{
public static function factory($config = array())
{
$default = array(
'base_url' => 'http://api.clickatell.com/',
);
$required = array('api_id', 'username', 'password', 'base_url');
$config = Collection::fromConfig($config, $default, $required);
$description = ServiceDescription::factory(__DIR__.'/service.json');
$client = new self($config->get('base_url'), $config);
$client->setDescription($description);
return $client;
}
}
|
Fix task_api_get_results failing if task had no results, while this is actually fine.
|
package org.metaborg.runtime.task.primitives;
import static org.metaborg.runtime.task.util.ListBuilder.makeList;
import org.metaborg.runtime.task.Task;
import org.metaborg.runtime.task.TaskEngine;
import org.metaborg.runtime.task.TaskManager;
import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.core.InterpreterException;
import org.spoofax.interpreter.library.AbstractPrimitive;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;
public class task_api_get_results_0_1 extends AbstractPrimitive {
public static task_api_get_results_0_1 instance = new task_api_get_results_0_1();
public task_api_get_results_0_1() {
super("task_api_get_results", 0, 1);
}
@Override
public boolean call(IContext env, Strategy[] svars, IStrategoTerm[] tvars) throws InterpreterException {
final TaskEngine taskEngine = TaskManager.getInstance().getCurrent();
final IStrategoTerm taskID = tvars[0];
final Task task = taskEngine.getTask(taskID);
if(!task.solved())
return false;
env.setCurrent(makeList(env.getFactory(), task.results()));
return true;
}
}
|
package org.metaborg.runtime.task.primitives;
import static org.metaborg.runtime.task.util.ListBuilder.makeList;
import org.metaborg.runtime.task.Task;
import org.metaborg.runtime.task.TaskEngine;
import org.metaborg.runtime.task.TaskManager;
import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.core.InterpreterException;
import org.spoofax.interpreter.library.AbstractPrimitive;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;
public class task_api_get_results_0_1 extends AbstractPrimitive {
public static task_api_get_results_0_1 instance = new task_api_get_results_0_1();
public task_api_get_results_0_1() {
super("task_api_get_results", 0, 1);
}
@Override
public boolean call(IContext env, Strategy[] svars, IStrategoTerm[] tvars) throws InterpreterException {
final TaskEngine taskEngine = TaskManager.getInstance().getCurrent();
final IStrategoTerm taskID = tvars[0];
final Task task = taskEngine.getTask(taskID);
if(!task.hasResults())
return false;
env.setCurrent(makeList(env.getFactory(), task.results()));
return true;
}
}
|
Add maxHttpConnections for Influxdb 0.9.0 code path
Change-Id: Ief4759610c3b8570ed58170265e069458d731540
|
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
public class InfluxDbConfiguration {
@JsonProperty
String version;
public String getVersion() {
return version;
}
/**
* Used only for Influxdb V9.
*/
@JsonProperty
int maxHttpConnections;
public int getMaxHttpConnections() {
return maxHttpConnections;
}
@JsonProperty
String name;
public String getName() {
return name;
}
@JsonProperty
int replicationFactor;
public int getReplicationFactor() {
return replicationFactor;
}
@JsonProperty
String url;
public String getUrl() {
return url;
}
@JsonProperty
String user;
public String getUser() {
return user;
}
@JsonProperty
String password;
public String getPassword() {
return password;
}
@JsonProperty
String retentionPolicy;
public String getRetentionPolicy() {
return retentionPolicy;
}
}
|
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
public class InfluxDbConfiguration {
@JsonProperty
String version;
public String getVersion() {
return version;
}
@JsonProperty
String name;
public String getName() {
return name;
}
@JsonProperty
int replicationFactor;
public int getReplicationFactor() {
return replicationFactor;
}
@JsonProperty
String url;
public String getUrl() {
return url;
}
@JsonProperty
String user;
public String getUser() {
return user;
}
@JsonProperty
String password;
public String getPassword() {
return password;
}
@JsonProperty
String retentionPolicy;
public String getRetentionPolicy() {
return retentionPolicy;
}
}
|
Revert "Simplify the use of `phutil_get_library_root`"
Summary:
This reverts commit 67a17d0efb025665237d0d174d55d1887f9a6064.
This doesn't actually work because the call to `phutil_get_current_library_name()` always occurs within `libphutil`.
Test Plan: N/A
Reviewers: epriestley, #blessed_reviewers
Reviewed By: epriestley, #blessed_reviewers
Subscribers: Korvin, epriestley
Differential Revision: https://secure.phabricator.com/D13187
|
<?php
function phutil_get_library_root($library) {
$bootloader = PhutilBootloader::getInstance();
return $bootloader->getLibraryRoot($library);
}
function phutil_get_library_root_for_path($path) {
foreach (Filesystem::walkToRoot($path) as $dir) {
if (Filesystem::pathExists($dir.'/__phutil_library_init__.php')) {
return $dir;
}
}
return null;
}
function phutil_get_library_name_for_root($path) {
$path = rtrim(Filesystem::resolvePath($path), '/');
$bootloader = PhutilBootloader::getInstance();
$libraries = $bootloader->getAllLibraries();
foreach ($libraries as $library) {
$root = $bootloader->getLibraryRoot($library);
if (rtrim(Filesystem::resolvePath($root), '/') == $path) {
return $library;
}
}
return null;
}
function phutil_get_current_library_name() {
$caller = head(debug_backtrace(false));
$root = phutil_get_library_root_for_path($caller['file']);
return phutil_get_library_name_for_root($root);
}
/**
* Warns about use of deprecated behavior.
*/
function phutil_deprecated($what, $why) {
PhutilErrorHandler::dispatchErrorMessage(
PhutilErrorHandler::DEPRECATED,
$what,
array(
'why' => $why,
));
}
|
<?php
function phutil_get_library_root($library = null) {
if (!$library) {
$library = phutil_get_current_library_name();
}
$bootloader = PhutilBootloader::getInstance();
return $bootloader->getLibraryRoot($library);
}
function phutil_get_library_root_for_path($path) {
foreach (Filesystem::walkToRoot($path) as $dir) {
if (Filesystem::pathExists($dir.'/__phutil_library_init__.php')) {
return $dir;
}
}
return null;
}
function phutil_get_library_name_for_root($path) {
$path = rtrim(Filesystem::resolvePath($path), '/');
$bootloader = PhutilBootloader::getInstance();
$libraries = $bootloader->getAllLibraries();
foreach ($libraries as $library) {
$root = $bootloader->getLibraryRoot($library);
if (rtrim(Filesystem::resolvePath($root), '/') == $path) {
return $library;
}
}
return null;
}
function phutil_get_current_library_name() {
$caller = head(debug_backtrace(false));
$root = phutil_get_library_root_for_path($caller['file']);
return phutil_get_library_name_for_root($root);
}
/**
* Warns about use of deprecated behavior.
*/
function phutil_deprecated($what, $why) {
PhutilErrorHandler::dispatchErrorMessage(
PhutilErrorHandler::DEPRECATED,
$what,
array(
'why' => $why,
));
}
|
Test against jQuery slim 3.x
|
QUnit.config.urlConfig.push({
id: "jquery",
label: "jQuery version",
value: ["3.2.1", "3.2.1.slim", "3.1.1", "3.1.1.slim", "3.0.0", "3.0.0.slim", "2.2.4", "2.1.4", "2.0.3", "1.12.4", "1.11.3"],
tooltip: "What jQuery Core version to test against"
});
/* Hijacks normal form submit; lets it submit to an iframe to prevent
* navigating away from the test suite
*/
$(document).on('submit', function(e) {
if (!e.isDefaultPrevented()) {
var form = $(e.target), action = form.attr('action'),
name = 'form-frame' + jQuery.guid++,
iframe = $('<iframe name="' + name + '" />');
if (action && action.indexOf('iframe') < 0) form.attr('action', action + '?iframe=true')
form.attr('target', name);
$('#qunit-fixture').append(iframe);
form.trigger('iframe:loading');
}
});
|
QUnit.config.urlConfig.push({
id: "jquery",
label: "jQuery version",
value: ["3.2.1", "3.2.0", "3.1.1", "3.0.0", "2.2.4", "2.1.4", "2.0.3", "1.12.4", "1.11.3"],
tooltip: "What jQuery Core version to test against"
});
/* Hijacks normal form submit; lets it submit to an iframe to prevent
* navigating away from the test suite
*/
$(document).on('submit', function(e) {
if (!e.isDefaultPrevented()) {
var form = $(e.target), action = form.attr('action'),
name = 'form-frame' + jQuery.guid++,
iframe = $('<iframe name="' + name + '" />');
if (action && action.indexOf('iframe') < 0) form.attr('action', action + '?iframe=true')
form.attr('target', name);
$('#qunit-fixture').append(iframe);
form.trigger('iframe:loading');
}
});
|
Handle opening files directly from native OS
Relying on `open-file` event. Couldn't be any simpler.
You'll need a built copy of nteract to use this (with our new dist hooks).
|
import app from 'app';
import {
launchFilename,
launchNewNotebook,
} from './launch';
import { Menu } from 'electron';
import { defaultMenu, loadFullMenu } from './menu';
import { resolve } from 'path';
const program = require('commander');
const version = require('../../package.json').version;
program
.version(version)
.option('-k', '--kernel [kernel]', '')
.parse(process.argv);
const notebooks = program.args;
app.on('window-all-closed', () => {
// On OS X, we want to keep the app and menu bar active
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('open-file', (event, path) => {
event.preventDefault();
launchFilename(resolve(path));
});
app.on('ready', () => {
// Get the default menu first
Menu.setApplicationMenu(defaultMenu);
// Let the kernels/languages come in after
loadFullMenu().then(menu => Menu.setApplicationMenu(menu));
if (notebooks <= 0) {
launchNewNotebook('python3');
} else {
notebooks.filter(Boolean).forEach(f => launchFilename(resolve(f)));
}
});
|
import app from 'app';
import {
launchFilename,
launchNewNotebook,
} from './launch';
import { Menu } from 'electron';
import { defaultMenu, loadFullMenu } from './menu';
import { resolve } from 'path';
const program = require('commander');
const version = require('../../package.json').version;
program
.version(version)
.option('-k', '--kernel [kernel]', '')
.parse(process.argv);
const notebooks = program.args;
app.on('window-all-closed', () => {
// On OS X, we want to keep the app and menu bar active
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('ready', () => {
// Get the default menu first
Menu.setApplicationMenu(defaultMenu);
// Let the kernels/languages come in after
loadFullMenu().then(menu => Menu.setApplicationMenu(menu));
if (notebooks <= 0) {
launchNewNotebook('python3');
} else {
notebooks.filter(Boolean).forEach(f => launchFilename(resolve(f)));
}
});
|
Update tests to mock generic helper function
|
jest.mock('../../../models/meeting');
const { toggleRegistration } = require('../meeting');
const { getActiveGenfors, updateGenfors } = require('../../../models/meeting');
const { generateSocket, generateGenfors } = require('../../../utils/generateTestData');
describe('toggleRegistration', () => {
beforeEach(() => {
getActiveGenfors.mockImplementation(async () => generateGenfors());
updateGenfors.mockImplementation(async (genfors, data) =>
({ ...genfors, ...data, pin: genfors.pin }));
});
const generateData = data => (Object.assign({
registrationOpen: true,
}, data));
it('emits a toggle action that closes registration', async () => {
const socket = generateSocket();
await toggleRegistration(socket, generateData());
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits a toggle action that opens registration', async () => {
const socket = generateSocket();
await toggleRegistration(socket, generateData({ registrationOpen: false }));
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
});
|
jest.mock('../../../models/meeting');
const { toggleRegistration } = require('../meeting');
const { getActiveGenfors, toggleRegistrationStatus } = require('../../../models/meeting');
const { generateSocket, generateGenfors } = require('../../../utils/generateTestData');
describe('toggleRegistration', () => {
beforeEach(() => {
getActiveGenfors.mockImplementation(async () => generateGenfors());
toggleRegistrationStatus.mockImplementation(
async (genfors, registrationOpen) =>
generateGenfors({ ...genfors, registrationOpen: !registrationOpen }));
});
const generateData = data => (Object.assign({
registrationOpen: true,
}, data));
it('emits a toggle action that closes registration', async () => {
const socket = generateSocket();
await toggleRegistration(socket, generateData());
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits a toggle action that opens registration', async () => {
const socket = generateSocket();
await toggleRegistration(socket, generateData({ registrationOpen: false }));
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
});
|
Improve naming of a variable
|
var Promise = require('es6-promise').Promise;
var engine = require('static-engine');
module.exports = function (name, plugins) {
return function (pages) {
var promises = pages.map(function (page) {
return new Promise(function(resolve, reject){
var current_pages = page[name] && Array.isArray(page[name]) ? page[name] : [];
var formula = [ plugins.slice(0) ];
formula[0].unshift(function(){
return Promise.resolve(current_pages);
});
engine(formula).then(function (pages) {
page[name] = pages[0];
resolve(page);
});
});
});
return Promise.all(promises).then(function(results){
var pages = [];
Array.prototype.push.apply(pages, results);
return Promise.resolve(pages);
});
};
};
|
var Promise = require('es6-promise').Promise;
var engine = require('static-engine');
module.exports = function (name, plugins) {
return function (pages) {
var promises = pages.map(function (page) {
return new Promise(function(resolve, reject){
var current_pages = page[name] && Array.isArray(page[name]) ? page[name] : [];
var _plugins = Array.prototype.slice.apply(plugins);
_plugins.unshift(function(){
return Promise.resolve(current_pages);
});
engine([_plugins]).then(function (pages) {
page[name] = pages[0];
resolve(page);
});
});
});
return Promise.all(promises).then(function(results){
var pages = [];
Array.prototype.push.apply(pages, results);
return Promise.resolve(pages);
});
};
};
|
Append fields before files in FormData of request
|
import registerListeners from './register-listeners';
export default ({ request, files, instance, progress }) =>
new Promise(resolve => {
const xhr = new XMLHttpRequest();
instance(xhr);
registerListeners({ xhr, resolve, progress });
xhr.open(request.method || 'POST', request.url);
xhr.withCredentials = request.withCredentials || false;
if (request.headers) {
Object.keys(request.headers).forEach(header =>
xhr.setRequestHeader(header, request.headers[header]));
}
//send just the file if no fields or filename is set
if (!request.fileName && !request.fields) return xhr.send(files[0]);
var formData = new FormData();
//append fields first, fixes https://github.com/expressjs/multer/issues/322
if (request.fields) {
Object.keys(request.fields).forEach(field =>
formData.append(field, request.fields[field]));
}
Array.from(files).forEach(file =>
formData.append(request.fileName || 'file', file));
xhr.send(formData);
});
|
import registerListeners from './register-listeners';
export default ({ request, files, instance, progress }) =>
new Promise(resolve => {
const xhr = new XMLHttpRequest();
instance(xhr);
registerListeners({ xhr, resolve, progress });
xhr.open(request.method || 'POST', request.url);
xhr.withCredentials = request.withCredentials || false;
if (request.headers) {
Object.keys(request.headers).forEach(header =>
xhr.setRequestHeader(header, request.headers[header]));
}
//send just the file if no fields or filename is set
if (!request.fileName && !request.fields) return xhr.send(files[0]);
var formData = new FormData();
Array.from(files).forEach(file =>
formData.append(request.fileName || 'file', file));
if (request.fields) {
Object.keys(request.fields).forEach(field =>
formData.append(field, request.fields[field]));
}
xhr.send(formData);
});
|
Fix issue with not being able to paint on max edge
|
import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import immutableToJs from 'utils/immutableToJs';
import { toPickTile } from 'state/actions/pickTile';
import { toPlaceTile } from 'state/actions/placeTile';
import grounds from 'state/models/grounds';
import Editor from 'components/Editor/Editor';
function mapStateToProps(state) {
const keypath = ['editor'];
return {
activeEntity: state.getIn([...keypath, 'activeEntity']),
activeGround: state.getIn([...keypath, 'activeGround']),
minCol: grounds.minCol(state),
maxCol: grounds.maxCol(state) + 1,
minRow: grounds.minRow(state),
maxRow: grounds.maxRow(state) + 1,
};
}
function mapDispatchToProps(dispatch) {
return {
onPickTile(tileType, shortType) {
dispatch(toPickTile(...arguments));
},
onPlaceTile(tileType, col, row) {
dispatch(toPlaceTile(...arguments));
}
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Editor);
|
import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import immutableToJs from 'utils/immutableToJs';
import { toPickTile } from 'state/actions/pickTile';
import { toPlaceTile } from 'state/actions/placeTile';
import grounds from 'state/models/grounds';
import Editor from 'components/Editor/Editor';
function mapStateToProps(state) {
const keypath = ['editor'];
return {
activeEntity: state.getIn([...keypath, 'activeEntity']),
activeGround: state.getIn([...keypath, 'activeGround']),
minCol: grounds.minCol(state),
maxCol: grounds.maxCol(state),
minRow: grounds.minRow(state),
maxRow: grounds.maxRow(state),
};
}
function mapDispatchToProps(dispatch) {
return {
onPickTile(tileType, shortType) {
dispatch(toPickTile(...arguments));
},
onPlaceTile(tileType, col, row) {
dispatch(toPlaceTile(...arguments));
}
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Editor);
|
Check new-style, not old-style permission names in settings
Should finally fix UIU-130.
|
import _ from 'lodash';
import React from 'react';
import Settings from '@folio/stripes-components/lib/Settings';
import PermissionSets from './permissions/PermissionSets';
import PatronGroupsSettings from './PatronGroupsSettings';
import AddressTypesSettings from './AddressTypesSettings';
const pages = [
{
route: 'perms',
label: 'Permission sets',
component: PermissionSets,
perm: 'ui-users.editpermsets',
},
{
route: 'groups',
label: 'Patron groups',
component: PatronGroupsSettings,
perm: 'ui-users.settings.usergroups',
},
{
route: 'addresstypes',
label: 'Address Types',
component: AddressTypesSettings,
perm: 'ui-users.settings.addresstypes',
},
];
export default props => <Settings {...props} pages={_.sortBy(pages, ['label'])} paneTitle="Users" />;
|
import _ from 'lodash';
import React from 'react';
import Settings from '@folio/stripes-components/lib/Settings';
import PermissionSets from './permissions/PermissionSets';
import PatronGroupsSettings from './PatronGroupsSettings';
import AddressTypesSettings from './AddressTypesSettings';
const pages = [
{
route: 'perms',
label: 'Permission sets',
component: PermissionSets,
perm: 'ui-users.editpermsets',
},
{
route: 'groups',
label: 'Patron groups',
component: PatronGroupsSettings,
perm: 'settings.usergroups.all',
},
{
route: 'addresstypes',
label: 'Address Types',
component: AddressTypesSettings,
perm: 'settings.addresstypes.all',
},
];
export default props => <Settings {...props} pages={_.sortBy(pages, ['label'])} paneTitle="Users" />;
|
Stop infinite scroll when calling init. Use 'this' if initializing inside a controller already
|
function InfiniteScroll (cursor) {
var self = this;
// observeChanges will fire for initial set, so count can start at 0
self.count = 0;
var cursor = cursor.observeChanges({
added: function () {
self.count++;
},
removed: function () {
self.count--;
}
});
this.stop = function () {
cursor.stop();
};
}
initInfiniteScroll = function (cursors) {
var self = this;
var cursors = _.isArray(cursors) ? cursors : [cursors];
var controller = this instanceof Iron.Controller ? this : getCurrentController();
var limit = this.state || controller.state;
var currentLimit;
stopInfiniteScroll.call(self);
self._infiniteScroll = [];
_.each(cursors, function (cursor) {
var obj = new InfiniteScroll(cursor);
self._infiniteScroll.push(obj);
});
$(window).on('scroll', _.throttle(function () {
// trigger at 20% above bottom
var target = document.body.offsetHeight * 0.8;
if (window.innerHeight + window.scrollY >= target) {
_.each(self._infiniteScroll, function (obj) {
currentLimit = limit.get('itemsLimit');
if (obj.count >= currentLimit) {
limit.set('itemsLimit', currentLimit + 30); //fetch more items from server
}
});
}
}, 300));
};
stopInfiniteScroll = function () {
$(window).off('scroll');
_.each(this._infiniteScroll, function (obj) {
obj.stop();
});
};
|
function InfiniteScroll (cursor) {
var self = this;
// observeChanges will fire for initial set, so count can start at 0
self.count = 0;
var cursor = cursor.observeChanges({
added: function () {
self.count++;
},
removed: function () {
self.count--;
}
});
this.stop = function () {
cursor.stop();
};
}
initInfiniteScroll = function (cursors) {
var self = this;
var cursors = _.isArray(cursors) ? cursors : [cursors];
var controller = getCurrentController();
var limit = this.state || controller.state;
var currentLimit;
self._infiniteScroll = self._infiniteScroll || [];
_.each(cursors, function (cursor) {
var obj = new InfiniteScroll(cursor);
self._infiniteScroll.push(obj);
});
$(window).on('scroll', _.throttle(function () {
// trigger at 20% above bottom
var target = document.body.offsetHeight * 0.8;
if (window.innerHeight + window.scrollY >= target) {
_.each(self._infiniteScroll, function (obj) {
currentLimit = limit.get('itemsLimit');
if (obj.count >= currentLimit) {
limit.set('itemsLimit', currentLimit + 30); //fetch more items from server
}
});
}
}, 300));
};
stopInfiniteScroll = function () {
$(window).off('scroll');
_.each(this._infiniteScroll, function (obj) {
obj.stop();
});
};
|
Update to import for for Django 1.9 compatibility.
|
import datetime
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.utils.functional import SimpleLazyObject
from django.utils.timezone import utc
from downtime.models import Period
from .models import Banner
def template_settings(request):
'''Template context processor: add selected setting to context
so it can be used on any page .'''
context_extras = {
'ENABLE_BETA_WARNING': getattr(settings, 'ENABLE_BETA_WARNING', False),
'EULTHEME_NO_EXTERNAL_JS': getattr(settings, 'EULTHEME_NO_EXTERNAL_JS', False)}
return context_extras
def site_path(request):
'''Template context processor: provides access to current
:class:`~django.contrib.sites.models.Site` and
the site root path for use in building absolute urls.
'''
site = SimpleLazyObject(lambda: get_current_site(request))
protocol = 'https' if request.is_secure() else 'http'
return {
'site': site,
'site_root': SimpleLazyObject(lambda: "%s://%s" % (protocol, site.domain))}
def downtime_context(request):
'''Template context processor: add relevant maintenance banner to site.'''
banner = Banner.objects.get_deployed().first()
context = {}
if banner:
context.update({'banner': banner})
site_is_down = Period.objects.is_down()
if site_is_down:
context.update({'site_is_down': site_is_down})
return context
|
import datetime
from django.conf import settings
from django.contrib.sites.models import get_current_site
from django.utils.functional import SimpleLazyObject
from django.utils.timezone import utc
from downtime.models import Period
from .models import Banner
def template_settings(request):
'''Template context processor: add selected setting to context
so it can be used on any page .'''
context_extras = {
'ENABLE_BETA_WARNING': getattr(settings, 'ENABLE_BETA_WARNING', False),
'EULTHEME_NO_EXTERNAL_JS': getattr(settings, 'EULTHEME_NO_EXTERNAL_JS', False)}
return context_extras
def site_path(request):
'''Template context processor: provides access to current
:class:`~django.contrib.sites.models.Site` and
the site root path for use in building absolute urls.
'''
site = SimpleLazyObject(lambda: get_current_site(request))
protocol = 'https' if request.is_secure() else 'http'
return {
'site': site,
'site_root': SimpleLazyObject(lambda: "%s://%s" % (protocol, site.domain))}
def downtime_context(request):
'''Template context processor: add relevant maintenance banner to site.'''
banner = Banner.objects.get_deployed().first()
context = {}
if banner:
context.update({'banner': banner})
site_is_down = Period.objects.is_down()
if site_is_down:
context.update({'site_is_down': site_is_down})
return context
|
Improve checkbox filter performance by checking key instead of iterating
|
export function filterByText(data, textFilter) {
if (textFilter === '') {
return data;
}
// case-insensitive
textFilter = textFilter.toLowerCase();
const exactMatches = [];
const substringMatches = [];
data.forEach(i => {
const name = i.name.toLowerCase();
if (name.split(' ').includes(textFilter)) {
exactMatches.push(i);
} else if (name.includes(textFilter)) {
substringMatches.push(i);
}
});
// return in order of importance in case sorting isn't done
return exactMatches.concat(substringMatches);
}
export function filterByCheckbox(data, checkboxFilters) {
let filtered = data;
Object.keys(checkboxFilters).forEach(i => {
if (Object.keys(checkboxFilters[i]).some(j => checkboxFilters[i][j])) {
filtered = filtered.filter(j => checkboxFilters[i][j.filterable[i]]);
}
});
return filtered;
}
|
export function filterByText(data, textFilter) {
if (textFilter === '') {
return data;
}
// case-insensitive
textFilter = textFilter.toLowerCase();
const exactMatches = [];
const substringMatches = [];
data.forEach(i => {
const name = i.name.toLowerCase();
if (name.split(' ').includes(textFilter)) {
exactMatches.push(i);
} else if (name.includes(textFilter)) {
substringMatches.push(i);
}
});
// return in order of importance in case sorting isn't done
return exactMatches.concat(substringMatches);
}
export function filterByCheckbox(data, checkboxFilters) {
let filtered = data;
Object.keys(checkboxFilters).forEach(i => {
const currentFilters = Object.keys(checkboxFilters[i]).filter(j => checkboxFilters[i][j]);
if (currentFilters.length) {
filtered = filtered.filter(j => currentFilters.includes(j.filterable[i]));
}
});
return filtered;
}
|
Use correct Backdrop options for user satisfaction.
Sort by "_timestamp: ascending" and provide a limit of 0. This gives
us all available data, and works against live Backdrop data on preview.
It would be better to sort by "_timestamp:descending" and use a limit
of 2, since at the moment we only require 2 data points. However, this
would require us to refactor delta.js to cope with data in a different
order, and we may soon add a sparkline for this view that uses all
available data in any case. So I think this is an acceptable fix.
|
define([
'extensions/controllers/module',
'common/views/visualisations/user-satisfaction',
'common/collections/list'
],
function (ModuleController, UserSatisfactionView, ListCollection) {
var UserSatisfactionModule = ModuleController.extend({
className: function () {
var classes = this.model.get('classes');
return ['user_satisfaction'].concat(classes || []).join(' ');
},
visualisationClass: UserSatisfactionView,
collectionClass: ListCollection,
clientRenderOnInit: true,
collectionOptions: function () {
return {
id: 'user_satisfaction',
title: 'User satisfaction',
sortBy: '_timestamp:ascending',
limit: 0,
valueAttr: this.model.get("value-attribute")
};
}
});
return UserSatisfactionModule;
});
|
define([
'extensions/controllers/module',
'common/views/visualisations/user-satisfaction',
'common/collections/list'
],
function (ModuleController, UserSatisfactionView, ListCollection) {
var UserSatisfactionModule = ModuleController.extend({
className: function () {
var classes = this.model.get('classes');
return ['user_satisfaction'].concat(classes || []).join(' ');
},
visualisationClass: UserSatisfactionView,
collectionClass: ListCollection,
clientRenderOnInit: true,
collectionOptions: function () {
return {
id: 'user_satisfaction',
title: 'User satisfaction',
sortBy: '_timestamp:descending',
valueAttr: this.model.get("value-attribute")
};
}
});
return UserSatisfactionModule;
});
|
Drop use of Phramework settngs
|
<?php
/**
* Copyright 2015 Xenofon Spafaridis
*
* 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.
*/
namespace Phramework\Exceptions;
/**
* DatabaseException
* Used to throw an \Exception, when there is something wrong with a Database request.
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
* @author Xenofon Spafaridis <nohponex@gmail.com>
*/
class DatabaseException extends \Exception
{
/**
* Database \Exception
*
* @todo Notify administrators
* @param string $message \Exception message
* @param string $error Internal error message
*/
public function __construct($message, $error = null)
{
parent::__construct($message, 500);
}
}
|
<?php
/**
* Copyright 2015 Xenofon Spafaridis
*
* 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.
*/
namespace Phramework\Exceptions;
/**
* DatabaseException
* Used to throw an \Exception, when there is something wrong with a Database request.
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
* @author Xenofon Spafaridis <nohponex@gmail.com>
*/
class DatabaseException extends \Exception
{
/**
* Database \Exception
*
* @todo Notify administrators
* @param string $message \Exception message
* @param string $error Internal error message
*/
public function __construct($message, $error = null)
{
if (\Phramework\Phramework::getSetting('debug') && $error) {
parent::__construct($error, 500);
} else {
parent::__construct($message, 500);
}
}
}
|
Remove reference to old demo.
|
// Demo components.
import "./src/CalendarDayMoonPhase.js";
import "./src/CarouselComboBox.js";
import "./src/CountryListBox.js";
import "./src/CustomCarousel2.js";
import "./src/CustomDrawer.js";
import "./src/LabeledColorSwatch.js";
import "./src/LocaleSelector.js";
import "./src/MessageListBox.js";
import "./src/MessageSummary.js";
import "./src/ModesWithKeyboard.js";
import "./src/PurpleSpinBox.js";
import "./src/RefreshAppDemo.js";
import "./src/RomanSpinBox.js";
import "./src/SampleDialog.js";
import "./src/serene/SereneTabs.js";
import "./src/SingleSelectionDemo.js";
import "./src/SlidingPagesWithArrows.js";
import "./src/SwipeDemo.js";
import "./src/ToolbarTab.js";
import "./src/UnitsSpinBox.js";
// We assume we'll want to provide demos of all of Elix itself.
import "../define/elix.js";
|
// Demo components.
import "./src/CalendarDayMoonPhase.js";
import "./src/CarouselComboBox.js";
import "./src/CountryListBox.js";
import "./src/CustomCarousel2.js";
import "./src/CustomDrawer.js";
import "./src/FocusVisibleTest.js";
import "./src/LabeledColorSwatch.js";
import "./src/LocaleSelector.js";
import "./src/MessageListBox.js";
import "./src/MessageSummary.js";
import "./src/ModesWithKeyboard.js";
import "./src/PurpleSpinBox.js";
import "./src/RefreshAppDemo.js";
import "./src/RomanSpinBox.js";
import "./src/SampleDialog.js";
import "./src/serene/SereneTabs.js";
import "./src/SingleSelectionDemo.js";
import "./src/SlidingPagesWithArrows.js";
import "./src/SwipeDemo.js";
import "./src/ToolbarTab.js";
import "./src/UnitsSpinBox.js";
// We assume we'll want to provide demos of all of Elix itself.
import "../define/elix.js";
|
Replace browser router with hash router to avoid hadling routing on server side
|
import React from 'react'
import {render} from 'react-dom'
import {Provider} from 'react-redux'
import Home from './components/home/Home'
import {
HashRouter as Router,
Route,
Link
} from 'react-router-dom'
import ArticleForm from './components/article/ArticleForm'
import configureStore from './redux/common/configureStore';
const store = configureStore();
render(
<Provider store={store}>
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/article">Add article</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}/>
<Route path="/article" component={ArticleForm}/>
</div>
</Router>
</Provider>,
document.getElementById('root')
);
|
import React from 'react'
import {render} from 'react-dom'
import {Provider} from 'react-redux'
import Home from './components/home/Home'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
import ArticleForm from './components/article/ArticleForm'
import configureStore from './redux/common/configureStore';
const store = configureStore();
render(
<Provider store={store}>
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/article">Add article</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}/>
<Route path="/article" component={ArticleForm}/>
</div>
</Router>
</Provider>,
document.getElementById('root')
);
|
Send email to hippo when user acknowledge his/her AWS.
|
<?php
include_once( "header.php" );
include_once( "methods.php" );
include_once( 'tohtml.php' );
include_once( "check_access_permissions.php" );
mustHaveAnyOfTheseRoles( Array( 'USER' ) );
echo userHTML( );
$user = $_SESSION[ 'user' ];
if( $_POST )
{
$data = array( 'speaker' => $user );
$data = array_merge( $_POST, $data );
echo( "Sending your acknowledgment to database " );
$res = updateTable( 'upcoming_aws', 'id,speaker', 'acknowledged', $data );
if( $res )
{
echo printInfo(
"You have successfully acknowledged your AWS schedule.
Please mark your calendar as well."
);
$email = "<p>" . loginToHTML( $user ) . " has just acknowledged his/her AWS date. </p>";
$emial .= "<p>" . humanReadableDate( 'now' ) . "</p>";
$subject = "$user has acknowledged his/her AWS date";
$to = 'hippo@lists.ncbs.res.in';
sendPlainTextEmail( $email, $subject, $to );
goToPage( "user_aws.php", 1 );
exit;
}
else
{
echo printWarning( "Failed to update database ..." );
}
}
echo goBackToPageLink( "user_aws.php", "Go back" );
?>
|
<?php
include_once( "header.php" );
include_once( "methods.php" );
include_once( 'tohtml.php' );
include_once( "check_access_permissions.php" );
mustHaveAnyOfTheseRoles( Array( 'USER' ) );
echo userHTML( );
$user = $_SESSION[ 'user' ];
if( $_POST )
{
$data = array( 'speaker' => $user );
$data = array_merge( $_POST, $data );
echo( "Sending your acknowledgment to database " );
$res = updateTable( 'upcoming_aws', 'id,speaker', 'acknowledged', $data );
if( $res )
{
echo printInfo(
"You have successfully acknowledged your AWS schedule.
Please mark your calendar as well."
);
$email = "<p>User " . loginToText( $user ) . " has just acknowledged his/her AWS date. </p>";
$subject = "$user has acknowledged his/her AWS date";
$to = 'hippo@lists.ncbs.res.in';
sendPlainTextEmail( $email, $subject, $to );
goToPage( "user_aws.php", 1 );
exit;
}
else
{
echo printWarning( "Failed to update database ..." );
}
}
echo goBackToPageLink( "user_aws.php", "Go back" );
?>
|
Remove not required logging from multiselect
|
function cachedScript(url, options) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend(options || {}, {
dataType: "script",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax(options);
};
export function initBootstrapSelect(ref, initialValues) {
cachedScript("/_content/JoinRpg.WebComponents/lib/bootstrap-select/js/bootstrap-select.js", {
complete: function (result) {
$(ref).selectpicker();
$(ref).selectpicker('val', initialValues);
// TODO why we need to force set?
}
});
};
export function refreshBootstrapSelect(ref) {
$(ref).selectpicker('refresh');
};
export function getSelectedValues(ref) {
var results = [];
var i;
for (i = 0; i < ref.options.length; i++) {
if (ref.options[i].selected) {
results[results.length] = ref.options[i].value;
}
}
return results;
}
|
function cachedScript(url, options) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend(options || {}, {
dataType: "script",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax(options);
};
export function initBootstrapSelect(ref, initialValues) {
cachedScript("/_content/JoinRpg.WebComponents/lib/bootstrap-select/js/bootstrap-select.js", {
complete: function (result) {
$(ref).selectpicker();
$(ref).selectpicker('val', initialValues);
// TODO why we need to force set?
}
});
};
export function refreshBootstrapSelect(ref) {
$(ref).selectpicker('refresh');
};
export function getSelectedValues(ref) {
var results = [];
var i;
for (i = 0; i < ref.options.length; i++) {
if (ref.options[i].selected) {
results[results.length] = ref.options[i].value;
}
}
console.log('***');
console.log(ref.options[0].selected);
console.log(results);
return results;
}
|
Fix port for Sip Heartbeat.
git-svn-id: 41af2ad439860065ec011fd0c01969868ab46825@14954 ab1d8caa-1f67-47f1-9e81-24633a41865c
|
/*
* Copyright (C) 2008 Pingtel Corp., certain elements licensed under a Contributor Agreement.
* Contributors retain copyright to elements licensed under a Contributor Agreement.
* Licensed to the User under the LGPL license.
*
*/
package org.sipfoundry.sipxbridge;
import gov.nist.javax.sip.ListeningPointExt;
import java.net.InetAddress;
import java.util.TimerTask;
import javax.sip.SipProvider;
import org.apache.log4j.Logger;
/**
* Sends out a CRLF to keep the NAT pinhole open.
*
* @author mranga
*
*/
class CrLfTimerTask extends TimerTask {
private static Logger logger = Logger.getLogger(CrLfTimerTask.class);
private ItspAccountInfo accountInfo;
private SipProvider provider;
CrLfTimerTask(SipProvider provider, ItspAccountInfo accountInfo) {
this.provider = provider;
this.accountInfo = accountInfo;
}
@Override
public void run() {
try {
ListeningPointExt listeningPoint = (ListeningPointExt) provider.getListeningPoint("udp");
listeningPoint.sendHeartbeat
(InetAddress.getByName(accountInfo.getInboundProxy()).getHostAddress(),
accountInfo.getInboundProxyPort());
} catch (Exception ex) {
logger.error("Unexpected parse exception",ex);
}
}
}
|
/*
* Copyright (C) 2008 Pingtel Corp., certain elements licensed under a Contributor Agreement.
* Contributors retain copyright to elements licensed under a Contributor Agreement.
* Licensed to the User under the LGPL license.
*
*/
package org.sipfoundry.sipxbridge;
import gov.nist.javax.sip.ListeningPointExt;
import java.net.InetAddress;
import java.util.TimerTask;
import javax.sip.SipProvider;
import org.apache.log4j.Logger;
/**
* Sends out a CRLF to keep the NAT pinhole open.
*
* @author mranga
*
*/
class CrLfTimerTask extends TimerTask {
private static Logger logger = Logger.getLogger(CrLfTimerTask.class);
private ItspAccountInfo accountInfo;
private SipProvider provider;
CrLfTimerTask(SipProvider provider, ItspAccountInfo accountInfo) {
this.provider = provider;
this.accountInfo = accountInfo;
}
@Override
public void run() {
try {
ListeningPointExt listeningPoint = (ListeningPointExt) provider.getListeningPoint("udp");
listeningPoint.sendHeartbeat
(InetAddress.getByName(accountInfo.getInboundProxy()).getHostAddress(),
Gateway.getSipKeepaliveSeconds());
} catch (Exception ex) {
logger.error("Unexpected parse exception",ex);
}
}
}
|
Clarify the rational for the ToLower(key) call
|
package otgrpc
import (
"strings"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"google.golang.org/grpc/metadata"
)
var (
// Morally a const:
gRPCComponentTag = opentracing.Tag{string(ext.Component), "gRPC"}
)
// metadataReaderWriter satisfies both the opentracing.TextMapReader and
// opentracing.TextMapWriter interfaces.
type metadataReaderWriter struct {
metadata.MD
}
func (w metadataReaderWriter) Set(key, val string) {
// The GRPC HPACK implementation rejects any uppercase keys here.
//
// As such, since the HTTP_HEADERS format is case-insensitive anyway, we
// blindly lowercase the key (which is guaranteed to work in the
// Inject/Extract sense per the OpenTracing spec).
key = strings.ToLower(key)
w.MD[key] = append(w.MD[key], val)
}
func (w metadataReaderWriter) ForeachKey(handler func(key, val string) error) error {
for k, vals := range w.MD {
for _, v := range vals {
if dk, dv, err := metadata.DecodeKeyValue(k, v); err == nil {
if err = handler(dk, dv); err != nil {
return err
}
} else {
return err
}
}
}
return nil
}
|
package otgrpc
import (
"strings"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"google.golang.org/grpc/metadata"
)
var (
// Morally a const:
gRPCComponentTag = opentracing.Tag{string(ext.Component), "gRPC"}
)
// metadataReaderWriter satisfies both the opentracing.TextMapReader and
// opentracing.TextMapWriter interfaces.
type metadataReaderWriter struct {
metadata.MD
}
func (w metadataReaderWriter) Set(key, val string) {
key = strings.ToLower(key)
w.MD[key] = append(w.MD[key], val)
}
func (w metadataReaderWriter) ForeachKey(handler func(key, val string) error) error {
for k, vals := range w.MD {
for _, v := range vals {
if dk, dv, err := metadata.DecodeKeyValue(k, v); err == nil {
if err = handler(dk, dv); err != nil {
return err
}
} else {
return err
}
}
}
return nil
}
|
Make it possible to manually override version numbers
|
#!/usr/bin/python
import time
from datetime import date
from setuptools import setup
from pagekite.common import APPVER
import os
try:
# This borks sdist.
os.remove('.SELF')
except:
pass
setup(
name="pagekite",
version=os.getenv(
'PAGEKITE_VERSION',
APPVER.replace('github', 'dev%d' % (120*int(time.time()/120)))),
license="AGPLv3+",
author="Bjarni R. Einarsson",
author_email="bre@pagekite.net",
url="http://pagekite.org/",
description="""PageKite makes localhost servers visible to the world.""",
long_description="""\
PageKite is a system for running publicly visible servers (generally
web servers) on machines without a direct connection to the Internet,
such as mobile devices or computers behind restrictive firewalls.
PageKite works around NAT, firewalls and IP-address limitations by
using a combination of tunnels and reverse proxies.
Natively supported protocols: HTTP, HTTPS
Any other TCP-based service, including SSH and VNC, may be exposed
as well to clients supporting HTTP Proxies.
""",
packages=['pagekite', 'pagekite.ui', 'pagekite.proto'],
scripts=['scripts/pagekite', 'scripts/lapcat', 'scripts/vipagekite'],
install_requires=['SocksipyChain >= 2.0.15']
)
|
#!/usr/bin/python
import time
from datetime import date
from setuptools import setup
from pagekite.common import APPVER
import os
try:
# This borks sdist.
os.remove('.SELF')
except:
pass
setup(
name="pagekite",
version=APPVER.replace('github', 'dev%d' % (120*int(time.time()/120))),
license="AGPLv3+",
author="Bjarni R. Einarsson",
author_email="bre@pagekite.net",
url="http://pagekite.org/",
description="""PageKite makes localhost servers visible to the world.""",
long_description="""\
PageKite is a system for running publicly visible servers (generally
web servers) on machines without a direct connection to the Internet,
such as mobile devices or computers behind restrictive firewalls.
PageKite works around NAT, firewalls and IP-address limitations by
using a combination of tunnels and reverse proxies.
Natively supported protocols: HTTP, HTTPS
Any other TCP-based service, including SSH and VNC, may be exposed
as well to clients supporting HTTP Proxies.
""",
packages=['pagekite', 'pagekite.ui', 'pagekite.proto'],
scripts=['scripts/pagekite', 'scripts/lapcat', 'scripts/vipagekite'],
install_requires=['SocksipyChain >= 2.0.15']
)
|
Add test for JSON parse method
|
/**
* IMDBHandlerTest.java
*
* @author Johan Brook
* @copyright (c) 2012 Johan Brook
* @license MIT
*/
package se.chalmers.watchmetest.net;
import org.json.JSONArray;
import org.json.JSONObject;
import se.chalmers.watchme.net.IMDBHandler;
import se.chalmers.watchme.utils.MovieHelper;
import junit.framework.TestCase;
public class IMDBHandlerTest extends TestCase {
IMDBHandler imdb;
protected void setUp() throws Exception {
super.setUp();
this.imdb = new IMDBHandler();
}
public void testGetMovies() {
JSONArray json = this.imdb.getMoviesByTitle("casino royale");
assertNotNull(json);
assertTrue(json.length() > 0);
}
public void testGetMovie() {
JSONArray json = this.imdb.getMoviesByTitle("casino royale");
JSONObject movie = json.optJSONObject(0);
assertNotNull(movie);
}
public void testGetNonExistingMovie() {
JSONArray json = this.imdb.getMoviesByTitle("awdkaowidoawijdwoaijdawoidjaowid");
assertNull(json);
}
public void testParseStringToJSON() {
String json = "[{key: \"val\"}]";
String json2 = "{key: \"val\"}";
JSONObject res = IMDBHandler.parseStringToJSON(json);
JSONObject res2 = IMDBHandler.parseStringToJSON(json2);
assertNotNull(res);
assertNotNull(res2);
assertNotNull(res.optString("key"));
assertNotNull(res2.optString("key"));
}
}
|
/**
* IMDBHandlerTest.java
*
* @author Johan Brook
* @copyright (c) 2012 Johan Brook
* @license MIT
*/
package se.chalmers.watchmetest.net;
import org.json.JSONArray;
import org.json.JSONObject;
import se.chalmers.watchme.net.IMDBHandler;
import junit.framework.TestCase;
public class IMDBHandlerTest extends TestCase {
IMDBHandler imdb;
protected void setUp() throws Exception {
super.setUp();
this.imdb = new IMDBHandler();
}
public void testGetMovies() {
JSONArray json = this.imdb.getMoviesByTitle("casino royale");
assertNotNull(json);
assertTrue(json.length() > 0);
}
public void testGetMovie() {
JSONArray json = this.imdb.getMoviesByTitle("casino royale");
JSONObject movie = json.optJSONObject(0);
assertNotNull(movie);
}
public void testGetNonExistingMovie() {
JSONArray json = this.imdb.getMoviesByTitle("awdkaowidoawijdwoaijdawoidjaowid");
assertNull(json);
}
}
|
Modify Fuse require statement to hopefully fit with exporting logic
|
require('cloud/app.js');
var Fuse = require('cloud/fuse.min.js');
/*
* Provides Cloud Functions for Rice Maps.
*/
Parse.Cloud.define("placesSearch", function(request, response) {
console.log("Search Query: " + request.params.query);
// Define Parse cloud query that retrieves all Place objects and matches them to a search
var query = new Parse.Query("Place");
query.find({
success: function(results) {
// Perform Fuse.js fuzzy search on all Place objects
var options = {
keys: ['name', 'symbol']
}
searcher = new Fuse(results, options);
matches = searcher.search(request.params.query)
response.success(matches);
},
error: function(error) {
response.error(error);
}
});
});
|
require('cloud/app.js');
require('cloud/fuse.min.js');
/*
* Provides Cloud Functions for Rice Maps.
*/
Parse.Cloud.define("placesSearch", function(request, response) {
console.log("Search Query: " + request.params.query);
// Define Parse cloud query that retrieves all Place objects and matches them to a search
var query = new Parse.Query("Place");
query.find({
success: function(results) {
// Perform Fuse.js fuzzy search on all Place objects
var options = {
keys: ['name', 'symbol']
}
searcher = new Fuse(results, options);
matches = searcher.search(request.params.query)
response.success(matches);
},
error: function(error) {
response.error(error);
}
});
});
|
Insert filename only, not path
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from downstream_node.config import config
from downstream_node.models import Challenges, Files
from heartbeat import Heartbeat
from downstream_node.startup import db
__all__ = ['create_token', 'delete_token', 'add_file', 'remove_file',
'gen_challenges', 'update_challenges']
def create_token(*args, **kwargs):
raise NotImplementedError
def delete_token(*args, **kwargs):
raise NotImplementedError
def add_file(*args, **kwargs):
raise NotImplementedError
def remove_file(*args, **kwargs):
raise NotImplementedError
def gen_challenges(filepath, root_seed):
secret = getattr(config, 'HEARTBEAT_SECRET')
hb = Heartbeat(filepath, secret=secret)
hb.generate_challenges(1000, root_seed)
files = Files(name=os.path.split(filepath)[1])
db.session.add(files)
for challenge in hb.challenges:
chal = Challenges(
filename=filepath,
rootseed=root_seed,
block=challenge.block,
seed=challenge.seed,
response=challenge.response,
)
db.session.add(chal)
db.session.commit()
def update_challenges(*args, **kwargs):
raise NotImplementedError
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from downstream_node.config import config
from downstream_node.models import Challenges, Files
from heartbeat import Heartbeat
from downstream_node.startup import db
__all__ = ['create_token', 'delete_token', 'add_file', 'remove_file',
'gen_challenges', 'update_challenges']
def create_token(*args, **kwargs):
raise NotImplementedError
def delete_token(*args, **kwargs):
raise NotImplementedError
def add_file(*args, **kwargs):
raise NotImplementedError
def remove_file(*args, **kwargs):
raise NotImplementedError
def gen_challenges(filepath, root_seed):
secret = getattr(config, 'HEARTBEAT_SECRET')
hb = Heartbeat(filepath, secret=secret)
hb.generate_challenges(1000, root_seed)
files = Files(name=filepath)
db.session.add(files)
for challenge in hb.challenges:
chal = Challenges(
filename=filepath,
rootseed=root_seed,
block=challenge.block,
seed=challenge.seed,
response=challenge.response,
)
db.session.add(chal)
db.session.commit()
def update_challenges(*args, **kwargs):
raise NotImplementedError
|
Add tracking for lessons 1, 2, 3
|
# See also examples/example_track/track_meta.py for a longer, commented example
track = dict(
author_username='ryanholbrook',
course_name='Computer Vision',
course_url='https://www.kaggle.com/ryanholbrook/computer-vision'
)
lessons = [
{'topic': topic_name} for topic_name in
[
'The Convolutional Classifier',
'Convnet Architecture',
'Filter, Detect, Condense',
# 'Convolution and Pooling',
# 'Exploring Convnets',
# 'Transfer Learning',
# 'Data Augmentation',
]
]
notebooks = [
dict(
filename='tut1.ipynb',
lesson_idx=0,
type='tutorial',
),
dict(
filename='tut2.ipynb',
lesson_idx=1,
type='tutorial',
),
dict(
filename='tut3.ipynb',
lesson_idx=2,
type='tutorial',
),
]
for nb in notebooks:
nb['dataset_sources'] = [
"ryanholbrook/stanford-cars-for-learn",
"ryanholbrook/saved-models",
]
|
# See also examples/example_track/track_meta.py for a longer, commented example
track = dict(
author_username='ryanholbrook',
course_name='computer_vision',
course_url='https://www.kaggle.com/ryanholbrook/computer-vision'
)
lessons = [
dict(
# By convention, this should be a lowercase noun-phrase.
topic='Testing',
),
]
notebooks = [
dict(
filename='test.ipynb',
lesson_idx=0,
type='exercise',
scriptid=1,
),
]
for nb in notebooks:
nb['dataset_sources'] = ["ryanholbrook/stanford-cars-for-learn"]
|
Change string singlequotes to doublequotes
|
var hexcolor = document.getElementById('hexcolor');
var clock = document.getElementById('clock');
var hexColor = document.getElementById('hex-color');
function colorClock() {
var time = new Date();
var day = time.getDay();
var hours = time.getHours().toString();
var minutes = time.getMinutes().toString();
var seconds = time.getSeconds().toString();
if (hours.length < 2) {
hours = "0" + hours;
}
if (minutes.length < 2) {
minutes = "0" + minutes;
}
if (seconds.length < 2) {
seconds = "0" + seconds;
}
var clockStr = hours + " : " + minutes + " : " + seconds;
var hexColorStr = "#" + hours + minutes + seconds;
var dayStr = day;
hexcolor.textContent = hexColorStr;
// clock.textContent = clockStr;
document.getElementById('container').style.backgroundColor = hexColorStr;
document.getElementById('hexcolor').style.color = hexColorStr;
}
colorClock();
setInterval(colorClock, 1000);
|
var hexcolor = document.getElementById('hexcolor');
var clock = document.getElementById('clock');
var hexColor = document.getElementById('hex-color');
function colorClock() {
var time = new Date();
var day = time.getDay();
var hours = time.getHours().toString();
var minutes = time.getMinutes().toString();
var seconds = time.getSeconds().toString();
if (hours.length < 2) {
hours = '0' + hours;
}
if (minutes.length < 2) {
minutes = '0' + minutes;
}
if (seconds.length < 2) {
seconds = '0' + seconds;
}
var clockStr = hours + ' : ' + minutes + ' : ' + seconds;
var hexColorStr = '#' + hours + minutes + seconds;
var dayStr = day;
hexcolor.textContent = hexColorStr;
// clock.textContent = clockStr;
document.getElementById('container').style.backgroundColor = hexColorStr;
document.getElementById('hexcolor').style.color = hexColorStr;
}
colorClock();
setInterval(colorClock, 1000);
|
Add warning for missing Ora i18n driver independent of DB version
|
package org.utplsql.cli;
import org.utplsql.api.DBHelper;
import org.utplsql.api.Version;
import org.utplsql.api.compatibility.OptionalFeatures;
import java.sql.Connection;
import java.sql.SQLException;
/** Helper class to check several circumstances with RunCommand. Might need refactoring.
*
* @author pesse
*/
class RunCommandChecker {
/** Checks that orai18n library exists if database is an oracle 11
*
*/
static void checkOracleI18nExists(Connection con) throws SQLException {
if ( !OracleLibraryChecker.checkOrai18nExists() )
{
System.out.println("WARNING: Could not find Oracle i18n driver in classpath. Depending on the database charset " +
"utPLSQL-cli, especially code coverage, might not run properly. It is recommended you download " +
"the i18n driver from the Oracle website and copy it to the 'lib' folder of your utPLSQL-cli installation.");
System.out.println("Download from http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html");
}
}
}
|
package org.utplsql.cli;
import org.utplsql.api.DBHelper;
import org.utplsql.api.Version;
import org.utplsql.api.compatibility.OptionalFeatures;
import java.sql.Connection;
import java.sql.SQLException;
/** Helper class to check several circumstances with RunCommand. Might need refactoring.
*
* @author pesse
*/
class RunCommandChecker {
/** Checks that orai18n library exists if database is an oracle 11
*
*/
static void checkOracleI18nExists(Connection con) throws SQLException {
String oracleDatabaseVersion = DBHelper.getOracleDatabaseVersion(con);
if ( oracleDatabaseVersion.startsWith("11.") && !OracleLibraryChecker.checkOrai18nExists() )
{
System.out.println("Warning: Could not find Oracle i18n driver in classpath. Depending on the database charset " +
"utPLSQL-cli might not run properly. It is recommended you download " +
"the i18n driver from the Oracle website and copy it to the 'lib' folder of your utPLSQL-cli installation.");
System.out.println("Download from http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html");
}
}
}
|
WebsocketConnection: Fix saga (call -> takeEvery)
|
import { put, takeEvery, call } from 'redux-saga/effects';
import { SEND_REQUEST } from './constants';
import { sendRequestSuccess, sendRequestFail } from './actions'
import { getWebsocket } from './websocket'
function* sendRequest(action) {
let websocket = getWebsocket()
const request = action.request
const requestId = request.request_id
let errFlag = false
if (websocket) {
try {
websocket.send(JSON.stringify(action.request))
yield put(sendRequestSuccess(requestId))
} catch (e) {
errFlag = true
}
} else {
errFlag = true
}
if (errFlag)
yield put(sendRequestFail(requestId))
}
function* sendRequestSaga(action) {
yield takeEvery(SEND_REQUEST, sendRequest)
}
export default [
sendRequestSaga,
];
|
import { put, takeEvery, call } from 'redux-saga/effects';
import { SEND_REQUEST } from './constants';
import { sendRequestSuccess, sendRequestFail } from './actions'
import { getWebsocket } from './websocket'
function* sendRequest(action) {
let websocket = getWebsocket()
const request = action.request
const requestId = request.request_id
let errFlag = false
if (websocket) {
try {
websocket.send(action.request)
yield put(sendRequestSuccess(requestId))
} catch (e) {
errFlag = true
}
} else {
errFlag = true
}
if (errFlag)
yield put(sendRequestFail(requestId))
}
function* sendRequestSaga(action) {
yield call(takeEvery, SEND_REQUEST, sendRequest)
}
export default [
sendRequestSaga,
];
|
Remove the PHP 5.5 `::class` usage
|
<?php
namespace spec\Dock\Docker\Dns;
use Dock\Docker\Dns\ContainerAddressResolver;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class DnsDockResolverSpec extends ObjectBehavior
{
function it_is_a_container_address_resolve()
{
$this->shouldImplement('Dock\Docker\Dns\ContainerAddressResolver');
}
function it_returns_the_resolution_with_just_the_image_name()
{
$this->getDnsByContainerNameAndImage('container', 'image')->shouldContain('image.docker');
}
function it_returns_the_container_specific_resolution()
{
$this->getDnsByContainerNameAndImage('container', 'image')->shouldContain('container.image.docker');
}
function it_removes_the_tag_in_image_name()
{
$this->getDnsByContainerNameAndImage('container', 'image:latest')->shouldContain('container.image.docker');
}
}
|
<?php
namespace spec\Dock\Docker\Dns;
use Dock\Docker\Dns\ContainerAddressResolver;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class DnsDockResolverSpec extends ObjectBehavior
{
function it_is_a_container_address_resolve()
{
$this->shouldImplement(ContainerAddressResolver::class);
}
function it_returns_the_resolution_with_just_the_image_name()
{
$this->getDnsByContainerNameAndImage('container', 'image')->shouldContain('image.docker');
}
function it_returns_the_container_specific_resolution()
{
$this->getDnsByContainerNameAndImage('container', 'image')->shouldContain('container.image.docker');
}
function it_removes_the_tag_in_image_name()
{
$this->getDnsByContainerNameAndImage('container', 'image:latest')->shouldContain('container.image.docker');
}
}
|
Add some new spell result types
|
package com.elmakers.mine.bukkit.api.spell;
/**
* Every Spell will return a SpellResult when cast. This result
* will determine the messaging and effects used, as well as whether
* or not the Spell cast consumes its CastingCost costs.
*
* A Spell that fails to cast will not consume costs or register for cooldown.
*/
public enum SpellResult {
CAST,
AREA,
FIZZLE,
BACKFIRE,
FAIL,
CANCEL,
INSUFFICIENT_RESOURCES,
INSUFFICIENT_PERMISSION,
COOLDOWN,
NO_TARGET,
RESTRICTED,
TARGET_SELECTED,
ENTITY_REQUIRED,
LIVING_ENTITY_REQUIRED,
PLAYER_REQUIRED,
LOCATION_REQUIRED,
WORLD_REQUIRED,
INVALID_WORLD,
COST_FREE;
/**
* Determine if this result is a success or not.
*
* @return True if this cast was a success.
*/
public boolean isSuccess() {
return this == CAST || this == AREA || this == FIZZLE || this == BACKFIRE;
}
}
|
package com.elmakers.mine.bukkit.api.spell;
/**
* Every Spell will return a SpellResult when cast. This result
* will determine the messaging and effects used, as well as whether
* or not the Spell cast consumes its CastingCost costs.
*
* A Spell that fails to cast will not consume costs or register for cooldown.
*/
public enum SpellResult {
CAST,
AREA,
FIZZLE,
BACKFIRE,
FAIL,
CANCEL,
INSUFFICIENT_RESOURCES,
INSUFFICIENT_PERMISSION,
COOLDOWN,
NO_TARGET,
RESTRICTED,
TARGET_SELECTED,
PLAYER_REQUIRED,
WORLD_REQUIRED,
INVALID_WORLD,
COST_FREE;
/**
* Determine if this result is a success or not.
*
* @return True if this cast was a success.
*/
public boolean isSuccess() {
return this == CAST || this == AREA || this == FIZZLE || this == BACKFIRE;
}
}
|
Add installation of repository dependencies for tools
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bioblend import galaxy
from bioblend import toolshed
if __name__ == '__main__':
gi_url = "http://172.21.23.6:8080/"
ts_url = "http://172.21.23.6:9009/"
name = "qiime"
owner = "iuc"
tool_panel_section_id = "qiime_rRNA_taxonomic_assignation"
gi = galaxy.GalaxyInstance(url=gi_url, key='8a099e97b0a83c73ead9f5b0fe19f4be')
ts = toolshed.ToolShedInstance(url=ts_url)
changeset_revision = str(ts.repositories.get_ordered_installable_revisions(name,
owner)[-1])
gi.toolShed.install_repository_revision(ts_url, name, owner, changeset_revision,
install_tool_dependencies=True, install_repository_dependencies=True,
tool_panel_section_id=tool_panel_section_id)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bioblend import galaxy
from bioblend import toolshed
if __name__ == '__main__':
gi_url = "http://172.21.23.6:8080/"
ts_url = "http://172.21.23.6:9009/"
name = "qiime"
owner = "iuc"
tool_panel_section_id = "qiime_rRNA_taxonomic_assignation"
gi = galaxy.GalaxyInstance(url=gi_url, key='8a099e97b0a83c73ead9f5b0fe19f4be')
ts = toolshed.ToolShedInstance(url=ts_url)
changeset_revision = str(ts.repositories.get_ordered_installable_revisions(name,
owner)[-1])
gi.toolShed.install_repository_revision(ts_url, name, owner, changeset_revision,
install_tool_dependencies=True, install_repository_dependencies=False,
tool_panel_section_id=tool_panel_section_id)
|
Add option to display the VWP version
|
const Path = require('path')
const action = process.argv[2]
var args = process.argv.slice(3)
var env = process.env.NODE_ENV
var webpack
switch (action) {
case 'build':
webpack = 'webpack'
env = env || 'production'
break
case 'dist':
webpack = 'webpack'
env = env || 'production'
args.push('-p')
break
case 'dev':
case 'start':
webpack = 'webpack-dev-server'
env = env || 'development'
args.push('--hot')
break
case '--version':
case '-v':
console.log('echo', 'VWP version: ', require('../package.json').version)
return
default:
console.log('missing command: build, dev or dist')
process.exit(1)
}
var cmd = []
cmd.push(require.resolve(`.bin/${webpack}`))
cmd.push('--config')
cmd.push(Path.resolve(__dirname, '../webpackfile.js'))
cmd.push('--progress')
cmd.push(...args)
console.log(cmd.join(' '))
|
const Path = require('path')
const action = process.argv[2]
var args = process.argv.slice(3)
var env = process.env.NODE_ENV
var webpack
switch (action) {
case 'build':
webpack = 'webpack'
env = env || 'production'
break
case 'dist':
webpack = 'webpack'
env = env || 'production'
args.push('-p')
break
case 'dev':
case 'start':
webpack = 'webpack-dev-server'
env = env || 'development'
args.push('--hot')
break
default:
console.log('missing command: build, dev or dist')
process.exit(1)
}
var cmd = []
cmd.push(require.resolve(`.bin/${webpack}`))
cmd.push('--config')
cmd.push(Path.resolve(__dirname, '../webpackfile.js'))
cmd.push('--progress')
cmd.push(...args)
console.log(cmd.join(' '))
|
Update Flask version to 1.0.2
|
from setuptools import setup, find_packages
requirements = [
'Flask==1.0.2',
]
setup(
name='flask-pundit',
version='1.1.0',
license='MIT',
url='https://github.com/anurag90x/flask-pundit',
author='Anurag Chaudhury',
author_email='anuragchaudhury@gmail.com',
description='Simple library to manage resource authorization and scoping',
packages=find_packages(exclude=['tests']),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite='nose.collector',
install_requires=requirements,
tests_require=['mock==1.3.0'],
classifiers=[
'Framework :: Flask',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: MIT License'
]
)
|
from setuptools import setup, find_packages
requirements = [
'Flask==0.10.1',
]
setup(
name='flask-pundit',
version='1.1.0',
license='MIT',
url='https://github.com/anurag90x/flask-pundit',
author='Anurag Chaudhury',
author_email='anuragchaudhury@gmail.com',
description='Simple library to manage resource authorization and scoping',
packages=find_packages(exclude=['tests']),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite='nose.collector',
install_requires=requirements,
tests_require=['mock==1.3.0'],
classifiers=[
'Framework :: Flask',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: MIT License'
]
)
|
Fix error when profile is not present
|
'use strict';
angular.module('mean.icu.ui.profile', [])
.controller('ProfileController', function($scope, $state, me, UsersService) {
$scope.me = me;
if (!$scope.me.profile) {
$scope.me.profile = {};
}
$scope.avatar = $scope.me.profile.avatar || 'http://placehold.it/250x250';
$scope.hash = new Date().getTime();
$scope.uploadAvatar = function(files) {
if (files) {
var file = files[0];
UsersService.updateAvatar(file).success(function(data) {
$scope.me.profile.avatar = data.avatar;
$state.reload();
});
}
};
$scope.editProfile = function(form) {
if ($scope.confirm !== $scope.me.password) {
return;
}
UsersService.update($scope.me).then(function() {
$state.reload();
});
};
});
|
'use strict';
angular.module('mean.icu.ui.profile', [])
.controller('ProfileController', function($scope, $state, me, UsersService) {
$scope.me = me;
$scope.avatar = $scope.me.profile.avatar || 'http://placehold.it/250x250';
$scope.hash = new Date().getTime();
$scope.uploadAvatar = function(files) {
if (files) {
var file = files[0];
UsersService.updateAvatar(file).success(function(data) {
$scope.me.profile.avatar = data.avatar;
$state.reload();
});
}
};
$scope.editProfile = function(form) {
if ($scope.confirm !== $scope.me.password) {
return;
}
UsersService.update($scope.me).then(function() {
$state.reload();
});
};
});
|
Improve error handling by returning the `statusCode` and including the failed URL in the rejected Error
|
import { get, defaults, compact } from 'lodash';
import request from 'request';
import config from '../../config';
export default (url, options = {}) => {
return new Promise((resolve, reject) => {
const opts = defaults(options, {
method: 'GET',
timeout: config.REQUEST_TIMEOUT_MS,
});
request(url, opts, (err, response) => {
if (!!err || response.statusCode !== 200) {
if (err) return reject(err);
const message = compact([
get(response, 'request.uri.href'),
response.body,
]).join(' - ');
const error = new Error(message);
error.statusCode = response.statusCode;
return reject(error);
}
try {
const shouldParse = typeof response.body === 'string';
const parsed = shouldParse ? JSON.parse(response.body) : response.body;
resolve({
body: parsed,
headers: response.headers,
});
} catch (error) {
reject(error);
}
});
});
};
|
import { defaults } from 'lodash';
import request from 'request';
import config from '../../config';
export default (url, options = {}) => {
return new Promise((resolve, reject) => {
const opts = defaults(options, {
method: 'GET',
timeout: config.REQUEST_TIMEOUT_MS,
});
request(url, opts, (err, response) => {
if (!!err || response.statusCode !== 200) {
return reject(err || new Error(response.body));
}
try {
const shouldParse = typeof response.body === 'string';
const parsed = shouldParse ? JSON.parse(response.body) : response.body;
resolve({
body: parsed,
headers: response.headers,
});
} catch (error) {
reject(error);
}
});
});
};
|
Fix error where DATABASE_URL does not exist in environment
|
var Sequelize = require('sequelize'),
pg = require('pg').native;
module.exports = function(opts) {
if (!opts.DATABASE_URL) {
throw(new Error('Must specify DATABASE_URL in config.json or as environment variable'));
}
// TODO Support other databases
var match = opts.DATABASE_URL.match(/postgres:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/),
db = new Sequelize(match[5], match[1], match[2], {
dialect: 'postgres',
protocol: 'postgres',
port: match[4],
host: match[3],
logging: false,
native: true,
define: {
underscored: true
}
});
db.authenticate()
.error(function(err){
throw(new Error('Cannot connect to postgres db: ' + err));
})
.success(function(){
console.log('Connected to PostgreSQL db');
});
return db;
};
|
var Sequelize = require('sequelize'),
pg = require('pg').native;
module.exports = function(opts) {
if (!opts.DATABASE_URL) {
throw(new Error('Must specify DATABASE_URL in config.json or as environment variable'));
}
// TODO Support other databases
var match = process.env.DATABASE_URL.match(/postgres:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/),
db = new Sequelize(match[5], match[1], match[2], {
dialect: 'postgres',
protocol: 'postgres',
port: match[4],
host: match[3],
logging: false,
native: true,
define: {
underscored: true
}
});
db.authenticate()
.error(function(err){
throw(new Error('Cannot connect to postgres db: ' + err));
})
.success(function(){
console.log('Connected to PostgreSQL db');
});
return db;
};
|
Adjust the helperfunction for a lazy map component to use the correct xtype.
|
function getMap(){
var map = new OpenLayers.Map({
layers: [
new OpenLayers.Layer.WMS(
"OpenLayers WMS",
"http://vmap0.tiles.osgeo.org/wms/vmap0",
{
layers: "basic"
}
)
]
});
return map;
}
function getMapPanel(opts) {
var map = getMap();
var options = Ext.apply(opts || {});
if (!opts || !opts.map) {
options.map = map;
}
var mappanel = Ext.create('GXM.Map', options);
return mappanel;
}
function getLazyMapPanel(opts) {
var options = Ext.apply(opts || {}, { xtype: 'gxm_map' });
options.map = ( opts && opts.map ) ? opts.map : getMap();
var mappanel = options;
var panel = Ext.create('Ext.Panel', {
fullscreen: true,
items:[ mappanel ]
});
return panel.items.get(0);
}
|
function getMap(){
var map = new OpenLayers.Map({
layers: [
new OpenLayers.Layer.WMS(
"OpenLayers WMS",
"http://vmap0.tiles.osgeo.org/wms/vmap0",
{
layers: "basic"
}
)
]
});
return map;
}
function getMapPanel(opts) {
var map = getMap();
var options = Ext.apply(opts || {});
if (!opts || !opts.map) {
options.map = map;
}
var mappanel = Ext.create('GXM.Map', options);
return mappanel;
}
function getLazyMapPanel(opts) {
var options = Ext.apply(opts || {}, { xtype: 'gxm_mappanel' });
options.map = ( opts && opts.map ) ? opts.map : getMap();
var mappanel = options;
var panel = Ext.create('Ext.Panel', {
fullscreen: true,
items:[ mappanel ]
});
return panel.items.get(0);
}
|
Fix crashing bug: Compare Libya
|
import { createSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import {
parseSelectedLocations,
getSelectedLocationsFilter,
addSelectedNameToLocations
} from 'selectors/compare';
// values from search
const getSelectedLocations = state => state.selectedLocations || null;
const getContentOverviewData = state => state.ndcContentOverviewData || null;
const getCountriesData = state => state.countriesData || null;
const parseLocations = parseSelectedLocations(getSelectedLocations);
export const getLocationsFilter = getSelectedLocationsFilter(
getSelectedLocations
);
export const addNameToLocations = addSelectedNameToLocations(
getCountriesData,
parseLocations
);
export const getSummaryText = createSelector(
[addNameToLocations, getContentOverviewData],
(selectedLocations, data) => {
if (!selectedLocations || !data || isEmpty(data)) return null;
return selectedLocations.map(l => {
const d = data[l.iso_code3];
const text =
d && d.values && d.values.find(v => v.slug === 'indc_summary');
return { ...l, text: text && text.value };
});
}
);
export default {
getSummaryText,
getLocationsFilter
};
|
import { createSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import {
parseSelectedLocations,
getSelectedLocationsFilter,
addSelectedNameToLocations
} from 'selectors/compare';
// values from search
const getSelectedLocations = state => state.selectedLocations || null;
const getContentOverviewData = state => state.ndcContentOverviewData || null;
const getCountriesData = state => state.countriesData || null;
const parseLocations = parseSelectedLocations(getSelectedLocations);
export const getLocationsFilter = getSelectedLocationsFilter(
getSelectedLocations
);
export const addNameToLocations = addSelectedNameToLocations(
getCountriesData,
parseLocations
);
export const getSummaryText = createSelector(
[addNameToLocations, getContentOverviewData],
(selectedLocations, data) => {
if (!selectedLocations || !data || isEmpty(data)) return null;
return selectedLocations.map(l => {
const d = data[l.iso_code3];
const text =
d && d.values && d.values.find(v => v.slug === 'indc_summary').value;
return { ...l, text };
});
}
);
export default {
getSummaryText,
getLocationsFilter
};
|
Test over export and import functions added.
|
"use strict";
var PLS = require("../src/pls");
var Matrix = require("ml-matrix");
describe("PLS-DA algorithm", function () {
var training = [[0.1, 0.02], [0.25, 1.01] ,[0.95, 0.01], [1.01, 0.96]];
var predicted = [[1, 0], [1, 0], [1, 0], [0, 1]];
var pls = new PLS(training, predicted);
it("test with a pseudo-AND operator", function () {
var result = pls.predict(training);
(result[0][0] > result[0][1]).should.be.ok;
(result[1][0] > result[1][1]).should.be.ok;
(result[2][0] > result[2][1]).should.be.ok;
(result[3][0] < result[3][1]).should.be.ok;
});
it("Export and import", function () {
var model = pls.export();
var newpls = PLS.load(model);
var result = newpls.predict(training);
(result[0][0] > result[0][1]).should.be.ok;
(result[1][0] > result[1][1]).should.be.ok;
(result[2][0] > result[2][1]).should.be.ok;
(result[3][0] < result[3][1]).should.be.ok;
})
});
|
"use strict";
var PLS = require("../src/pls");
var Matrix = require("ml-matrix");
describe("PLS-DA algorithm", function () {
it("test with a pseudo-AND operator", function () {
var training = [[0.1, 0.02], [0.25, 1.01] ,[0.95, 0.01], [1.01, 0.96]];
var predicted = [[1, 0], [1, 0], [1, 0], [0, 1]];
var pls = new PLS(training, predicted);
var result = pls.predict(training);
(result[0][0] > result[0][1]).should.be.ok;
(result[1][0] > result[1][1]).should.be.ok;
(result[2][0] > result[2][1]).should.be.ok;
(result[3][0] < result[3][1]).should.be.ok;
});
});
|
Use find_packages to discover packages.
|
#!/usr/bin/env python
# coding=utf8
import os
import sys
from setuptools import setup, find_packages
if sys.version_info < (2, 7):
tests_require = ['unittest2', 'mock']
test_suite = 'unittest2.collector'
else:
tests_require = ['mock']
test_suite = 'unittest.collector'
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='simplekv',
version='0.4dev',
description='A simple key-value storage for binary data.',
long_description=read('README.rst'),
keywords='key-value-store storage key-value db database',
author='Marc Brinkmann',
author_email='git@marcbrinkmann.de',
url='http://github.com/mbr/simplekv',
license='MIT',
packages=find_packages(exclude=['test']),
py_modules=[],
tests_require=tests_require,
test_suite='unittest2.collector',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Database',
'Topic :: Software Development :: Libraries',
]
)
|
#!/usr/bin/env python
# coding=utf8
import os
import sys
from setuptools import setup
if sys.version_info < (2, 7):
tests_require = ['unittest2', 'mock']
test_suite = 'unittest2.collector'
else:
tests_require = ['mock']
test_suite = 'unittest.collector'
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='simplekv',
version='0.4dev',
description='A simple key-value storage for binary data.',
long_description=read('README.rst'),
keywords='key-value-store storage key-value db database',
author='Marc Brinkmann',
author_email='git@marcbrinkmann.de',
url='http://github.com/mbr/simplekv',
license='MIT',
packages=['simplekv'],
py_modules=[],
tests_require=tests_require,
test_suite='unittest2.collector',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Database',
'Topic :: Software Development :: Libraries',
]
)
|
Allow AWS client against non-https servers
I want to test my application against a "fake" local S3. It is not running HTTPS. This change allows me to specify a non-HTTPS connection by passing { protocol: 'http://' } to the client creation as an option.
|
/*
* client.js: Storage client for AWS S3
*
* (C) 2011 Nodejitsu Inc.
*
*/
var utile = require('utile'),
urlJoin = require('url-join'),
xml2js = require('xml2js'),
auth = require('../../../common/auth'),
amazon = require('../../client');
var Client = exports.Client = function (options) {
this.serversUrl = 's3.amazonaws.com';
amazon.Client.call(this, options);
utile.mixin(this, require('./containers'));
utile.mixin(this, require('./files'));
this.before.push(auth.amazon.headersSignature);
};
utile.inherits(Client, amazon.Client);
Client.prototype._xmlRequest = function query(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
return this._request(options, function (err, body, res) {
if (err) {
return callback(err);
}
var parser = new xml2js.Parser();
parser.parseString(body || '', function (err, data) {
return err
? callback(err)
: callback(null, data, res);
});
});
};
Client.prototype._getUrl = function (options) {
options = options || {};
if (typeof options === 'string') {
return urlJoin(this.protocol + this.serversUrl, options);
}
return urlJoin(this.protocol +
(options.container ? options.container + '.' : '') +
this.serversUrl, options.path);
};
|
/*
* client.js: Storage client for AWS S3
*
* (C) 2011 Nodejitsu Inc.
*
*/
var utile = require('utile'),
urlJoin = require('url-join'),
xml2js = require('xml2js'),
auth = require('../../../common/auth'),
amazon = require('../../client');
var Client = exports.Client = function (options) {
this.serversUrl = 's3.amazonaws.com';
amazon.Client.call(this, options);
utile.mixin(this, require('./containers'));
utile.mixin(this, require('./files'));
this.before.push(auth.amazon.headersSignature);
};
utile.inherits(Client, amazon.Client);
Client.prototype._xmlRequest = function query(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
return this._request(options, function (err, body, res) {
if (err) {
return callback(err);
}
var parser = new xml2js.Parser();
parser.parseString(body || '', function (err, data) {
return err
? callback(err)
: callback(null, data, res);
});
});
};
Client.prototype._getUrl = function (options) {
options = options || {};
if (typeof options === 'string') {
return urlJoin('https://' + this.serversUrl, options);
}
return urlJoin('https://' +
(options.container ? options.container + '.' : '') +
this.serversUrl, options.path);
};
|
Fix audit for cash flow
|
package ee.tuleva.onboarding.audit;
import ee.tuleva.onboarding.auth.principal.Person;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
@RequiredArgsConstructor
public class AuditServiceMonitor {
private final AuditEventPublisher auditEventPublisher;
@Before("execution(* ee.tuleva.onboarding.account.AccountStatementService.getAccountStatement(..)) && args(person)")
public void logServiceAccess(Person person) {
auditEventPublisher.publish(person.getPersonalCode(), AuditEventType.GET_ACCOUNT_STATEMENT);
}
@Before("execution(* ee.tuleva.onboarding.comparisons.overview.EpisAccountOverviewProvider.getAccountOverview(..)) && args(person, ..)")
public void logCashFlowAccess(Person person) {
auditEventPublisher.publish(person.getPersonalCode(), AuditEventType.GET_CASH_FLOWS);
}
}
|
package ee.tuleva.onboarding.audit;
import ee.tuleva.onboarding.auth.principal.Person;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
@RequiredArgsConstructor
public class AuditServiceMonitor {
private final AuditEventPublisher auditEventPublisher;
@Before("execution(* ee.tuleva.onboarding.account.AccountStatementService.getAccountStatement(..)) && args(person)")
public void logServiceAccess(Person person) {
auditEventPublisher.publish(person.getPersonalCode(), AuditEventType.GET_ACCOUNT_STATEMENT);
}
@Before("execution(* ee.tuleva.onboarding.comparisons.overview.EpisAccountOverviewProvider.getAccountOverview(..)) && args(person)")
public void logCashFlowAccess(Person person) {
auditEventPublisher.publish(person.getPersonalCode(), AuditEventType.GET_CASH_FLOWS);
}
}
|
Fix typo in command description
|
<?php
namespace Command\Zray;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\NullOutput;
class Enable extends Zray
{
protected function configure()
{
$this->setName('zray:enable')
->setDescription('Enable Zend Server Z-Ray');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
parent::execute($input, $output);
$files = \Helper\Ini::findIniFiles($this->_ini_files);
foreach($files as $file) {
`sudo sed -i 's#^; zend_extension=#zend_extension=#' $file`;
}
$this->getApplication()->find('server:restart')->run(new ArrayInput(array('command' => 'server:restart', 'service' => array('apache'))), new NullOutput());
$output->writeln('Zend Server Z-Ray has been enabled');
}
}
|
<?php
namespace Command\Zray;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\NullOutput;
class Enable extends Zray
{
protected function configure()
{
$this->setName('zray:enable')
->setDescription('Enable Xdebug');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
parent::execute($input, $output);
$files = \Helper\Ini::findIniFiles($this->_ini_files);
foreach($files as $file) {
`sudo sed -i 's#^; zend_extension=#zend_extension=#' $file`;
}
$this->getApplication()->find('server:restart')->run(new ArrayInput(array('command' => 'server:restart', 'service' => array('apache'))), new NullOutput());
$output->writeln('Zend Server Z-Ray has been enabled');
}
}
|
Make sure template paths are resolved
|
var nodePath = require('path');
var fs = require('fs');
var Module = require('module').Module;
var raptorTemplatesCompiler = require('../../compiler');
var cwd = process.cwd();
function loadSource(templatePath, compiledSrc) {
var templateModulePath = templatePath + '.js';
var templateModule = new Module(templateModulePath, module);
templateModule.paths = Module._nodeModulePaths(nodePath.dirname(templateModulePath));
templateModule.filename = templateModulePath;
templateModule._compile(
compiledSrc,
templateModulePath);
return templateModule.exports;
}
module.exports = function load(templatePath) {
templatePath = nodePath.resolve(cwd, templatePath);
var targetFile = templatePath + '.js';
var compiler = raptorTemplatesCompiler.createCompiler(templatePath);
var isUpToDate = compiler.checkUpToDate(templatePath, targetFile);
if (isUpToDate) {
return require(targetFile);
}
var templateSrc = fs.readFileSync(templatePath, {encoding: 'utf8'});
var compiledSrc = compiler.compile(templateSrc);
// console.log('Compiled code for "' + templatePath + '":\n' + compiledSrc);
fs.writeFileSync(targetFile, compiledSrc, {encoding: 'utf8'});
return require(targetFile);
};
module.exports.loadSource = loadSource;
|
var nodePath = require('path');
var fs = require('fs');
var Module = require('module').Module;
var raptorTemplatesCompiler = require('../../compiler');
function loadSource(templatePath, compiledSrc) {
var templateModulePath = templatePath + '.js';
var templateModule = new Module(templateModulePath, module);
templateModule.paths = Module._nodeModulePaths(nodePath.dirname(templateModulePath));
templateModule.filename = templateModulePath;
templateModule._compile(
compiledSrc,
templateModulePath);
return templateModule.exports;
}
module.exports = function load(templatePath) {
var targetFile = templatePath + '.js';
var compiler = raptorTemplatesCompiler.createCompiler(templatePath);
var isUpToDate = compiler.checkUpToDate(templatePath, targetFile);
if (isUpToDate) {
return require(targetFile);
}
var templateSrc = fs.readFileSync(templatePath, {encoding: 'utf8'});
var compiledSrc = compiler.compile(templateSrc);
// console.log('Compiled code for "' + templatePath + '":\n' + compiledSrc);
fs.writeFileSync(targetFile, compiledSrc, {encoding: 'utf8'});
return require(targetFile);
};
module.exports.loadSource = loadSource;
|
Remove pointer problems by making shallow copy before parsing schema
|
import {fields} from './elements/index';
/**
* Parse an object into a {@link Field}.
* @param {String} id The ID for the field.
* @param {Object} obj The parameters for the field.
* @param {Field} [parent] The parent of the new field.
* @return {Field} The field created from the given data.
*/
export function parseJSON(id, obj, parent = undefined) {
// Create shallow copy of object to avoid unwanted pointer-like things.
obj = Object.assign({}, obj);
const createdObj = new fields[obj.type]();
if (obj.type === 'object') {
for (const [key, field] of Object.entries(obj.children)) {
obj.children[key] = parseJSON(key, field, createdObj);
}
if (obj.legendChildren) {
for (const [key, field] of Object.entries(obj.legendChildren)) {
obj.legendChildren[key] = parseJSON(key, field, createdObj);
}
}
} else if (obj.type === 'array') {
obj.item = parseJSON(obj.item.id, obj.item, createdObj);
}
obj.parent = parent;
return createdObj.init(id, obj);
}
|
import {fields} from './elements/index';
/**
* Parse an object into a {@link Field}.
* @param {String} id The ID for the field.
* @param {Object} obj The parameters for the field.
* @param {Field} [parent] The parent of the new field.
* @return {Field} The field created from the given data.
*/
export function parseJSON(id, obj, parent = undefined) {
const createdObj = new fields[obj.type]();
if (obj.type === 'object') {
for (const [key, field] of Object.entries(obj.children)) {
obj.children[key] = parseJSON(key, field, createdObj);
}
if (obj.legendChildren) {
for (const [key, field] of Object.entries(obj.legendChildren)) {
obj.legendChildren[key] = parseJSON(key, field, createdObj);
}
}
} else if (obj.type === 'array') {
obj.item = parseJSON(obj.item.id, obj.item, createdObj);
}
obj.parent = parent;
return createdObj.init(id, obj);
}
|
[test] Add `deviceName` field for Android
|
'use strict';
const sauceBrowsers = require('sauce-browsers');
const run = require('sauce-test');
const path = require('path');
const pkg = require('../package');
const platforms = sauceBrowsers([
{ name: 'android', version: ['oldest', 'latest'] },
{ name: 'chrome', version: ['oldest', 'latest'] },
{ name: 'firefox', version: ['oldest', 'latest'] },
{ name: 'internet explorer', version: 'oldest..latest' },
{ name: 'iphone', version: ['oldest', 'latest'] },
{ name: 'opera', version: 'oldest..latest' },
{ name: 'safari', version: 'oldest..latest' },
{ name: 'microsoftedge', version: 'oldest..latest' }
]).then((platforms) => {
return platforms.map((platform) => {
const ret = {
browserName: platform.api_name,
version: platform.short_version,
platform: platform.os
};
if (ret.browserName === 'android') ret.deviceName = platform.long_name;
return ret;
});
});
run(path.join(__dirname, 'test.js'), 'saucelabs', {
html: path.join(__dirname, 'index.html'),
accessKey: process.env.SAUCE_ACCESS_KEY,
username: process.env.SAUCE_USERNAME,
browserify: true,
disableSSL: true,
name: pkg.name,
parallel: 5,
platforms
}).done((results) => {
if (!results.passed) process.exit(1);
});
|
'use strict';
const sauceBrowsers = require('sauce-browsers');
const run = require('sauce-test');
const path = require('path');
const pkg = require('../package');
const platforms = sauceBrowsers([
{ name: 'android', version: ['oldest', 'latest'] },
{ name: 'chrome', version: ['oldest', 'latest'] },
{ name: 'firefox', version: ['oldest', 'latest'] },
{ name: 'internet explorer', version: 'oldest..latest' },
{ name: 'iphone', version: ['oldest', 'latest'] },
{ name: 'opera', version: 'oldest..latest' },
{ name: 'safari', version: 'oldest..latest' },
{ name: 'microsoftedge', version: 'oldest..latest' }
]).then((platforms) => {
return platforms.map((platform) => {
return {
browserName: platform.api_name,
version: platform.short_version,
platform: platform.os
};
});
});
run(path.join(__dirname, 'test.js'), 'saucelabs', {
html: path.join(__dirname, 'index.html'),
accessKey: process.env.SAUCE_ACCESS_KEY,
username: process.env.SAUCE_USERNAME,
browserify: true,
disableSSL: true,
name: pkg.name,
parallel: 5,
platforms
}).done((results) => {
if (!results.passed) process.exit(1);
});
|
Fix regression when setting custom attributes on DOM elements
|
var $ = require('jquery');
var _ = require('./utils.js');
// When passed to the template evaluator,
// its render method will create actual DOM elements
var DOMInterface = function() {
return {
createFragment: function() {
return document.createDocumentFragment();
},
createDOMElement: function(tag, id, classes, attributes) {
var elem = document.createElement(tag);
if(id) elem.id = id;
if(classes && classes.length) elem.className = classes.join(' ');
// elem = $(elem);
_.each(attributes, function(value, key) {
// if(['checked', 'selected', 'disabled', 'readonly', 'multiple', 'defer', 'declare', 'noresize'].indexOf(key) != -1) {
// } else {
elem.setAttribute(key, value);
// }
// elem[key] = value;
// elem.attr(key, value);
});
return elem;
},
createTextNode: function(text) {
return document.createTextNode(text);
}
};
};
module.exports = DOMInterface;
|
var $ = require('jquery');
var _ = require('./utils.js');
// When passed to the template evaluator,
// its render method will create actual DOM elements
var DOMInterface = function() {
return {
createFragment: function() {
return document.createDocumentFragment();
},
createDOMElement: function(tag, id, classes, attributes) {
var elem = document.createElement(tag);
if(id) elem.id = id;
if(classes && classes.length) elem.className = classes.join(' ');
// elem = $(elem);
_.each(attributes, function(value, key) {
// if(['checked', 'selected', 'disabled', 'readonly', 'multiple', 'defer', 'declare', 'noresize'].indexOf(key) != -1) {
// } else {
// elem.setAttribute(key, value);
// }
elem[key] = value;
// elem.attr(key, value);
});
return elem;
},
createTextNode: function(text) {
return document.createTextNode(text);
}
};
};
module.exports = DOMInterface;
|
Rewrite to use jquery svg
|
define([
'jquery',
'jquerySvgDom',
'underscore',
'backbone',
'views/KeyView',
'router',
'text!/../images/piano.svg'
], function ($, svgDom, _, Backbone, KeyView, Router, KeyboardTemplate) {
var KeyboardView = Backbone.View.extend({
initialize: function (options) {
this.listenTo(this.model, 'change', this.updateNotes);
},
events: {
'click': 'toggleSelect'
},
render: function () {
this.$el.html(KeyboardTemplate);
return this;
},
toggleSelect: function (e) {
$(e.target).toggleClass('selected');
this.updateNotes();
},
updateNotes: function(){
var notes = $('svg .selected').map(function(index, elem) {
return parseInt($(elem).attr('id'));
}).toArray();
this.model.set('notes', notes);
}
});
return KeyboardView;
});
|
define([
'jquery',
'underscore',
'backbone',
'views/KeyView',
'router'
], function ($, _, Backbone, KeyView, Router) {
var KeyboardView = Backbone.View.extend({
el: $('#keyboard'),
initialize: function (options) {
var self = this;
this.router = options.router;
$('#keyboard > .key').each(function (note) {
new KeyView({
el: $('#' + note)[0],
model: self.model
});
});
this.listenTo(this.model, 'change', this.render);
},
render: function () {
var self = this;
$('.selected').each(function (index, note) {
self.removeClass($(note), 'selected');
});
var notes = this.model.get('notes');
notes.forEach(function (note) {
self.addClass($('#' + note), 'selected');
});
return this;
},
removeClass: function (element, className) {
var currentClass = element.attr('class');
element.attr('class', currentClass.split(className)[0]);
},
addClass: function (element, className) {
var currentClass = element.attr('class');
element.attr('class', currentClass + ' ' + className);
}
});
return KeyboardView;
});
|
Load app view as default
|
import * as Backbone from 'backbone';
import Items from '../collections/items';
import SearchBoxView from '../views/searchBox-view';
import SearchResultsView from '../views/searchResults-view';
import AppView from '../views/app-view';
import DocumentSet from '../helpers/search';
import dispatcher from '../helpers/dispatcher';
class AppRouter extends Backbone.Router {
get routes() {
return {
'': 'loadDefault',
'search/(?*queryString)': 'showSearchResults'
};
}
initialize() {
this.listenTo(dispatcher, 'router:go', this.go);
}
go(route) {
this.navigate(route, {trigger: true});
}
loadDefault() {
new AppView();
}
showSearchResults(queryString) {
let q = queryString.substring(2);
DocumentSet.search(q).then(function(result) {
let currentDocuments = new DocumentSet(result).documents;
let docCollection = new Items(currentDocuments);
new SearchResultsView({collection: docCollection}).render();
});
}
}
export default AppRouter;
|
import * as Backbone from 'backbone';
import Items from '../collections/items';
import SearchBoxView from '../views/searchBox-view';
import SearchResultsView from '../views/searchResults-view';
import DocumentSet from '../helpers/search';
import dispatcher from '../helpers/dispatcher';
class AppRouter extends Backbone.Router {
get routes() {
return {
'': 'loadDefault',
'search/(?*queryString)': 'showSearchResults'
};
}
initialize() {
this.listenTo(dispatcher, 'router:go', this.go);
}
go(route) {
this.navigate(route, {trigger: true});
}
loadDefault() {
new SearchBoxView();
}
showSearchResults(queryString) {
let q = queryString.substring(2);
DocumentSet.search(q).then(function(result) {
let currentDocuments = new DocumentSet(result).documents;
let docCollection = new Items(currentDocuments);
new SearchResultsView({collection: docCollection}).render();
});
}
}
export default AppRouter;
|
Clean up to reference correct names of classes and related methods
|
<?php
/**
* mbc-transactional-digest
*
* Collect transactional campaign sign up message requests in a certain time period and
* compose a single digest message request.
*/
date_default_timezone_set('America/New_York');
define('CONFIG_PATH', __DIR__ . '/messagebroker-config');
// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\ MBC_TransactionalDigest\MBC_TransactionalDigest_Controller;
// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-logging-gateway.config.inc';
// Kick off
echo '------- mbc-transactional-digest START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;
$mb = $mbConfig->getProperty('messageBroker');
$mb->consumeMessage(array(new MBC_TransactionalDigest_Controller(), 'consumeTransactionalDigestQueue'));
echo '------- mbc-transactional-digest END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;
|
<?php
/**
* mbc-transactional-digest
*
* Collect user .
*/
date_default_timezone_set('America/New_York');
define('CONFIG_PATH', __DIR__ . '/messagebroker-config');
// The number of messages for the consumer to reserve with each callback
// See consumeMwessage for further details.
// Necessary for parallel processing when more than one consumer is running on the same queue.
define('QOS_SIZE', 1);
// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\MBC_LoggingGateway\MBC_LoggingGateway_Consumer;
// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-logging-gateway.config.inc';
// Kick off
echo '------- mbc-impoert-logging START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;
$mb = $mbConfig->getProperty('messageBroker');
$mb->consumeMessage(array(new MBC_LoggingGateway_Consumer(), 'consumeLoggingGatewayQueue'), QOS_SIZE);
echo '------- mbc-impoert-logging END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;
|
Fix bug with missing iri
|
/*
* VowlThing.java
*
*/
package de.uni_stuttgart.vis.vowl.owl2vowl.model.entities.nodes.classes;
import de.uni_stuttgart.vis.vowl.owl2vowl.constants.NodeType;
import de.uni_stuttgart.vis.vowl.owl2vowl.constants.Standard_Iris;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.annotation.Annotation;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.visitor.VowlElementVisitor;
import org.semanticweb.owlapi.model.IRI;
/**
*
*/
public class VowlThing extends AbstractClass {
public static final String THING_IRI = Standard_Iris.OWL_THING_CLASS_URI;
public static final IRI GENERIC_THING_IRI = IRI.create(THING_IRI);
protected VowlThing(IRI iri, String type) {
super(iri, type);
}
public VowlThing(IRI iri) {
super(iri, NodeType.TYPE_THING);
getAnnotations().addLabel(new Annotation("label", "Thing"));
}
@Override
public void accept(VowlElementVisitor visitor) {
visitor.visit(this);
}
}
|
/*
* VowlThing.java
*
*/
package de.uni_stuttgart.vis.vowl.owl2vowl.model.entities.nodes.classes;
import de.uni_stuttgart.vis.vowl.owl2vowl.constants.NodeType;
import de.uni_stuttgart.vis.vowl.owl2vowl.constants.Standard_Iris;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.annotation.Annotation;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.visitor.VowlElementVisitor;
import org.semanticweb.owlapi.model.IRI;
/**
*
*/
public class VowlThing extends AbstractClass {
public static final String THING_IRI = Standard_Iris.OWL_THING_CLASS_URI;
protected VowlThing(IRI iri, String type) {
super(iri, type);
}
public VowlThing(IRI iri) {
super(iri, NodeType.TYPE_THING);
getAnnotations().addLabel(new Annotation("label", "Thing"));
}
@Override
public void accept(VowlElementVisitor visitor) {
visitor.visit(this);
}
}
|
Use DecimalFormat to replace DecimalFormat because of DecimalFormat will add a comma in formatted result when value greater than 1000.
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.core.util;
import java.math.RoundingMode;
import java.text.DecimalFormat;
/**
* @author peng-yongsheng
*/
public class NumberFormatUtils {
public static Double rateNumberFormat(Double rate) {
DecimalFormat decimalFormat = new DecimalFormat("#.00");
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
Double formattedRate = Double.valueOf(decimalFormat.format(rate));
return Double.valueOf(formattedRate);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.core.util;
import java.math.RoundingMode;
import java.text.NumberFormat;
/**
* @author peng-yongsheng
*/
public class NumberFormatUtils {
public static Double rateNumberFormat(Double rate) {
NumberFormat rateNumberFormat = NumberFormat.getNumberInstance();
rateNumberFormat.setMaximumFractionDigits(2);
rateNumberFormat.setRoundingMode(RoundingMode.HALF_UP);
Double formattedRate = Double.valueOf(rateNumberFormat.format(rate));
return Double.valueOf(formattedRate);
}
}
|
Add parameter to service controller example
|
<?php
require __DIR__.'/../vendor/autoload.php';
class HelloController
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function worldAction($request)
{
return "Hello, I'm {$this->name}.\n";
}
}
$container = Yolo\createContainer(
[
'hello.name' => 'the amazing app',
],
[
new Yolo\DependencyInjection\ServiceControllerExtension(),
new Yolo\DependencyInjection\CallableExtension(
'controller',
function ($configs, $container) {
$container->register('hello.controller', 'HelloController')
->addArgument('%hello.name%');
}
),
]
);
$app = new Yolo\Application($container);
$app->get('/', 'hello.controller:worldAction');
$app->run();
|
<?php
require __DIR__.'/../vendor/autoload.php';
class HelloController
{
public function worldAction($request)
{
return "Hallo welt, got swag yo!\n";
}
}
$container = Yolo\createContainer(
[
'debug' => true,
],
[
new Yolo\DependencyInjection\MonologExtension(),
new Yolo\DependencyInjection\ServiceControllerExtension(),
new Yolo\DependencyInjection\CallableExtension(
'controller',
function ($configs, $container) {
$container->register('hello.controller', 'HelloController');
}
),
]
);
$app = new Yolo\Application($container);
$app->get('/', 'hello.controller:worldAction');
$app->run();
|
Include mock classes in test class file
|
<?php
/**
* Definition of class DICTest
*
* @copyright 2015-today Justso GmbH
* @author j.schirrmacher@justso.de
* @package justso\justapi\test
*/
namespace justso\justapi\test;
use justso\justapi\Bootstrap;
use justso\justapi\DependencyContainer;
use justso\justapi\testutil\FileSystemSandbox;
require (dirname(__DIR__) . '/testutil/MockClass.php');
require (dirname(__DIR__) . '/testutil/MockClass2.php');
/**
* Class DICTest
*
* @package justso\justapi\test
*/
class DICTest extends \PHPUnit_Framework_TestCase
{
public function testInstantiation()
{
$config = array('environments' => array('test' => array('approot' => '/test')));
Bootstrap::getInstance()->setTestConfiguration('/test', $config);
$fs = new FileSystemSandbox();
$fs->copyFromRealFS(dirname(__DIR__) . '/testutil/TestDICConfig.php', '/test/conf/dependencies.php');
$env = new DependencyContainer($fs);
$object = $env->newInstanceOf('TestInterface');
$this->assertInstanceOf('MockClass', $object);
}
}
|
<?php
/**
* Definition of class DICTest
*
* @copyright 2015-today Justso GmbH
* @author j.schirrmacher@justso.de
* @package justso\justapi\test
*/
namespace justso\justapi\test;
use justso\justapi\Bootstrap;
use justso\justapi\DependencyContainer;
use justso\justapi\testutil\FileSystemSandbox;
/**
* Class DICTest
*
* @package justso\justapi\test
*/
class DICTest extends \PHPUnit_Framework_TestCase
{
public function testInstantiation()
{
$config = array('environments' => array('test' => array('approot' => '/test')));
Bootstrap::getInstance()->setTestConfiguration('/test', $config);
$fs = new FileSystemSandbox();
$fs->copyFromRealFS(dirname(__DIR__) . '/testutil/TestDICConfig.php', '/test/conf/dependencies.php');
$env = new DependencyContainer($fs);
$object = $env->newInstanceOf('TestInterface');
$this->assertInstanceOf('MockClass', $object);
}
}
|
Store date format into a constant
|
<?php
/**
* Created by Pierre-Henry Soria
*/
namespace PFBC\Validation;
use PH7\Framework\Date\CDateTime;
use PH7\Framework\Mvc\Model\DbConfig;
class BirthDate extends \PFBC\Validation
{
const DATE_PATTERN = 'm/d/Y';
/** @var int */
protected $iMin;
/** @var int */
protected $iMax;
public function __construct()
{
parent::__construct();
$this->iMin = DbConfig::getSetting('minAgeRegistration');
$this->iMax = DbConfig::getSetting('maxAgeRegistration');
$this->message = t('You must be from %0% to %1% years old to join the service.', $this->iMin, $this->iMax);
}
/**
* @param string $sDate
*
* @return bool
*/
public function isValid($sDate)
{
if ($this->isNotApplicable($sDate)) {
return true;
}
$sDate = (new CDateTime)->get($sDate)->date(self::DATE_PATTERN);
return $this->oValidate->birthDate($sDate, $this->iMin, $this->iMax);
}
}
|
<?php
/**
* Created by Pierre-Henry Soria
*/
namespace PFBC\Validation;
use PH7\Framework\Date\CDateTime;
use PH7\Framework\Mvc\Model\DbConfig;
class BirthDate extends \PFBC\Validation
{
/** @var int */
protected $iMin;
/** @var int */
protected $iMax;
public function __construct()
{
parent::__construct();
$this->iMin = DbConfig::getSetting('minAgeRegistration');
$this->iMax = DbConfig::getSetting('maxAgeRegistration');
$this->message = t('You must be from %0% to %1% years old to join the service.', $this->iMin, $this->iMax);
}
/**
* @param string $sDate
*
* @return bool
*/
public function isValid($sDate)
{
if ($this->isNotApplicable($sDate)) {
return true;
}
$sDate = (new CDateTime)->get($sDate)->date('m/d/Y');
return $this->oValidate->birthDate($sDate, $this->iMin, $this->iMax);
}
}
|
Add a class alias for the legacy Extensions class
|
<?php
/**
* Autoloaded file to handle deprecation such as class aliases.
*
* NOTE:
* If for any reason arrays are required in this file, only ever use array()
* syntax to prevent breakage on PHP < 5.4 and allow the legacy warnings.
*/
// Class aliases for BC
class_alias('\Bolt\Asset\Target', '\Bolt\Extensions\Snippets\Location');
class_alias('\Bolt\Menu\Menu', '\Bolt\Helpers\Menu');
class_alias('\Bolt\Menu\MenuBuilder', '\Bolt\Helpers\MenuBuilder');
class_alias('\Bolt\Legacy\BaseExtension', '\Bolt\BaseExtension');
class_alias('\Bolt\Extension\Manager', '\Bolt\Extensions');
class_alias('\Bolt\Legacy\Content', '\Bolt\Content');
class_alias('\Bolt\Legacy\Storage', '\Bolt\Storage');
class_alias('\Bolt\Storage\Field\Base', '\Bolt\Field\Base');
class_alias('\Bolt\Storage\Field\FieldInterface', '\Bolt\Field\FieldInterface');
class_alias('\Bolt\Storage\Field\Manager', '\Bolt\Field\Manager');
|
<?php
/**
* Autoloaded file to handle deprecation such as class aliases.
*
* NOTE:
* If for any reason arrays are required in this file, only ever use array()
* syntax to prevent breakage on PHP < 5.4 and allow the legacy warnings.
*/
// Class aliases for BC
class_alias('\Bolt\Asset\Target', '\Bolt\Extensions\Snippets\Location');
class_alias('\Bolt\Menu\Menu', '\Bolt\Helpers\Menu');
class_alias('\Bolt\Menu\MenuBuilder', '\Bolt\Helpers\MenuBuilder');
class_alias('\Bolt\Legacy\BaseExtension', '\Bolt\BaseExtension');
class_alias('\Bolt\Legacy\Content', '\Bolt\Content');
class_alias('\Bolt\Legacy\Storage', '\Bolt\Storage');
class_alias('\Bolt\Storage\Field\Base', '\Bolt\Field\Base');
class_alias('\Bolt\Storage\Field\FieldInterface', '\Bolt\Field\FieldInterface');
class_alias('\Bolt\Storage\Field\Manager', '\Bolt\Field\Manager');
|
Allow attribute to be customized in TagRegistered
|
"""
meta.py
Some useful metaclasses.
"""
from __future__ import unicode_literals
class LeafClassesMeta(type):
"""
A metaclass for classes that keeps track of all of them that
aren't base classes.
"""
_leaf_classes = set()
def __init__(cls, name, bases, attrs):
if not hasattr(cls, '_leaf_classes'):
cls._leaf_classes = set()
leaf_classes = getattr(cls, '_leaf_classes')
leaf_classes.add(cls)
# remove any base classes
leaf_classes -= set(bases)
class TagRegistered(type):
"""
As classes of this metaclass are created, they keep a registry in the
base class of all classes by a class attribute, indicated by attr_name.
"""
attr_name = 'tag'
def __init__(cls, name, bases, namespace):
super(TagRegistered, cls).__init__(name, bases, namespace)
if not hasattr(cls, '_registry'):
cls._registry = {}
meta = cls.__class__
attr = getattr(cls, meta.attr_name, None)
if attr:
cls._registry[attr] = cls
|
"""
meta.py
Some useful metaclasses.
"""
from __future__ import unicode_literals
class LeafClassesMeta(type):
"""
A metaclass for classes that keeps track of all of them that
aren't base classes.
"""
_leaf_classes = set()
def __init__(cls, name, bases, attrs):
if not hasattr(cls, '_leaf_classes'):
cls._leaf_classes = set()
leaf_classes = getattr(cls, '_leaf_classes')
leaf_classes.add(cls)
# remove any base classes
leaf_classes -= set(bases)
class TagRegistered(type):
"""
As classes of this metaclass are created, they keep a registry in the
base class of all classes by a class attribute, 'tag'.
"""
def __init__(cls, name, bases, namespace):
super(TagRegistered, cls).__init__(name, bases, namespace)
if not hasattr(cls, '_registry'):
cls._registry = {}
attr = getattr(cls, 'tag', None)
if attr:
cls._registry[attr] = cls
|
Use the version number in pyproject.toml as the single source of truth
From Python 3.8 on we can use importlib.metadata.version('package_name')
to get the current version.
|
"""Rename audio files from metadata tags."""
import sys
from importlib import metadata
from .args import fields, parse_args
from .batch import Batch
from .job import Job
from .message import job_info, stats
fields
__version__: str = metadata.version('audiorename')
def execute(*argv: str):
"""Main function
:param list argv: The command line arguments specified as a list: e. g
:code:`['--dry-run', '.']`
"""
job = None
try:
args = parse_args(argv)
job = Job(args)
job.stats.counter.reset()
job.stats.timer.start()
if job.cli_output.job_info:
job_info(job)
if job.rename.dry_run:
job.msg.output('Dry run')
batch = Batch(job)
batch.execute()
job.stats.timer.stop()
if job.cli_output.stats:
stats(job)
except KeyboardInterrupt:
if job:
job.stats.timer.stop()
if job.cli_output.stats:
stats(job)
sys.exit(0)
|
"""Rename audio files from metadata tags."""
import sys
from .args import fields, parse_args
from .batch import Batch
from .job import Job
from .message import job_info, stats
fields
__version__: str = '0.0.0'
def execute(*argv: str):
"""Main function
:param list argv: The command line arguments specified as a list: e. g
:code:`['--dry-run', '.']`
"""
job = None
try:
args = parse_args(argv)
job = Job(args)
job.stats.counter.reset()
job.stats.timer.start()
if job.cli_output.job_info:
job_info(job)
if job.rename.dry_run:
job.msg.output('Dry run')
batch = Batch(job)
batch.execute()
job.stats.timer.stop()
if job.cli_output.stats:
stats(job)
except KeyboardInterrupt:
if job:
job.stats.timer.stop()
if job.cli_output.stats:
stats(job)
sys.exit(0)
|
Fix activation code to string
|
<?php namespace Maatwebsite\Usher\Domain\Users\Activations;
use Doctrine\ORM\Mapping as ORM;
use Maatwebsite\Usher\Services\CodeGenerator;
use Maatwebsite\Usher\Domain\Shared\Embeddables\Date;
use Maatwebsite\Usher\Contracts\Users\Activiations\ActivationCode as ActivationCodeInterface;
/**
* @ORM\Embeddable
*/
class ActivationCode extends Date implements ActivationCodeInterface
{
/**
* @ORM\Column(type="string", name="activation_code", unique=true)
*/
protected $code;
/**
* @param string $code
*/
public function __construct($code)
{
$this->code = $code;
}
/**
* @return mixed
*/
public function getCode()
{
return $this->code;
}
/**
* @param mixed $code
*/
public function setCode($code)
{
$this->code = $code;
}
/**
* @return ActivationCode
*/
public static function generate()
{
return new static(
CodeGenerator::make()
);
}
/**
* @return string
*/
public function toString()
{
return (string) $this->getCode();
}
}
|
<?php namespace Maatwebsite\Usher\Domain\Users\Activations;
use Doctrine\ORM\Mapping as ORM;
use Maatwebsite\Usher\Services\CodeGenerator;
use Maatwebsite\Usher\Domain\Shared\Embeddables\Date;
use Maatwebsite\Usher\Contracts\Users\Activiations\ActivationCode as ActivationCodeInterface;
/**
* @ORM\Embeddable
*/
class ActivationCode extends Date implements ActivationCodeInterface
{
/**
* @ORM\Column(type="string", name="activation_code", unique=true)
*/
protected $code;
/**
* @param string $code
*/
public function __construct($code)
{
$this->code = $code;
}
/**
* @return mixed
*/
public function getCode()
{
return $this->code;
}
/**
* @param mixed $code
*/
public function setCode($code)
{
$this->code = $code;
}
/**
* @return ActivationCode
*/
public static function generate()
{
return new static(
CodeGenerator::make()
);
}
/**
* @return string
*/
public function toString()
{
return (string) $this->getToken();
}
}
|
Use built-in _format to enable xml output
|
<?php
namespace Kunstmaan\SitemapBundle\Controller;
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionMap;
use Kunstmaan\NodeBundle\Helper\NodeMenu;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class SitemapController extends Controller
{
/**
* Use the mode parameter to select in which mode the sitemap should be generated. At this moment only XML is supported
*
* @Route("/sitemap.{_format}", name="KunstmaanSitemapBundle_sitemap", requirements={"_format" = "xml"})
* @Template("KunstmaanSitemapBundle:Sitemap:view.xml.twig")
*
* @param $mode
*
* @return array
*/
public function sitemapAction()
{
$em = $this->getDoctrine()->getManager();
$locale = $this->getRequest()->getLocale();
$securityContext = $this->container->get('security.context');
$aclHelper = $this->container->get('kunstmaan_admin.acl.helper');
$nodeMenu = new NodeMenu($em, $securityContext, $aclHelper, $locale, null, PermissionMap::PERMISSION_VIEW, true, true);
return array(
'nodemenu' => $nodeMenu,
);
}
}
|
<?php
namespace Kunstmaan\SitemapBundle\Controller;
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionMap;
use Kunstmaan\NodeBundle\Helper\NodeMenu;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class SitemapController extends Controller
{
/**
* Use the mode parameter to select in which mode the sitemap should be generated. At this moment only XML is supported
*
* @Route("/sitemap.{mode}", name="KunstmaanSitemapBundle_sitemap")
* @Template("KunstmaanSitemapBundle:Sitemap:view.xml.twig")
*
* @param $mode
*
* @return array
*/
public function sitemapAction($mode)
{
$em = $this->getDoctrine()->getManager();
$locale = $this->getRequest()->getLocale();
$securityContext = $this->container->get('security.context');
$aclHelper = $this->container->get('kunstmaan_admin.acl.helper');
$nodeMenu = new NodeMenu($em, $securityContext, $aclHelper, $locale, null, PermissionMap::PERMISSION_VIEW, true, true);
return array(
'nodemenu' => $nodeMenu,
);
}
}
|
Update package info for `query` package
|
/*
* Copyright 2017, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* This package contains the API for working with queries and common queries for different storages.
*
* <p>The package is {@linkplain io.spine.annotation.Internal internal} to Spine code and should not
* be used outside of the library.
*/
@Internal
@ParametersAreNonnullByDefault
package io.spine.server.storage.jdbc.query;
import io.spine.annotation.Internal;
import javax.annotation.ParametersAreNonnullByDefault;
|
/*
* Copyright 2017, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* This package contains the types representing the queries to a relational Database.
*
* <p>The package is {@linkplain io.spine.annotation.Internal internal} to Spine code and should not
* be used outside of the library.
*/
@Internal
@ParametersAreNonnullByDefault
package io.spine.server.storage.jdbc.query;
import io.spine.annotation.Internal;
import javax.annotation.ParametersAreNonnullByDefault;
|
Add tmp dir to protractor-sauce
|
var fs = require('fs');
var specs = JSON.parse(fs.readFileSync('tests/end2end/specs.json'));
var browser_capabilities = JSON.parse(process.env.SELENIUM_BROWSER_CAPABILITIES);
browser_capabilities['name'] = 'GlobaLeaks-E2E';
browser_capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
browser_capabilities['build'] = process.env.TRAVIS_BUILD_NUMBER;
exports.config = {
framework: 'jasmine',
baseUrl: 'http://localhost:9000/',
troubleshoot: false,
directConnect: false,
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
capabilities: browser_capabilities,
params: {
'testFileDownload': false,
'verifyFileDownload': false,
'tmpDir': '/tmp/globaleaks-download',
},
specs: specs,
jasmineNodeOpts: {
isVerbose: true,
includeStackTrace: true,
defaultTimeoutInterval: 360000
}
};
|
var fs = require('fs');
var specs = JSON.parse(fs.readFileSync('tests/end2end/specs.json'));
var browser_capabilities = JSON.parse(process.env.SELENIUM_BROWSER_CAPABILITIES);
browser_capabilities['name'] = 'GlobaLeaks-E2E';
browser_capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
browser_capabilities['build'] = process.env.TRAVIS_BUILD_NUMBER;
exports.config = {
framework: 'jasmine',
baseUrl: 'http://localhost:9000/',
troubleshoot: false,
directConnect: false,
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
capabilities: browser_capabilities,
params: {
'testFileDownload': false,
'verifyFileDownload': false
},
specs: specs,
jasmineNodeOpts: {
isVerbose: true,
includeStackTrace: true,
defaultTimeoutInterval: 360000
}
};
|
Fix bug where loading dialog continues to show on invalid sessionID in URL
|
angular.module('dcs.controllers').controller('MainController', ['$scope', '$state', '$stateParams', 'session', '$timeout', '$mdDialog',
function($scope, $state, $stateParams, session, $timeout, $mdDialog)
{
$scope.init =
function()
{
if(typeof($stateParams["sessionID"]) !== 'string' || $stateParams["sessionID"].length != 30)
$state.go('upload');
$scope.initialLoad = true;
$mdDialog.show({
templateUrl: 'directives/loading.dialog.html',
parent: angular.element(document.body),
clickOutsideToClose:false
});
session.initialize($stateParams["sessionID"],
function(success)
{
if(!success)
$timeout(function()
{
$mdDialog.hide();
$state.go('upload');
});
else
{
$scope.dataLoaded = true;
$scope.$digest();
}
});
$scope.$on("firstLoad",
function()
{
$timeout(function()
{
$mdDialog.hide();
});
});
};
$scope.init();
}]);
|
angular.module('dcs.controllers').controller('MainController', ['$scope', '$state', '$stateParams', 'session', '$timeout', '$mdDialog',
function($scope, $state, $stateParams, session, $timeout, $mdDialog)
{
$scope.init =
function()
{
if(typeof($stateParams["sessionID"]) !== 'string' || $stateParams["sessionID"].length != 30)
$state.go('upload');
$scope.initialLoad = true;
$mdDialog.show({
templateUrl: 'directives/loading.dialog.html',
parent: angular.element(document.body),
clickOutsideToClose:false
});
session.initialize($stateParams["sessionID"],
function(success)
{
if(!success)
{
$timeout(function()
{
$mdDialog.hide();
});
$state.go('upload');
}
else
{
$scope.dataLoaded = true;
$scope.$digest();
}
});
$scope.$on("firstLoad",
function()
{
$timeout(function()
{
$mdDialog.hide();
});
});
};
$scope.init();
}]);
|
Bump to next development cycle
|
from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md')) as f:
jgo_long_description = f.read()
setup(
name='jgo',
version='0.1.1.dev0',
author='Philipp Hanslovsky, Curtis Rueden',
author_email='hanslovskyp@janelia.hhmi.org',
description='Launch Java code from Python and the CLI, installation-free.',
long_description=jgo_long_description,
long_description_content_type='text/markdown',
license='Public domain',
url='https://github.com/scijava/jgo',
packages=['jgo'],
entry_points={
'console_scripts': [
'jgo=jgo.jgo:jgo_main'
]
},
python_requires='>=3',
)
|
from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md')) as f:
jgo_long_description = f.read()
setup(
name='jgo',
version='0.1.0',
author='Philipp Hanslovsky, Curtis Rueden',
author_email='hanslovskyp@janelia.hhmi.org',
description='Launch Java code from Python and the CLI, installation-free.',
long_description=jgo_long_description,
long_description_content_type='text/markdown',
license='Public domain',
url='https://github.com/scijava/jgo',
packages=['jgo'],
entry_points={
'console_scripts': [
'jgo=jgo.jgo:jgo_main'
]
},
python_requires='>=3',
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.