text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
---|---|---|
Adjust post-stimulus waiting period setting | /**
* Settings configuration for jsPASAT
*/
var jsPASAT = {
// Pace of PASAT trial presentation
'TIMING_STIM_DISPLAY': 1000,
'TIMING_POST_STIM': 4000,
// Practice block stimuli
'PRACTICE_BLOCK_1_STIMULI': [9, 1, 3, 5, 2, 6],
'PRACTICE_BLOCK_2_STIMULI': [6, 4, 5, 7, 2, 8, 4, 5, 9, 3, 6, 9, 2, 7, 3, 8],
// Block
'TRIALS_PER_BLOCK': 15,
// Re-useable Likert scale labels
'LIKERT_SCALE_1': ["1<br>None", "2", "3", "4", "5", "6", "7<br>A Lot"],
'LIKERT_SCALE_2': [
"1<br>Significantly<br>Below Average",
"2",
"3",
"4<br>Average",
"5",
"6",
"7<br>Significantly<br>Above Average"
],
};
| /**
* Settings configuration for jsPASAT
*/
var jsPASAT = {
// Pace of PASAT trial presentation
'TIMING_STIM_DISPLAY': 1000,
'TIMING_POST_STIM': 3000,
// Practice block stimuli
'PRACTICE_BLOCK_1_STIMULI': [9, 1, 3, 5, 2, 6],
'PRACTICE_BLOCK_2_STIMULI': [6, 4, 5, 7, 2, 8, 4, 5, 9, 3, 6, 9, 2, 7, 3, 8],
// Block
'TRIALS_PER_BLOCK': 15,
// Re-useable Likert scale labels
'LIKERT_SCALE_1': ["1<br>None", "2", "3", "4", "5", "6", "7<br>A Lot"],
'LIKERT_SCALE_2': [
"1<br>Significantly<br>Below Average",
"2",
"3",
"4<br>Average",
"5",
"6",
"7<br>Significantly<br>Above Average"
],
};
|
Remove extra character from whitespace replacement | 'use strict';
/* Filters */
angular.module('myApp.filters', []).
filter('interpolate', ['version', function(version) {
return function(text) {
return String(text).replace(/\%VERSION\%/mg, version);
}
}])
.filter('mapUrl', function() {
return function(e) {
var str = "";
for (var i=0;i<e.length;i++) {
str += typeof e[i].name === 'undefined' ||
e[i].name.localeCompare('') === 0 ?
e[i].latitude + ',' + e[i].longitude + '%7C' :
e[i].name + '%7C';
}
str = str.replace(/ /g, '%20');
return str.replace(/%7C$/, '');
};
});
| 'use strict';
/* Filters */
angular.module('myApp.filters', []).
filter('interpolate', ['version', function(version) {
return function(text) {
return String(text).replace(/\%VERSION\%/mg, version);
}
}])
.filter('mapUrl', function() {
return function(e) {
var str = "";
for (var i=0;i<e.length;i++) {
str += typeof e[i].name === 'undefined' ||
e[i].name.localeCompare('') === 0 ?
e[i].latitude + ',' + e[i].longitude + '%7C' :
e[i].name + '%7C';
}
str = str.replace(/ /g, '%20C');
return str.replace(/%7C$/, '');
};
});
|
Connect <Header /> to the router to subscribe to location updates | import { connect } from 'react-redux';
import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';
import { loggedOut } from '~client/actions/login';
import { getLoggedIn } from '~client/selectors/app';
import { getUnsaved } from '~client/selectors/api';
import AppLogo from '~client/components/AppLogo';
import Navbar from '~client/components/Navbar';
const Header = ({ loggedIn, loadingApi, unsavedApi, onLogout }) => (
<div className="navbar">
<div className="inner">
<AppLogo loading={loadingApi} unsaved={unsavedApi} />
{loggedIn && <Navbar onLogout={onLogout} />}
</div>
</div>
);
Header.propTypes = {
loggedIn: PropTypes.bool.isRequired,
loadingApi: PropTypes.bool.isRequired,
unsavedApi: PropTypes.bool.isRequired,
onLogout: PropTypes.func.isRequired
};
const mapStateToProps = state => ({
loggedIn: getLoggedIn(state),
loadingApi: state.api.loading,
unsavedApi: getUnsaved(state)
});
const mapDispatchToProps = {
onLogout: loggedOut
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Header));
| import { connect } from 'react-redux';
import React from 'react';
import PropTypes from 'prop-types';
import { loggedOut } from '~client/actions/login';
import { getLoggedIn } from '~client/selectors/app';
import { getUnsaved } from '~client/selectors/api';
import AppLogo from '~client/components/AppLogo';
import Navbar from '~client/components/Navbar';
const Header = ({ loggedIn, loadingApi, unsavedApi, onLogout }) => (
<div className="navbar">
<div className="inner">
<AppLogo loading={loadingApi} unsaved={unsavedApi} />
{loggedIn && <Navbar onLogout={onLogout} />}
</div>
</div>
);
Header.propTypes = {
loggedIn: PropTypes.bool.isRequired,
loadingApi: PropTypes.bool.isRequired,
unsavedApi: PropTypes.bool.isRequired,
onLogout: PropTypes.func.isRequired
};
const mapStateToProps = state => ({
loggedIn: getLoggedIn(state),
loadingApi: state.api.loading,
unsavedApi: getUnsaved(state)
});
const mapDispatchToProps = {
onLogout: loggedOut
};
export default connect(mapStateToProps, mapDispatchToProps)(Header);
|
Add filters to snapshot preview | #!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var chalk = require('chalk')
var filter = process.argv[2]
function show (result) {
Object.keys(result).sort().reverse().forEach(file => {
var test = file.replace(/\.test\.js\.snap$/, '')
result[file].split('exports[`')
.filter(str => str.indexOf('// ') !== 0)
.filter(str => !filter || str.indexOf(filter) !== -1)
.forEach(str => {
if (str.trim().length === 0) return
var parts = str.replace(/"\s*`;\s*$/, '').split(/`] = `\s*"/)
process.stdout.write(
chalk.gray(`${ test } ${ parts[0].replace(/ 1$/, '') }:\n\n`))
process.stdout.write(parts[1])
})
})
}
fs.readdir(__dirname, (err, list) => {
if (err) throw err
var snaps = list.filter(i => /\.snap$/.test(i))
var result = { }
snaps.forEach(file => {
fs.readFile(path.join(__dirname, file), (err2, content) => {
if (err2) throw err2
result[file] = content.toString()
if (Object.keys(result).length === snaps.length) show(result)
})
})
})
| #!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var chalk = require('chalk')
function show (result) {
Object.keys(result).sort().reverse().forEach(file => {
var test = file.replace(/\.test\.js\.snap$/, '')
result[file].split('exports[`')
.filter(str => str.indexOf('// ') !== 0)
.forEach(str => {
if (str.trim().length === 0) return
var parts = str.replace(/"\s*`;\s*$/, '').split(/`] = `\s*"/)
process.stdout.write(
chalk.gray(`${ test } ${ parts[0].replace(/ 1$/, '') }:\n\n`))
process.stdout.write(parts[1])
})
})
}
fs.readdir(__dirname, (err, list) => {
if (err) throw err
var snaps = list.filter(i => /\.snap$/.test(i))
var result = { }
snaps.forEach(file => {
fs.readFile(path.join(__dirname, file), (err2, content) => {
if (err2) throw err2
result[file] = content.toString()
if (Object.keys(result).length === snaps.length) show(result)
})
})
})
|
Bz1178769: Fix JBDS import errors for greeter quickstart | /*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.quickstarts.greeter;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class Resources {
// Expose an entity manager using the resource producer pattern
@PersistenceContext
@Produces
private EntityManager em;
@Produces
public Logger getLogger(InjectionPoint ip) {
String category = ip.getMember().getDeclaringClass().getName();
return Logger.getLogger(category);
}
@Produces
@RequestScoped
public FacesContext getFacesContext() {
return FacesContext.getCurrentInstance();
}
}
| /*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.quickstarts.greeter;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class Resources {
// Expose an entity manager using the resource producer pattern
@SuppressWarnings("unused")
@PersistenceContext
@Produces
private EntityManager em;
@Produces
public Logger getLogger(InjectionPoint ip) {
String category = ip.getMember().getDeclaringClass().getName();
return Logger.getLogger(category);
}
@Produces
@RequestScoped
public FacesContext getFacesContext() {
return FacesContext.getCurrentInstance();
}
}
|
Fix a bad reference value in the Internal Note model. | var keystone = require('keystone'),
Types = keystone.Field.Types;
// Create model. Additional options allow menu name to be used what auto-generating URLs
var InternalNotes = new keystone.List('Internal Note', {
track: true,
autokey: { path: 'key', from: 'slug', unique: true },
defaultSort: 'date'
});
// Create fields
InternalNotes.add({
child: { type: Types.Relationship, label: 'child', ref: 'Child', initial: true, },
prospectiveParentOrFamily: { type: Types.Relationship, label: 'family', ref: 'Prospective Parent or Family', initial: true },
date: { type: Types.Text, label: 'note date', note: 'mm/dd/yyyy', required: true, noedit: true, initial: true, },
employee: { type: Types.Relationship, label: 'note creator', ref: 'User', required: true, noedit: true, initial: true, },
note: { type: Types.Textarea, label: 'note', required: true, initial: true, }
});
// Pre Save
InternalNotes.schema.pre('save', function(next) {
'use strict';
// generate an internal ID based on the current highest internal ID
// get the employee who is currently logged in and save ID to employee
// TODO: Assign a registration number if one isn't assigned
next();
});
// Define default columns in the admin interface and register the model
InternalNotes.defaultColumns = 'date, child, family, note';
InternalNotes.register(); | var keystone = require('keystone'),
Types = keystone.Field.Types;
// Create model. Additional options allow menu name to be used what auto-generating URLs
var InternalNotes = new keystone.List('Internal Note', {
track: true,
autokey: { path: 'key', from: 'slug', unique: true },
defaultSort: 'date'
});
// Create fields
InternalNotes.add({
child: { type: Types.Relationship, label: 'child', ref: 'Child', initial: true, },
family: { type: Types.Relationship, label: 'family', ref: 'Prospective Parent or Family', initial: true },
date: { type: Types.Text, label: 'note date', note: 'mm/dd/yyyy', required: true, noedit: true, initial: true, },
employee: { type: Types.Relationship, label: 'note creator', ref: 'User', required: true, noedit: true, initial: true, },
note: { type: Types.Textarea, label: 'note', required: true, initial: true, }
});
// Pre Save
InternalNotes.schema.pre('save', function(next) {
'use strict';
// generate an internal ID based on the current highest internal ID
// get the employee who is currently logged in and save ID to employee
// TODO: Assign a registration number if one isn't assigned
next();
});
// Define default columns in the admin interface and register the model
InternalNotes.defaultColumns = 'date, child, family, note';
InternalNotes.register(); |
Add debug console root logging handler. | # Case Conductor is a Test Case Management system.
# Copyright (C) 2011-2012 Mozilla
#
# This file is part of Case Conductor.
#
# Case Conductor is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Case Conductor is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Case Conductor. If not, see <http://www.gnu.org/licenses/>.
from .base import *
try:
from .local import *
except ImportError:
pass
CACHES["default"]["VERSION"] = 1
if DEBUG:
MIDDLEWARE_CLASSES.insert(
0, "cc.debug.middleware.AjaxTracebackMiddleware")
LOGGING["handlers"]["console"] = {
"level": "DEBUG",
"class": "logging.StreamHandler",
}
LOGGING["root"] = {"handlers": ["console"]}
try:
HMAC_KEYS
except NameError:
HMAC_KEYS = {"default": SECRET_KEY}
| # Case Conductor is a Test Case Management system.
# Copyright (C) 2011-2012 Mozilla
#
# This file is part of Case Conductor.
#
# Case Conductor is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Case Conductor is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Case Conductor. If not, see <http://www.gnu.org/licenses/>.
from .base import *
try:
from .local import *
except ImportError:
pass
CACHES["default"]["VERSION"] = 1
if DEBUG:
MIDDLEWARE_CLASSES.insert(
0, "cc.debug.middleware.AjaxTracebackMiddleware")
try:
HMAC_KEYS
except NameError:
HMAC_KEYS = {"default": SECRET_KEY}
|
Test the only untested line | from json import loads
from os import close, unlink
from tempfile import mkstemp
from unittest import TestCase
from cunhajacaiu import app
class FlaskTestCase(TestCase):
def setUp(self):
# set a test db
self.db_handler, self.db_path = mkstemp()
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + self.db_path
# set a testing app
app.config['TESTING'] = True
app.config['REQUESTS_CACHE_BACKEND'] = 'memory'
self.app = app.test_client()
def tearDown(self):
close(self.db_handler)
unlink(self.db_path)
class MockJsonNewsResponse:
HTTP_STATUS_CODE = (500, 200)
COUNT = 0
@staticmethod
def json():
with open('tests/news.json') as file_handler:
return loads(file_handler.read())
@property
def status_code(self):
self.COUNT += 1
return self.HTTP_STATUS_CODE[self.COUNT - 1]
| from json import loads
from os import close, unlink
from tempfile import mkstemp
from unittest import TestCase
from cunhajacaiu import app
class FlaskTestCase(TestCase):
def setUp(self):
# set a test db
self.db_handler, self.db_path = mkstemp()
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + self.db_path
# set a testing app
app.config['TESTING'] = True
app.config['REQUESTS_CACHE_BACKEND'] = 'memory'
self.app = app.test_client()
def tearDown(self):
close(self.db_handler)
unlink(self.db_path)
class MockJsonNewsResponse:
@staticmethod
def json():
with open('tests/news.json') as file_handler:
return loads(file_handler.read())
@property
def status_code(self):
return 200
|
Improve how variables are output. Remove useless php tag. Switch to associative arrays for decoded json. | <html>
<head>
<title>dcs-get package listing</title>
</head>
<body>
<h1>Package Listing</h1>
<p>This is an up to date list of all packages available for dcs-get, along with their dependencies.</p>
<h2>Packages</h2>
<?php
//error_reporting(0);
error_reporting(E_ALL);
define('BASE_URL', 'http://backus.uwcs.co.uk/dcs-get/');
$packages = json_decode(file_get_contents(BASE_URL.'packages.json'), true);
ksort($packages);
foreach($packages as $package => $data) {
echo '<ul>';
echo '<li>';
echo htmlspecialchars($package).' - ';
if (isset($data['description'])) {
echo htmlspecialchars($data['description']).' - ';
}
echo 'Version: '.htmlspecialchars(implode(', ', $data['version'])).'<br>';
if (isset($data['dependencies'])) {
echo '<ul>';
foreach ($data['dependencies'] as $dep => $details) {
echo '<li>'.htmlspecialchars($details[0]).' - '.htmlspecialchars($details[1]).'</li>';
}
echo '</ul>';
}
echo '</li>';
echo '</ul>';
}
?>
</body>
</html>
| <html>
<head>
<title>dcs-get package listing</title>
</head>
<body>
<h1>Package Listing</h1>
<p>This is an up to date list of all packages available for dcs-get, along with their dependencies.</p>
<h2>Packages</h2>
<?php
error_reporting(0);
//error_reporting(E_ALL);
define('BASE_URL', 'http://backus.uwcs.co.uk/dcs-get/');
$packages = json_decode(file_get_contents(BASE_URL.'packages.json'));
$sorted_packages = array();
foreach ($packages as $package => $data) {
$sorted_packages[$package] = $data;
}
ksort($sorted_packages);
foreach($sorted_packages as $package => $data) {
echo '<ul>';
echo '<li>';
echo "$package - ";
if (isset($data->description)) {
echo "$data->description - ";
}
echo 'Version: '.implode(', ', $data->version).'<br>';
if (isset($data->dependencies)) {
echo '<ul>';
foreach ($data->dependencies as $dep => $stuff) {
echo "<li>$stuff[0] - $stuff[1]</li>";
}
echo '</ul>';
}
echo '</li>';
echo '</ul>';
}
?>
</body>
</html>
<?php
|
Nit: Fix statement exceeding 100-character line limit | enum BeamType {
FAR(1.0f, 0.1f, 3.0f, 0.5f, 5.0f),
MIDDLE(2.0f, 0.2f, 6.0f, 0.7f, 7.0f),
NEAR(3.0f, 0.3f, 9.0f, 0.9f, 9.0f);
final float velocity;
final float acceleration;
final float terminalVelocity;
final float opacity;
final float size;
BeamType(float velocity, float acceleration, float terminalVelocity,
float opacity, float size) {
this.velocity = velocity;
this.acceleration = acceleration;
this.terminalVelocity = terminalVelocity;
this.opacity = opacity * 255;
this.size = size;
}
float velocity() {
return velocity;
}
float acceleration() {
return acceleration;
}
float terminalVelocity() {
return terminalVelocity;
}
float opacity() {
return opacity;
}
float size() {
return size;
}
}
| enum BeamType {
FAR(1.0f, 0.1f, 3.0f, 0.5f, 5.0f),
MIDDLE(2.0f, 0.2f, 6.0f, 0.7f, 7.0f),
NEAR(3.0f, 0.3f, 9.0f, 0.9f, 9.0f);
final float velocity;
final float acceleration;
final float terminalVelocity;
final float opacity;
final float size;
BeamType(float velocity, float acceleration, float terminalVelocity, float opacity, float size) {
this.velocity = velocity;
this.acceleration = acceleration;
this.terminalVelocity = terminalVelocity;
this.opacity = opacity * 255;
this.size = size;
}
float velocity() {
return velocity;
}
float acceleration() {
return acceleration;
}
float terminalVelocity() {
return terminalVelocity;
}
float opacity() {
return opacity;
}
float size() {
return size;
}
}
|
Remove flags that drastically slow down writes | #!/usr/bin/python3
import argparse
import os
import icon_lib
parser = argparse.ArgumentParser(description='iconograph persistent')
parser.add_argument(
'--chroot-path',
dest='chroot_path',
action='store',
required=True)
FLAGS = parser.parse_args()
def main():
module = icon_lib.IconModule(FLAGS.chroot_path)
os.mkdir(os.path.join(FLAGS.chroot_path, 'persistent'))
tool_path = os.path.join(FLAGS.chroot_path, 'icon', 'persistent')
os.makedirs(tool_path, exist_ok=True)
script = os.path.join(tool_path, 'startup.sh')
with open(script, 'w') as fh:
os.chmod(fh.fileno(), 0o755)
fh.write("""\
#!/bin/bash
set -ex
e2fsck -a /persistent
mount -o noatime LABEL=PERSISTENT /persistent
""")
with module.ServiceFile('persistent.service') as fh:
fh.write("""
[Unit]
Description=Mount /persistent
DefaultDependencies=no
Conflicts=shutdown.target
After=systemd-remount-fs.service
Before=sysinit.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/icon/persistent/startup.sh
[Install]
WantedBy=sysinit.target
""")
module.EnableService('persistent.service')
if __name__ == '__main__':
main()
| #!/usr/bin/python3
import argparse
import os
import icon_lib
parser = argparse.ArgumentParser(description='iconograph persistent')
parser.add_argument(
'--chroot-path',
dest='chroot_path',
action='store',
required=True)
FLAGS = parser.parse_args()
def main():
module = icon_lib.IconModule(FLAGS.chroot_path)
os.mkdir(os.path.join(FLAGS.chroot_path, 'persistent'))
tool_path = os.path.join(FLAGS.chroot_path, 'icon', 'persistent')
os.makedirs(tool_path, exist_ok=True)
script = os.path.join(tool_path, 'startup.sh')
with open(script, 'w') as fh:
os.chmod(fh.fileno(), 0o755)
fh.write("""\
#!/bin/bash
set -ex
e2fsck -a /persistent
mount -o data=journal,noatime,sync LABEL=PERSISTENT /persistent
""")
with module.ServiceFile('persistent.service') as fh:
fh.write("""
[Unit]
Description=Mount /persistent
DefaultDependencies=no
Conflicts=shutdown.target
After=systemd-remount-fs.service
Before=sysinit.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/icon/persistent/startup.sh
[Install]
WantedBy=sysinit.target
""")
module.EnableService('persistent.service')
if __name__ == '__main__':
main()
|
Read template str as UTF-8 string | var browserify = require('browserify');
var brfs = require('brfs');
var through = require('through');
require('browserify/lib/builtins').fs = 'create-webfs.js'; // TODO: find a better way to replace this module
var b = browserify();
// directly include rfile TODO: use brfs, but it replaces fs.readFileSync
b.transform(function(s) {
var data = '';
return through(write, end);
function write(buf) { data += buf; }
function end() {
var fs = require('fs');
var s = data;
var includedFile = fs.readFileSync('node_modules//browserify/node_modules/umd/template.js', 'utf8');
s = s.replace(/rfile\('.\/template.js'\)/, JSON.stringify(includedFile));
this.queue(s);
this.queue(null);
};
}, { global: true });
b.add('./demo.js');
b.bundle().pipe(process.stdout);
| var browserify = require('browserify');
var brfs = require('brfs');
var through = require('through');
require('browserify/lib/builtins').fs = 'create-webfs.js'; // TODO: find a better way to replace this module
var b = browserify();
// directly include rfile TODO: use brfs, but it replaces fs.readFileSync
b.transform(function(s) {
var data = '';
return through(write, end);
function write(buf) { data += buf; }
function end() {
var fs = require('fs');
var s = data;
var includedFile = fs.readFileSync('node_modules//browserify/node_modules/umd/template.js'); // TODO: encoding? string?
s = s.replace(/rfile\('.\/template.js'\)/, JSON.stringify(includedFile));
this.queue(s);
this.queue(null);
};
}, { global: true });
b.add('./demo.js');
b.bundle().pipe(process.stdout);
|
Allow both -m and --message | from argparse import ArgumentParser
from dodo_commands.framework import Dodo
from dodo_commands.framework.config import Paths
import os
def _args():
parser = ArgumentParser()
parser.add_argument(
'--message', '-m', dest='message', help='The commit message')
args = Dodo.parse_args(parser)
return args
if Dodo.is_main(__name__, safe=True):
args = _args()
if not os.path.exists(os.path.join(Paths().res_dir(), '.git')):
Dodo.run(['git', 'init'], cwd=Paths().res_dir())
Dodo.run(['git', 'add', '-A'], cwd=Paths().res_dir())
Dodo.run(['git', 'commit', '-m', args.message or 'Update configuration'],
cwd=Paths().res_dir())
| from argparse import ArgumentParser
from dodo_commands.framework import Dodo
from dodo_commands.framework.config import Paths
import os
def _args():
parser = ArgumentParser()
parser.add_argument('-m', dest='message')
args = Dodo.parse_args(parser)
return args
if Dodo.is_main(__name__, safe=True):
args = _args()
if not os.path.exists(os.path.join(Paths().res_dir(), '.git')):
Dodo.run(['git', 'init'], cwd=Paths().res_dir())
Dodo.run(['git', 'add', '-A'], cwd=Paths().res_dir())
Dodo.run(
['git', 'commit', '-m', args.message or 'Update configuration'],
cwd=Paths().res_dir())
|
Use striptags from genshi for striphtml, since we have to have genshi anyway | # -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from datetime import datetime
from tg import url as tgurl
#from webhelpers import date, feedgenerator, html, number, misc, text
import webhelpers as w
from webhelpers.html.tags import link_to
from webhelpers.text import truncate
from webhelpers.date import distance_of_time_in_words
from genshi.core import striptags
import re
#log = logging.getLogger(__name__)
cut = lambda text, max=200: truncate(text, max, whole_word=True)
strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity)
striphtml = striptags
def link(label, url='', **attrs):
return link_to(label, tgurl(url), **attrs)
| # -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from datetime import datetime
from tg import url as tgurl
#from webhelpers import date, feedgenerator, html, number, misc, text
import webhelpers as w
from webhelpers.html.tags import link_to
from webhelpers.text import truncate
from webhelpers.date import distance_of_time_in_words
import re
#log = logging.getLogger(__name__)
cut = lambda text, max=200: truncate(text, max, whole_word=True)
strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity)
def link(label, url='', **attrs):
return link_to(label, tgurl(url), **attrs)
def striphtml(text):
return re.sub('<[^<]+?>', ' ', text).strip()
|
Use less strict condition to avoid problems with concurrency
In latest go versions TestWatcher fails pretty often, because it is
"more concurrent" now. Reproducible with go master:
while go test github.com/mholt/caddy/middleware/markdown; do :; done
Signed-off-by: Alexander Morozov <4efb7da3e38416208b41d8021a942884d8a9435c@docker.com> | package markdown
import (
"fmt"
"strings"
"sync"
"testing"
"time"
)
func TestWatcher(t *testing.T) {
expected := "12345678"
interval := time.Millisecond * 100
i := 0
out := ""
stopChan := TickerFunc(interval, func() {
i++
out += fmt.Sprint(i)
})
// wait little more because of concurrency
time.Sleep(interval * 9)
stopChan <- struct{}{}
if !strings.HasPrefix(out, expected) {
t.Fatalf("Expected to have prefix %v, found %v", expected, out)
}
out = ""
i = 0
var mu sync.Mutex
stopChan = TickerFunc(interval, func() {
i++
mu.Lock()
out += fmt.Sprint(i)
mu.Unlock()
})
time.Sleep(interval * 10)
mu.Lock()
res := out
mu.Unlock()
if !strings.HasPrefix(res, expected) || res == expected {
t.Fatalf("expected (%v) must be a proper prefix of out(%v).", expected, out)
}
}
| package markdown
import (
"fmt"
"strings"
"sync"
"testing"
"time"
)
func TestWatcher(t *testing.T) {
expected := "12345678"
interval := time.Millisecond * 100
i := 0
out := ""
stopChan := TickerFunc(interval, func() {
i++
out += fmt.Sprint(i)
})
time.Sleep(interval * 8)
stopChan <- struct{}{}
if expected != out {
t.Fatalf("Expected %v, found %v", expected, out)
}
out = ""
i = 0
var mu sync.Mutex
stopChan = TickerFunc(interval, func() {
i++
mu.Lock()
out += fmt.Sprint(i)
mu.Unlock()
})
time.Sleep(interval * 10)
mu.Lock()
res := out
mu.Unlock()
if !strings.HasPrefix(res, expected) || res == expected {
t.Fatalf("expected (%v) must be a proper prefix of out(%v).", expected, out)
}
}
|
Refactor and tie in configurable options | (function ( $ ) {
$.fn.goodtree = function( options ) {
// Default Settings
var settings = $.extend({
'expandIconClass' : 'closed',
'contractIconClass' : 'open',
'classPrefix' : 'goodtree_',
}, options);
return this.each(function() {
// Hide all of the children Elements
$(this).find('ul').hide();
// Add the plus minus buttons
$(this).find('li').each(function() {
if($(this).children('ul').length > 0)
$(this).prepend($('<div />', {'class': settings.classPrefix + "toggle " + settings.expandIconClass}));
});
// Events
$('.' + settings.classPrefix + 'toggle').click(function() {
$(this).parent().children('ul').toggle();
$(this).hasClass('open')
? $(this).removeClass(settings.contractIconClass).addClass(settings.expandIconClass)
: $(this).removeClass(settings.expandIconClass).addClass(settings.contractIconClass);
});
});
};
}) ( jQuery ); | (function ( $ ) {
$.fn.goodtree = function( options ) {
// Default Settings
var settings = $.extend({
'expand_icon' : 'images/tree/expand.png',
'contract_icon' : 'images/tree/contract.png',
'class_prefix' : 'goodtree_',
}, options);
return this.each(function() {
// Hide all of the children Elements
$(this).find('ul').hide();
// Add the plus minus buttons
$(this).find('li').each(function() {
if($(this).children('ul').length > 0)
$(this).prepend("<div class='" + settings.class_prefix + "toggle closed'></div>");
});
// Events
$('.' + settings.class_prefix + 'toggle').click(function() {
$(this).parent().children('ul').toggle();
$(this).hasClass('open') ? $(this).removeClass('open').addClass('closed') : $(this).removeClass('closed').addClass('open');
});
});
};
}) ( jQuery ); |
Add option to shovel output files to a particular directory | package main
import (
"github.com/alecthomas/kingpin"
_ "github.com/cockroachdb/pq"
"github.com/npotts/arduino/WxShield2/wxplot"
"os"
)
var (
app = kingpin.New("wxPlot", "Plot data pulled from postgres/cockroachdb")
dataSourceName = app.Flag("dataSource", "Where should we connect to and yank data from (usually a string like 'postgresql://root@dataserver:26257?sslmode=disable')").Short('s').Default("postgresql://root@chipmunk:26257?sslmode=disable").String()
database = app.Flag("database", "The database to aim at").Short('d').Default("wx").String()
raw = app.Flag("table", "The database table read raw data from").Short('t').Default("raw").String()
dir = app.Flag("output-dir", "Where should the output files be shoveled").Short('t').Default(".").String()
)
func main() {
app.Parse(os.Args[1:])
i := wxplot.New(*dataSourceName, *database, *raw)
i.WriteFile(*dir+"/hourly.html", i.Hourly())
i.WriteFile(*dir+"/weekly.html", i.Weekly())
}
| package main
import (
"github.com/alecthomas/kingpin"
_ "github.com/cockroachdb/pq"
"github.com/npotts/arduino/WxShield2/wxplot"
"os"
)
var (
app = kingpin.New("wxPlot", "Plot data pulled from postgres/cockroachdb")
dataSourceName = app.Flag("dataSource", "Where should we connect to and yank data from (usually a string like 'postgresql://root@dataserver:26257?sslmode=disable')").Short('s').Default("postgresql://root@chipmunk:26257?sslmode=disable").String()
database = app.Flag("database", "The database to aim at").Short('d').Default("wx").String()
raw = app.Flag("table", "The database table read raw data from").Short('t').Default("raw").String()
)
func main() {
app.Parse(os.Args[1:])
i := wxplot.New(*dataSourceName, *database, *raw)
i.WriteFile("hourly.html",i.Hourly())
i.WriteFile("weekly.html",i.Weekly())
}
|
Update eslint config to allow 2 spaces
- happy to discuss and revert this. | module.exports = {
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"double"
],
"semi": [
"error",
"never"
]
}
}
| module.exports = {
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"indent": [
"error",
"tab"
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"double"
],
"semi": [
"error",
"never"
]
}
}
|
Refactor api test to setup test client in setup +review PLAT-127 DCORE-1109 | from nose.tools import eq_
import mock
from lcp import api
class TestApiClient(object):
def setup(self):
self.client = api.Client('BASE_URL')
def test_request_does_not_alter_absolute_urls(self):
for absolute_url in [
'http://www.points.com',
'https://www.points.com',
]:
yield self._assert_calls_requests_with_url, absolute_url, absolute_url
def test_request_adds_base_url_to_relative_urls(self):
for absolute_url in [
'some/relative/path/',
'/some/absolute/path',
]:
yield self._assert_calls_requests_with_url, absolute_url, 'BASE_URL' + absolute_url
@mock.patch('lcp.api.requests.request')
def _assert_calls_requests_with_url(self, original_url, expected_url, request_mock):
self.client.request('METHOD', original_url)
expected_headers = {'Content-Type': 'application/json'}
eq_(request_mock.call_args_list, [
mock.call('METHOD', expected_url, data='{}', headers=expected_headers)])
| from nose.tools import eq_
import mock
from lcp import api
@mock.patch('lcp.api.requests.request')
def _assert_calls_requests_with_url(original_url, expected_url, request_mock):
api.Client('BASE_URL').request('METHOD', original_url)
expected_headers = {'Content-Type': 'application/json'}
eq_(request_mock.call_args_list, [
mock.call('METHOD', expected_url, data='{}', headers=expected_headers)])
def test_request_does_not_alter_absolute_urls():
for absolute_url in [
'http://www.points.com',
'https://www.points.com',
]:
yield _assert_calls_requests_with_url, absolute_url, absolute_url
def test_request_adds_base_url_to_relative_urls():
for absolute_url in [
'some/relative/path/',
'/some/absolute/path',
]:
yield _assert_calls_requests_with_url, absolute_url, 'BASE_URL' + absolute_url
|
Remove assert in error-rasing test | from pytest import raises
from nirum.validate import (validate_boxed_type, validate_record_type,
validate_union_type)
def test_validate_boxed_type():
assert validate_boxed_type(3.14, float)
with raises(TypeError):
validate_boxed_type('hello', float)
def test_validate_record_type(fx_point, fx_record_type, fx_offset):
assert validate_record_type(fx_point)
with raises(TypeError):
validate_record_type(fx_record_type(left=fx_offset, top=1))
with raises(TypeError):
validate_record_type(fx_record_type(left=1, top=fx_offset))
def test_validate_union_type(fx_rectangle, fx_rectangle_type, fx_point):
assert validate_union_type(fx_rectangle)
with raises(TypeError):
validate_union_type(fx_rectangle_type(1, fx_point))
with raises(TypeError):
validate_union_type(fx_rectangle_type(fx_point, 1))
with raises(TypeError):
validate_union_type(fx_rectangle_type(1, 1))
| from pytest import raises
from nirum.validate import (validate_boxed_type, validate_record_type,
validate_union_type)
def test_validate_boxed_type():
assert validate_boxed_type(3.14, float)
with raises(TypeError):
validate_boxed_type('hello', float)
def test_validate_record_type(fx_point, fx_record_type, fx_offset):
assert validate_record_type(fx_point)
with raises(TypeError):
assert validate_record_type(fx_record_type(left=fx_offset, top=1))
with raises(TypeError):
assert validate_record_type(fx_record_type(left=1, top=fx_offset))
def test_validate_union_type(fx_rectangle, fx_rectangle_type, fx_point):
assert validate_union_type(fx_rectangle)
with raises(TypeError):
assert validate_union_type(fx_rectangle_type(1, fx_point))
with raises(TypeError):
assert validate_union_type(fx_rectangle_type(fx_point, 1))
with raises(TypeError):
assert validate_union_type(fx_rectangle_type(1, 1))
|
Make preprints url replacement absolute url | import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
import AnalyticsMixin from '../mixins/analytics-mixin';
export default Ember.Route.extend(AnalyticsMixin, ResetScrollMixin, {
model(params) {
return this.store.findRecord('preprint', params.preprint_id);
},
setupController(controller, model) {
controller.set('activeFile', model.get('primaryFile'));
Ember.run.scheduleOnce('afterRender', this, function() {
MathJax.Hub.Queue(['Typeset', MathJax.Hub, [Ember.$('.abstract')[0], Ember.$('#preprintTitle')[0]]]); // jshint ignore:line
});
return this._super(...arguments);
},
actions: {
error(error, transition) {
window.history.replaceState({}, 'preprints', '/preprints/' + transition.params.content.preprint_id);
this.intermediateTransitionTo('page-not-found');
}
}
});
| import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
import AnalyticsMixin from '../mixins/analytics-mixin';
export default Ember.Route.extend(AnalyticsMixin, ResetScrollMixin, {
model(params) {
return this.store.findRecord('preprint', params.preprint_id);
},
setupController(controller, model) {
controller.set('activeFile', model.get('primaryFile'));
Ember.run.scheduleOnce('afterRender', this, function() {
MathJax.Hub.Queue(['Typeset', MathJax.Hub, [Ember.$('.abstract')[0], Ember.$('#preprintTitle')[0]]]); // jshint ignore:line
});
return this._super(...arguments);
},
actions: {
error(error, transition) {
window.history.replaceState({}, 'preprints', 'preprints/' + transition.params.content.preprint_id);
this.intermediateTransitionTo('page-not-found');
}
}
});
|
Move Index import to the top to fix css order issue | /** DO NOT MODIFY **/
import React, { Component } from "react";
import { render } from "react-dom";
// Make sure that webpack considers new dependencies introduced in the Index
// file
import "../../Index.js";
import { Root } from "gluestick-shared";
import { match } from "react-router";
import routes from "./routes";
import store from "./.store";
import { StyleRoot } from "radium";
export default class Entry extends Component {
static defaultProps = {
store: store()
};
render () {
const {
routerContext,
radiumConfig,
store
} = this.props;
return (
<StyleRoot radiumConfig={radiumConfig}>
<Root routerContext={routerContext} routes={routes} store={store} />
</StyleRoot>
);
}
}
Entry.start = function () {
match({routes, location: window.location.pathname}, (error, redirectLocation, renderProps) => {
render(<Entry radiumConfig={{userAgent: window.navigator.userAgent}} {...renderProps} />, document.getElementById("main"));
});
};
| /** DO NOT MODIFY **/
import React, { Component } from "react";
import { render } from "react-dom";
import { Root } from "gluestick-shared";
import { match } from "react-router";
import routes from "./routes";
import store from "./.store";
import { StyleRoot } from "radium";
// Make sure that webpack considers new dependencies introduced in the Index
// file
import "../../Index.js";
export default class Entry extends Component {
static defaultProps = {
store: store()
};
render () {
const {
routerContext,
radiumConfig,
store
} = this.props;
return (
<StyleRoot radiumConfig={radiumConfig}>
<Root routerContext={routerContext} routes={routes} store={store} />
</StyleRoot>
);
}
}
Entry.start = function () {
match({routes, location: window.location.pathname}, (error, redirectLocation, renderProps) => {
render(<Entry radiumConfig={{userAgent: window.navigator.userAgent}} {...renderProps} />, document.getElementById("main"));
});
};
|
Clarify use of 'debug' option | 'use strict';
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
//var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
gulp.task('default', function() {
// place code for your default task here
console.log("default task (does nothing!)");
});
gulp.task('js', function () {
// call from command line as 'gulp js'
// set up the browserify instance on a task basis
var b = browserify({
entries: './stylist.js',
//entries: './vg.data.stash.js',
debug: true // enables sourcemaps
});
return b.bundle()
.pipe(source('stylist-bundle.js'))
.pipe(buffer())
/*
.pipe(sourcemaps.init({loadMaps: true}))
// Add transformation tasks to the pipeline here.
.pipe(uglify())
.on('error', gutil.log)
.pipe(sourcemaps.write('./'))
*/
.pipe(gulp.dest('./'));
});
| 'use strict';
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
//var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
gulp.task('default', function() {
// place code for your default task here
console.log("default task (does nothing!)");
});
gulp.task('js', function () {
// call from command line as 'gulp js'
// set up the browserify instance on a task basis
var b = browserify({
entries: './stylist.js',
//entries: './vg.data.stash.js',
debug: true
});
return b.bundle()
.pipe(source('stylist-bundle.js'))
.pipe(buffer())
/*
.pipe(sourcemaps.init({loadMaps: true}))
// Add transformation tasks to the pipeline here.
.pipe(uglify())
.on('error', gutil.log)
.pipe(sourcemaps.write('./'))
*/
.pipe(gulp.dest('./'));
});
|
Add defensive check to program arguments | package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Usage:\n\tmain region_name")
os.Exit(-1)
}
region := os.Args[1]
if region == "" {
fmt.Println("Usage:\n\tmain region_name")
os.Exit(-1)
}
svc := ec2.New(session.New(), &aws.Config{Region: aws.String(region)})
resp, err := svc.DescribeInstances(nil)
if err != nil {
panic(err)
}
fmt.Println("> Number of reservation sets: ", len(resp.Reservations))
for idx, res := range resp.Reservations {
fmt.Println(" > Number of instances: ", len(res.Instances))
for _, inst := range resp.Reservations[idx].Instances {
fmt.Println(" - Instance ID: ", *inst.InstanceId)
}
}
}
| package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
func main() {
svc := ec2.New(session.New(), &aws.Config{Region: aws.String("us-west-2")})
resp, err := svc.DescribeInstances(nil)
if err != nil {
panic(err)
}
fmt.Println("> Number of reservation sets: ", len(resp.Reservations))
for idx, res := range resp.Reservations {
fmt.Println(" > Number of instances: ", len(res.Instances))
for _, inst := range resp.Reservations[idx].Instances {
fmt.Println(" - Instance ID: ", *inst.InstanceId)
}
}
} |
Switch side of shrinking bar | AFRAME.registerComponent('hit-listener', {
schema: {
characterId: { default: undefined },
barWidth: { default: 1 },
maxLife: { default: 100 }
},
init: function () {
const el = this.el;
const data = this.data;
const position = el.getAttribute('position');
window.addEventListener('characterHit', function (e) {
if(data.characterId === e.detail.characterId) {
const width = Math.max((e.detail.remainingHealth/data.maxLife) * data.barWidth, 0);
const xPosition = (e.detail.remainingHealth/data.maxLife - 1) * data.barWidth / 2;
el.setAttribute('width', width);
el.setAttribute('position', {
x: xPosition,
y: position.y,
z: position.z
});
}
});
}
});
| AFRAME.registerComponent('hit-listener', {
schema: {
characterId: { default: undefined },
barWidth: { default: 1 },
maxLife: { default: 100 }
},
init: function () {
const el = this.el;
const data = this.data;
const position = el.getAttribute('position');
window.addEventListener('characterHit', function (e) {
if(data.characterId === e.detail.characterId) {
const width = Math.max((e.detail.remainingHealth/data.maxLife) * data.barWidth, 0);
const xPosition = (1 - e.detail.remainingHealth/data.maxLife) * data.barWidth / 2;
el.setAttribute('width', width);
el.setAttribute('position', {
x: xPosition,
y: position.y,
z: position.z
});
}
});
}
});
|
Return the simple response header and response body. | package org.yukung.sandbox.http;
import static org.yukung.sandbox.http.HttpRequest.*;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author yukung
*/
public class Main {
public static void main(String[] args) throws IOException {
System.out.println("start >>>");
try (
ServerSocket ss = new ServerSocket(8080);
Socket socket = ss.accept();
InputStream in = socket.getInputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))
) {
HttpRequest request = new HttpRequest(in);
System.out.println(request.getHeaderText());
System.out.println(request.getBodyText());
bw.write("HTTP/1.1 200 OK" + CRLF);
bw.write("Content-Type: text/html" + CRLF);
bw.write(CRLF);
bw.write("<h1>Hello World!</h1>");
}
System.out.println("<<< end");
}
}
| package org.yukung.sandbox.http;
import static org.yukung.sandbox.http.HttpRequest.CRLF;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author yukung
*/
public class Main {
public static void main(String[] args) throws IOException {
System.out.println("start >>>");
try (
ServerSocket ss = new ServerSocket(8080);
Socket socket = ss.accept();
InputStream in = socket.getInputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))
) {
HttpRequest request = new HttpRequest(in);
System.out.println(request.getHeaderText());
System.out.println(request.getBodyText());
bw.write("HTTP/1.1 200 OK" + CRLF);
}
System.out.println("<<< end");
}
}
|
Remove closing PHP tag from end of file | <?php
//require_once( config_get( 'plugin_path' ) . 'SourceGithub/SourceGithub.php' );
auth_reauthenticate();
layout_page_header( plugin_lang_get( 'title' ) );
layout_page_begin();
print_manage_menu();
$f_repo_id = gpc_get_int( 'id' );
$f_code = gpc_get_string( 'code' );
$t_repo = SourceRepo::load( $f_repo_id );
if ( SourceGithubPlugin::oauth_get_access_token( $t_repo, $f_code ) === true ) {
$t_was_authorized = true;
} else {
$t_was_authorized = false;
}
?>
<table class="table table-striped table-bordered table-condensed">
<tr>
<td class="category"><?php echo plugin_lang_get( 'oauth_authorization' ) ?></td>
<td class="pull-right"><?php print_small_button( plugin_page( 'repo_manage_page', false, 'Source' ) . '&id=' . $t_repo->id, plugin_lang_get( 'back_repo' ) ) ?></td>
</tr>
<tr>
<td class="center" colspan="2"><?php echo $t_was_authorized === true ? plugin_lang_get('repo_authorized') : plugin_lang_get('repo_authorization_failed'); ?></td>
</tr>
</table>
<?php
layout_page_end();
| <?php
//require_once( config_get( 'plugin_path' ) . 'SourceGithub/SourceGithub.php' );
auth_reauthenticate();
layout_page_header( plugin_lang_get( 'title' ) );
layout_page_begin();
print_manage_menu();
$f_repo_id = gpc_get_int( 'id' );
$f_code = gpc_get_string( 'code' );
$t_repo = SourceRepo::load( $f_repo_id );
if ( SourceGithubPlugin::oauth_get_access_token( $t_repo, $f_code ) === true ) {
$t_was_authorized = true;
} else {
$t_was_authorized = false;
}
?>
<table class="table table-striped table-bordered table-condensed">
<tr>
<td class="category"><?php echo plugin_lang_get( 'oauth_authorization' ) ?></td>
<td class="pull-right"><?php print_small_button( plugin_page( 'repo_manage_page', false, 'Source' ) . '&id=' . $t_repo->id, plugin_lang_get( 'back_repo' ) ) ?></td>
</tr>
<tr>
<td class="center" colspan="2"><?php echo $t_was_authorized === true ? plugin_lang_get('repo_authorized') : plugin_lang_get('repo_authorization_failed'); ?></td>
</tr>
</table>
<?php
layout_page_end();
?> |
Establish connection only when needed | import xmlrpclib
import cPickle
import subprocess
from time import sleep
p = None
s = None
def start_plot_server():
global p
if p is None:
p = subprocess.Popen(["python", "plot_server.py"])
def stop_plot_server():
if p is not None:
p.terminate()
sleep(0.01)
p.kill()
def plot_server_alive():
global s
try:
s.alive()
except Exception, e:
if str(e).endswith("Connection refused"):
return False
else:
raise
return True
def establish_connection():
global s
if s is not None:
return
s = xmlrpclib.ServerProxy("http://localhost:8000/", allow_none=True)
if not plot_server_alive():
start_plot_server()
print "waiting for the plot server to start up..."
while not plot_server_alive():
sleep(0.05)
print " done."
def plot(vert, triangles):
establish_connection()
print "plotting using mayavi..."
v = cPickle.dumps(vert)
t = cPickle.dumps(triangles)
s.plot(v, t)
print " done."
| import xmlrpclib
import cPickle
import subprocess
from time import sleep
p = None
s = None
def start_plot_server():
global p
if p is None:
p = subprocess.Popen(["python", "plot_server.py"])
def stop_plot_server():
if p is not None:
p.terminate()
sleep(0.01)
p.kill()
def plot_server_alive():
global s
try:
s.alive()
except Exception, e:
if str(e).endswith("Connection refused"):
return False
else:
raise
return True
def establish_connection():
global s
s = xmlrpclib.ServerProxy("http://localhost:8000/", allow_none=True)
if not plot_server_alive():
start_plot_server()
print "waiting for the plot server to start up..."
while not plot_server_alive():
sleep(0.05)
print " done."
def plot(vert, triangles):
print "plotting using mayavi..."
v = cPickle.dumps(vert)
t = cPickle.dumps(triangles)
s.plot(v, t)
print " done."
establish_connection()
|
Switch Login to use formsyFIeld | import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { browserHistory } from 'react-router';
import { Form, Button, Input } from 'semantic-ui-react';
import Formsy from 'formsy-react';
import { FormsyField } from '../formsy-semantic-ui';
import { createSession } from '../actions/auth';
class LoginPage extends Component {
handleSubmit = model => {
this.props.createSession(model)
.then(() => {
browserHistory.push('/');
});
};
render() {
return (
<Form as={Formsy.Form} onValidSubmit={this.handleSubmit}>
<h2>Login</h2>
<FormsyField control={Input} name="username" label="Username" placeholder="amigo" required />
<FormsyField control={Input} name="password" label="Password" placeholder="B33d33d33" type="password" required />
<Button type="submit" color="teal">Log-in</Button>
</Form>
);
}
}
LoginPage.propTypes = {
createSession: PropTypes.func.isRequired
};
function mapStateToProps(state) {
return state;
}
export default connect(mapStateToProps, {
createSession
})(LoginPage);
| import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { browserHistory } from 'react-router';
import { Form, Button } from 'semantic-ui-react';
import Formsy from 'formsy-react';
import { FormsyInput } from '../formsy-semantic-ui';
import { createSession } from '../actions/auth';
class LoginPage extends Component {
handleSubmit = model => {
this.props.createSession(model)
.then(() => {
browserHistory.push('/');
});
};
render() {
return (
<Form as={Formsy.Form} onValidSubmit={this.handleSubmit}>
<h2>Login</h2>
<FormsyInput name="username" label="Username" placeholder="amigo" required />
<FormsyInput name="password" label="Password" placeholder="B33d33d33" type="password" required />
<Button type="submit" color="teal">Log-in</Button>
</Form>
);
}
}
LoginPage.propTypes = {
createSession: PropTypes.func.isRequired
};
function mapStateToProps(state) {
return state;
}
export default connect(mapStateToProps, {
createSession
})(LoginPage);
|
Install typing module for older python versions. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
from setuptools import setup
setup(
name='django-brotli',
version='0.1.0',
description="""Middleware that compresses response using brotli algorithm.""",
long_description=io.open("README.rst", 'r', encoding="utf-8").read(),
url='https://github.com/illagrenan/django-brotli',
license='MIT',
author='Vasek Dohnal',
author_email='vaclav.dohnal@gmail.com',
packages=['django_brotli'],
install_requires=[
":python_version<'3.5'": ['typing'],
'django',
'brotlipy'
],
include_package_data=True,
zip_safe=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Framework :: Django :: 1.10',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 3.5',
]
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
from setuptools import setup
setup(
name='django-brotli',
version='0.1.0',
description="""Middleware that compresses response using brotli algorithm.""",
long_description=io.open("README.rst", 'r', encoding="utf-8").read(),
url='https://github.com/illagrenan/django-brotli',
license='MIT',
author='Vasek Dohnal',
author_email='vaclav.dohnal@gmail.com',
packages=['django_brotli'],
install_requires=['django', 'brotlipy'],
include_package_data=True,
zip_safe=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Framework :: Django :: 1.10',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 3.5',
]
)
|
Print a message if method reflection returns null. | package com.twitter.diagnostics;
import java.lang.reflect.Method;
import java.lang.NoSuchMethodException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
class Tracepoints {
@PerfTracepoint static native void tracepoint0();
};
public class PerfTracepointTest extends TestCase {
public PerfTracepointTest(String name)
{
super(name);
}
public static Test suite()
{
return new TestSuite(PerfTracepointTest.class);
}
public void testApp()
{
Method method = null;
try {
method = Tracepoints.class.getDeclaredMethod("tracepoint0");
assertNotNull("Method Tracepoints.tracepoint0 is null.", method);
} catch (NoSuchMethodException e) {
assertTrue("Method tracepoint0 not found in class Tracepoints.", false);
}
PerfTracepoint tracepoint = method.getAnnotation(PerfTracepoint.class);
assertNotNull("PerfTracepoint instance is null.", tracepoint);
}
}; | package com.twitter.diagnostics;
import java.lang.reflect.Method;
import java.lang.NoSuchMethodException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
class Tracepoints {
@PerfTracepoint static native void tracepoint0();
};
public class PerfTracepointTest extends TestCase {
public PerfTracepointTest(String name)
{
super(name);
}
public static Test suite()
{
return new TestSuite(PerfTracepointTest.class);
}
public void testApp()
{
Method method = null;
try {
method = Tracepoints.class.getDeclaredMethod("tracepoint0");
assertNotNull("Method Tracepoints.tracepoint0 is null.", method);
} catch (NoSuchMethodException e) {
assertTrue(false);
}
PerfTracepoint tracepoint = method.getAnnotation(PerfTracepoint.class);
assertNotNull("PerfTracepoint instance is null.", tracepoint);
}
}; |
Add Python 3.7 to the list of supported versions | from setuptools import setup
from os import path
with open(path.join(path.abspath(path.dirname(__file__)), 'README.rst')) as f:
readme = f.read()
setup(
name='ghstats',
version='1.2.0',
packages=['ghstats'],
description='GitHub Release download count and other statistics.',
long_description=readme,
author='Alexander Gorishnyak',
author_email='kefir500@gmail.com',
license='MIT',
url='https://github.com/kefir500/ghstats',
keywords='github release download count stats statistics',
entry_points={
'console_scripts': [
'ghstats = ghstats.ghstats:main_cli'
]
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Utilities'
]
)
| from setuptools import setup
from os import path
with open(path.join(path.abspath(path.dirname(__file__)), 'README.rst')) as f:
readme = f.read()
setup(
name='ghstats',
version='1.2.0',
packages=['ghstats'],
description='GitHub Release download count and other statistics.',
long_description=readme,
author='Alexander Gorishnyak',
author_email='kefir500@gmail.com',
license='MIT',
url='https://github.com/kefir500/ghstats',
keywords='github release download count stats statistics',
entry_points={
'console_scripts': [
'ghstats = ghstats.ghstats:main_cli'
]
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Utilities'
]
)
|
Remove all .pager instances after each test | var pager;
var items = 100;
var itemsOnPage = 10;
var pageCount = items/itemsOnPage;
beforeEach(function() {
$('<div id="pager" class="pager"></div>').appendTo('body').pagination({
items: items,
itemsOnPage: itemsOnPage
});
pager = $('#pager');
this.addMatchers({
toBePaged: function() {
return ( this.actual.hasClass('simple-pagination') &&
this.actual.find('li').length > 0 );
},
toBeOnPage: function(expected_page) {
actual_page = this.actual.find('li.active span').not('.prev').not('.next').html();
return actual_page == expected_page;
},
toBeDisabled: function() {
return this.actual.find('li').length == this.actual.find('li.disabled').length;
}
});
});
afterEach(function () {
$('.pager').remove();
}); | var pager;
var items = 100;
var itemsOnPage = 10;
var pageCount = items/itemsOnPage;
beforeEach(function() {
$('<div id="pager"></div>').appendTo('body').pagination({
items: items,
itemsOnPage: itemsOnPage
});
pager = $('#pager');
this.addMatchers({
toBePaged: function() {
return ( this.actual.hasClass('simple-pagination') &&
this.actual.find('li').length > 0 );
},
toBeOnPage: function(expected_page) {
actual_page = this.actual.find('li.active span').not('.prev').not('.next').html();
return actual_page == expected_page;
},
toBeDisabled: function() {
return this.actual.find('li').length == this.actual.find('li.disabled').length;
}
});
});
afterEach(function () {
pager.remove();
}); |
Add test of defining a signal with a return type.
svn path=/trunk/; revision=233 | #!/usr/bin/env seed
// Returns: 0
// STDIN:
// STDOUT:2 Weathermen\n\[object GtkWindow\]
// STDERR:
Seed.import_namespace("GObject");
Seed.import_namespace("Gtk");
Gtk.init(null, null);
HelloWindowType = {
parent: Gtk.Window,
name: "HelloWindow",
class_init: function(klass, prototype)
{
var HelloSignalDefinition = {name: "hello",
parameters: [GObject.TYPE_INT,
GObject.TYPE_STRING],
return_type: GObject.TYPE_OBJECT};
hello_signal_id = klass.install_signal(HelloSignalDefinition);
},
}
HelloWindow = new GType(HelloWindowType);
w = new HelloWindow();
w.signal.hello.connect(function(object, number, string)
{Seed.print(number+ " " + string);
return new Gtk.Window()});
Seed.print(w.signal.hello.emit(2, "Weathermen"));
| #!/usr/bin/env seed
// Returns: 0
// STDIN:
// STDOUT:2 Weathermen
// STDERR:
Seed.import_namespace("GObject");
Seed.import_namespace("Gtk");
Gtk.init(null, null);
HelloWindowType = {
parent: Gtk.Window,
name: "HelloWindow",
class_init: function(klass, prototype)
{
var HelloSignalDefinition = {name: "hello",
parameters: [GObject.TYPE_INT,
GObject.TYPE_STRING]};
hello_signal_id = klass.install_signal(HelloSignalDefinition);
},
}
HelloWindow = new GType(HelloWindowType);
w = new HelloWindow();
w.signal.hello.connect(function(object, number, string)
{Seed.print(number+ " " + string)});
w.signal.hello.emit(2, "Weathermen");
|
Update environment test to have cross platform support | """Test the checkers"""
from nose.tools import ok_, eq_
from preflyt import check
CHECKERS = [
{"checker": "env", "name": "PATH"}
]
BAD_CHECKERS = [
{"checker": "env", "name": "PATH1231342dhkfgjhk2394dv09324jk12039csdfg01231"}
]
def test_everything():
"""Test the check method."""
good, results = check(CHECKERS)
ok_(good, results)
eq_(len(results), 1)
for field_name in ('check', 'success', 'message'):
ok_(field_name in results[0])
def test_everything_failure():
"""Test the check method."""
good, results = check(BAD_CHECKERS)
ok_(not good, results)
eq_(len(results), 1)
for field_name in ('check', 'success', 'message'):
ok_(field_name in results[0])
| """Test the checkers"""
from nose.tools import ok_, eq_
from preflyt import check
CHECKERS = [
{"checker": "env", "name": "USER"}
]
BAD_CHECKERS = [
{"checker": "env", "name": "USER1231342dhkfgjhk2394dv09324jk12039csdfg01231"}
]
def test_everything():
"""Test the check method."""
good, results = check(CHECKERS)
ok_(good, results)
eq_(len(results), 1)
for field_name in ('check', 'success', 'message'):
ok_(field_name in results[0])
def test_everything_failure():
"""Test the check method."""
good, results = check(BAD_CHECKERS)
ok_(not good, results)
eq_(len(results), 1)
for field_name in ('check', 'success', 'message'):
ok_(field_name in results[0])
|
Use ioutil for reduce code line | package file_storage
import (
"github.com/photoshelf/photoshelf-storage/domain/model"
"io/ioutil"
"os"
"path"
)
type FileStorage struct {
baseDir string
}
func NewFileStorage(baseDir string) *FileStorage {
return &FileStorage{baseDir}
}
func (storage *FileStorage) Save(photo model.Photo) (*model.Identifier, error) {
data := photo.Image()
id := photo.Id()
if photo.IsNew() {
id = *model.NewIdentifier(data)
}
filename := path.Join(storage.baseDir, id.Value())
ioutil.WriteFile(filename, data, 0600)
return &id, nil
}
func (storage *FileStorage) Read(id model.Identifier) (*model.Photo, error) {
filename := path.Join(storage.baseDir, id.Value())
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return model.PhotoOf(id, data), nil
}
func (storage *FileStorage) Delete(id model.Identifier) error {
if err := os.Remove(path.Join(storage.baseDir, id.Value())); err != nil {
return err
}
return nil
}
| package file_storage
import (
"github.com/photoshelf/photoshelf-storage/domain/model"
"io/ioutil"
"os"
"path"
)
type FileStorage struct {
baseDir string
}
func NewFileStorage(baseDir string) *FileStorage {
return &FileStorage{baseDir}
}
func (storage *FileStorage) Save(photo model.Photo) (*model.Identifier, error) {
data := photo.Image()
id := photo.Id()
if photo.IsNew() {
id = *model.NewIdentifier(data)
}
dst, err := os.Create(path.Join(storage.baseDir, id.Value()))
if err != nil {
return nil, err
}
defer dst.Close()
if _, err := dst.Write(data); err != nil {
return nil, err
}
return &id, nil
}
func (storage *FileStorage) Read(id model.Identifier) (*model.Photo, error) {
file, err := os.Open(path.Join(storage.baseDir, id.Value()))
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
return model.PhotoOf(id, data), nil
}
func (storage *FileStorage) Delete(id model.Identifier) error {
if err := os.Remove(path.Join(storage.baseDir, id.Value())); err != nil {
return err
}
return nil
}
|
Work on older Python without assertIn method. | #!/usr/bin/env python
# vim: set ts=4 sw=4 et sts=4 ai:
#
# Test some basic functionality.
#
import unittest
import os
import sys
sys.path.append('..')
class TestQBasic(unittest.TestCase):
def setUp(self):
if os.path.exists('/tmp/q'):
os.remove('/tmp/q')
def tearDown(self):
self.setUp()
def assertInQLog(self, string):
self.assertTrue(os.path.exists('/tmp/q'))
logdata = open('/tmp/q', 'r').read()
try:
self.assertIn(string, logdata)
except AttributeError:
self.assertTrue(string in logdata)
def test_q_log_message(self):
import q
q.q('Test message')
self.assertInQLog('Test message')
def test_q_function_call(self):
import q
@q.t
def test(arg):
return 'RetVal'
self.assertEqual('RetVal', test('ArgVal'))
self.assertInQLog('ArgVal')
self.assertInQLog('RetVal')
unittest.main()
| #!/usr/bin/env python
# vim: set ts=4 sw=4 et sts=4 ai:
#
# Test some basic functionality.
#
import unittest
import os
import sys
sys.path.append('..')
class TestQBasic(unittest.TestCase):
def setUp(self):
if os.path.exists('/tmp/q'):
os.remove('/tmp/q')
def tearDown(self):
self.setUp()
def assertInQLog(self, string):
self.assertTrue(os.path.exists('/tmp/q'))
self.assertIn(string, open('/tmp/q', 'r').read())
def test_q_log_message(self):
import q
q.q('Test message')
self.assertInQLog('Test message')
def test_q_function_call(self):
import q
@q.t
def test(arg):
return 'RetVal'
self.assertEqual('RetVal', test('ArgVal'))
self.assertInQLog('ArgVal')
self.assertInQLog('RetVal')
unittest.main()
|
Update API to look at one folder and return processor | """
This module provides a simplified API for invoking the Geneways input processor
, which converts extracted information collected with Geneways into INDRA
statements.
See publication:
Rzhetsky, Andrey, Ivan Iossifov, Tomohiro Koike, Michael Krauthammer, Pauline
Kra, Mitzi Morris, Hong Yu et al. "GeneWays: a system for extracting,
analyzing, visualizing, and integrating molecular pathway data."
Journal of biomedical informatics 37, no. 1 (2004): 43-53.
"""
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
from indra.sources.geneways.processor import GenewaysProcessor
# Path to the INDRA data folder
path_this = os.path.dirname(os.path.abspath(__file__))
data_folder = os.path.join(path_this, '../../../data')
def process_geneways(input_folder=data_folder):
"""Reads in Geneways data and returns a list of statements.
Parameters
----------
input_folder : Optional[str]
A folder in which to search for Geneways data. Looks for these
Geneways extraction data files: human_action.txt,
human_actionmention.txt, human_symbols.txt.
Omit this parameter to use the default input folder which is
indra/data.
Returns
-------
gp : GenewaysProcessor
A GenewaysProcessor object which contains a list of INDRA statements
generated from the Geneways action mentions.
"""
gp = GenewaysProcessor(input_folder)
return gp
| """
This module provides a simplified API for invoking the Geneways input processor
, which converts extracted information collected with Geneways into INDRA
statements.
See publication:
Rzhetsky, Andrey, Ivan Iossifov, Tomohiro Koike, Michael Krauthammer, Pauline
Kra, Mitzi Morris, Hong Yu et al. "GeneWays: a system for extracting,
analyzing, visualizing, and integrating molecular pathway data."
Journal of biomedical informatics 37, no. 1 (2004): 43-53.
"""
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from indra.sources.geneways.processor import GenewaysProcessor
def process_geneways(search_path=None):
"""Reads in Geneways data and returns a list of statements.
Parameters
----------
search_path : list
a list of directories in which to search for Geneways data.
Looks for these Geneways extraction data files:
human_action.txt, human_actionmention.txt,
human_symbols.txt. Omit this parameter to use the default search path.
Returns
-------
statements : list[indra.statements.Statement]
A list of INDRA statements generated from the Geneways action mentions.
"""
if search_path is None:
search_path = ['./data', '../data', '../../data', '~/data', '.']
processor = GenewaysProcessor(search_path)
return processor.statements
|
Revert "Properly cast dates to y-m-d format"
This reverts commit 7910dace9fc93ab5d5494e68cdee21867ad4558b partially. | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Timeline extends Model
{
use HasFactory;
protected $table = 'timeline';
protected $fillable = ['date', 'item_id', 'item_type'];
public function item() {
return $this->morphTo();
}
public function flight() {
return $this->belongsTo(Flight::class, 'item_id')->whereItemType(Flight::class);
}
public function promotion() {
return $this->belongsTo(Promotion::class, 'item_id')->whereItemType(Promotion::class);
}
public function launch() {
return $this->belongsTo(Launch::class, 'item_id')->whereItemType(Launch::class);
}
}
| <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Timeline extends Model
{
use HasFactory;
protected $table = 'timeline';
protected $fillable = ['date', 'item_id', 'item_type'];
protected $dates = ['date'];
protected $casts = [
'date' => 'date:Y-m-d'
];
public function item() {
return $this->morphTo();
}
public function flight() {
return $this->belongsTo(Flight::class, 'item_id')->whereItemType(Flight::class);
}
public function promotion() {
return $this->belongsTo(Promotion::class, 'item_id')->whereItemType(Promotion::class);
}
public function launch() {
return $this->belongsTo(Launch::class, 'item_id')->whereItemType(Launch::class);
}
}
|
Remove message traits from Signup controller | SignupController = Space.accountsUi.SignupController;
SignupController.extend(Donations, 'OrgRegistrationsController', {
dependencies: {
orgRegStore: 'Donations.OrgRegistrationsStore',
signupsStore: 'Space.accountsUi.SignupsStore'
},
requestSignupEvent: 'Donations.OrgRegistrationRequested',
initiateSignupCommand: 'Donations.RegisterOrganization',
eventSubscriptions() {
let superSubs = SignupController.prototype.eventSubscriptions.call(this);
return superSubs.concat([{
'Donations.OrgRegistrationFormSubmitted': this._onOrgRegistrationFormSubmit,
'Space.accountsUi.SignupCompleted': this._onSignupCompleted
}]);
},
_onOrgRegistrationFormSubmit() {
this.publish(new Donations.OrgRegistrationRequested({
name: this.orgRegStore.orgName(),
password: new Password(this.orgRegStore.password()),
country: new Country(this.orgRegStore.orgCountry()),
contact: new Donations.Contact({
email: new EmailAddress(this.orgRegStore.contactEmail()),
name: this.orgRegStore.contactName(),
phone: this.orgRegStore.contactPhone()
})
}));
},
_onSignupCompleted() {
this.publish(new Space.accountsUi.LoginRequested({
user: this.orgRegStore.contactEmail(),
password: new Password(this.orgRegStore.password())
}));
}
});
| SignupController = Space.accountsUi.SignupController;
SignupController.extend(Donations, 'OrgRegistrationsController', {
mixin: [
Space.messaging.EventSubscribing,
Space.messaging.EventPublishing
],
dependencies: {
orgRegStore: 'Donations.OrgRegistrationsStore',
signupsStore: 'Space.accountsUi.SignupsStore'
},
requestSignupEvent: 'Donations.OrgRegistrationRequested',
initiateSignupCommand: 'Donations.RegisterOrganization',
eventSubscriptions() {
let superSubs = SignupController.prototype.eventSubscriptions.call(this);
return superSubs.concat([{
'Donations.OrgRegistrationFormSubmitted': this._onOrgRegistrationFormSubmit,
'Space.accountsUi.SignupCompleted': this._onSignupCompleted
}]);
},
_onOrgRegistrationFormSubmit() {
this.publish(new Donations.OrgRegistrationRequested({
name: this.orgRegStore.orgName(),
password: new Password(this.orgRegStore.password()),
country: new Country(this.orgRegStore.orgCountry()),
contact: new Donations.Contact({
email: new EmailAddress(this.orgRegStore.contactEmail()),
name: this.orgRegStore.contactName(),
phone: this.orgRegStore.contactPhone()
})
}));
},
_onSignupCompleted() {
this.publish(new Space.accountsUi.LoginRequested({
user: this.orgRegStore.contactEmail(),
password: new Password(this.orgRegStore.password())
}));
}
});
|
Fix the identifier-ness test in maybe_quote. | function quote(s) {
return "\"" + s.replace(/([\\\"])/, "\\$1") + "\"";
}
function maybe_quote(s) {
if (/^[_A-Za-z][_A-Za-z0-9]*$/.test(s))
return s;
else
return quote(s);
}
function repr(x, max_depth) {
if (max_depth == undefined)
max_depth = 1;
if (x === null) {
return "null";
} else if (x instanceof java.lang.Iterable) {
var elems = [];
var i = x.iterator();
while (i.hasNext())
elems.push(repr(i.next()));
return x["class"] + ":[ " + elems.join(", ") + " ]";
} else if (typeof x == "object") {
if ("hashCode" in x)
// Guess that it's a Java object.
return String(x);
if (max_depth <= 0)
return "{...}";
var elems = [];
for (var k in x)
elems.push(maybe_quote(k) + ": " + repr(x[k], max_depth - 1));
return "{ " + elems.join(", ") + " }";
} else if (typeof x == "string") {
return quote(x);
} else {
return String(x);
}
}
| function quote(s) {
return "\"" + s.replace(/([\\\"])/, "\\$1") + "\"";
}
function maybe_quote(s) {
if (/[\\\"]/.test(s))
return quote(s);
else
return s;
}
function repr(x, max_depth) {
if (max_depth == undefined)
max_depth = 1;
if (x === null) {
return "null";
} else if (x instanceof java.lang.Iterable) {
var elems = [];
var i = x.iterator();
while (i.hasNext())
elems.push(repr(i.next()));
return x["class"] + ":[ " + elems.join(", ") + " ]";
} else if (typeof x == "object") {
if ("hashCode" in x)
// Guess that it's a Java object.
return String(x);
if (max_depth <= 0)
return "{...}";
var elems = [];
for (var k in x)
elems.push(maybe_quote(k) + ": " + repr(x[k], max_depth - 1));
return "{ " + elems.join(", ") + " }";
} else if (typeof x == "string") {
return quote(x);
} else {
return String(x);
}
}
|
Remove shebang line from non-script. | from twisted.protocols import amp
from twisted.cred.error import UnauthorizedLogin
# commands to server side
class Login(amp.Command):
arguments = [("username", amp.String()), ("password", amp.String())]
response = []
errors = {UnauthorizedLogin: "UnauthorizedLogin"}
# If we set requiresAnswer = False, then the client-side callRemote
# returns None instead of a deferred, and we can't attach callbacks.
# So be sure to return an empty dict instead.
# TODO doc patch for twisted
class SendToAll(amp.Command):
arguments = [("message", amp.String())]
response = []
class SendToUser(amp.Command):
arguments = [("message", amp.String()), "username", amp.String()]
response = []
# commands to client side
class Send(amp.Command):
arguments = [("message", amp.String()), ("sender", amp.String())]
response = []
class AddUser(amp.Command):
arguments = [("user", amp.String())]
response = []
class DelUser(amp.Command):
arguments = [("user", amp.String())]
response = []
class LoggedIn(amp.Command):
arguments = [("ok", amp.Boolean())]
response = []
| #!/usr/bin/env python
from twisted.protocols import amp
from twisted.cred.error import UnauthorizedLogin
# commands to server side
class Login(amp.Command):
arguments = [("username", amp.String()), ("password", amp.String())]
response = []
errors = {UnauthorizedLogin: "UnauthorizedLogin"}
# If we set requiresAnswer = False, then the client-side callRemote
# returns None instead of a deferred, and we can't attach callbacks.
# So be sure to return an empty dict instead.
# TODO doc patch for twisted
class SendToAll(amp.Command):
arguments = [("message", amp.String())]
response = []
class SendToUser(amp.Command):
arguments = [("message", amp.String()), "username", amp.String()]
response = []
# commands to client side
class Send(amp.Command):
arguments = [("message", amp.String()), ("sender", amp.String())]
response = []
class AddUser(amp.Command):
arguments = [("user", amp.String())]
response = []
class DelUser(amp.Command):
arguments = [("user", amp.String())]
response = []
class LoggedIn(amp.Command):
arguments = [("ok", amp.Boolean())]
response = []
|
Fix retry for experiment group | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
from api.settings import CeleryTasks, Intervals
from api.celery_api import app as celery_app
from experiments.tasks import build_experiment
from projects.models import ExperimentGroup
logger = logging.getLogger('polyaxon.tasks.projects')
@celery_app.task(name=CeleryTasks.EXPERIMENTS_START_GROUP, bind=True, max_retries=None)
def start_group_experiments(self, experiment_group_id):
try:
experiment_group = ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
logger.info('ExperimentGroup `{}` does not exist anymore.'.format(experiment_group_id))
return
pending_experiments = experiment_group.pending_experiments
experiment_to_start = experiment_group.n_experiments_to_start
while experiment_to_start > 0 and pending_experiments:
experiment = pending_experiments.pop()
build_experiment.delay(experiment_id=experiment.id)
experiment_to_start -= 1
if pending_experiments:
# Schedule another task
self.retry(countdown=Intervals.EXPERIMENTS_SCHEDULER)
| # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
from api.settings import CeleryTasks, Intervals
from api.celery_api import app as celery_app
from experiments.tasks import build_experiment
from projects.models import ExperimentGroup
logger = logging.getLogger('polyaxon.tasks.projects')
@celery_app.task(name=CeleryTasks.EXPERIMENTS_START_GROUP, bind=True)
def start_group_experiments(self, experiment_group_id):
try:
experiment_group = ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
logger.info('ExperimentGroup `{}` does not exist anymore.'.format(experiment_group_id))
return
pending_experiments = experiment_group.pending_experiments
experiment_to_start = experiment_group.n_experiments_to_start
while experiment_to_start > 0 and pending_experiments:
experiment = pending_experiments.pop()
build_experiment.delay(experiment_id=experiment.id)
experiment_to_start -= 1
if pending_experiments:
# Schedule another task
self.retry(countdown=Intervals.EXPERIMENTS_SCHEDULER, max_retries=None)
|
Allow user code to call the addinfo() method on the profiler object. | """High-perfomance logging profiler, mostly written in C."""
import _hotshot
from _hotshot import ProfilerError
class Profile:
def __init__(self, logfn, lineevents=0, linetimings=1):
self.lineevents = lineevents and 1 or 0
self.linetimings = (linetimings and lineevents) and 1 or 0
self._prof = p = _hotshot.profiler(
logfn, self.lineevents, self.linetimings)
def close(self):
self._prof.close()
def start(self):
self._prof.start()
def stop(self):
self._prof.stop()
def addinfo(self, key, value):
self._prof.addinfo(key, value)
# These methods offer the same interface as the profile.Profile class,
# but delegate most of the work to the C implementation underneath.
def run(self, cmd):
import __main__
dict = __main__.__dict__
return self.runctx(cmd, dict, dict)
def runctx(self, cmd, globals, locals):
code = compile(cmd, "<string>", "exec")
self._prof.runcode(code, globals, locals)
return self
def runcall(self, func, *args, **kw):
return self._prof.runcall(func, args, kw)
| """High-perfomance logging profiler, mostly written in C."""
import _hotshot
from _hotshot import ProfilerError
class Profile:
def __init__(self, logfn, lineevents=0, linetimings=1):
self.lineevents = lineevents and 1 or 0
self.linetimings = (linetimings and lineevents) and 1 or 0
self._prof = p = _hotshot.profiler(
logfn, self.lineevents, self.linetimings)
def close(self):
self._prof.close()
def start(self):
self._prof.start()
def stop(self):
self._prof.stop()
# These methods offer the same interface as the profile.Profile class,
# but delegate most of the work to the C implementation underneath.
def run(self, cmd):
import __main__
dict = __main__.__dict__
return self.runctx(cmd, dict, dict)
def runctx(self, cmd, globals, locals):
code = compile(cmd, "<string>", "exec")
self._prof.runcode(code, globals, locals)
return self
def runcall(self, func, *args, **kw):
return self._prof.runcall(func, args, kw)
|
Fix unicode string syntax for Python 3 | from os.path import abspath, join, dirname
import random
__title__ = 'names'
__version__ = '0.2'
__author__ = 'Trey Hunner'
__license__ = 'MIT'
full_path = lambda filename: abspath(join(dirname(__file__), filename))
FILES = {
'first:male': full_path('dist.male.first'),
'first:female': full_path('dist.female.first'),
'last': full_path('dist.all.last'),
}
def get_name(filename):
selected = random.random() * 90
with open(filename) as name_file:
for line in name_file:
name, _, cummulative, _ = line.split()
if float(cummulative) > selected:
return name
def get_first_name(gender=None):
if gender not in ('male', 'female'):
gender = random.choice(('male', 'female'))
return get_name(FILES['first:%s' % gender]).capitalize()
def get_last_name():
return get_name(FILES['last']).capitalize()
def get_full_name(gender=None):
return unicode("%s %s").format(get_first_name(gender), get_last_name())
| from os.path import abspath, join, dirname
import random
__title__ = 'names'
__version__ = '0.2'
__author__ = 'Trey Hunner'
__license__ = 'MIT'
full_path = lambda filename: abspath(join(dirname(__file__), filename))
FILES = {
'first:male': full_path('dist.male.first'),
'first:female': full_path('dist.female.first'),
'last': full_path('dist.all.last'),
}
def get_name(filename):
selected = random.random() * 90
with open(filename) as name_file:
for line in name_file:
name, _, cummulative, _ = line.split()
if float(cummulative) > selected:
return name
def get_first_name(gender=None):
if gender not in ('male', 'female'):
gender = random.choice(('male', 'female'))
return get_name(FILES['first:%s' % gender]).capitalize()
def get_last_name():
return get_name(FILES['last']).capitalize()
def get_full_name(gender=None):
return u"%s %s" % (get_first_name(gender), get_last_name())
|
Bump up version to 0.3 | # -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import find_packages
setup(
name = 'djiki',
version = '0.3',
description = 'Django Wiki Application',
url = 'https://github.com/emesik/djiki/',
long_description = open('README.rst').read(),
author = 'Michał Sałaban',
author_email = 'michal@salaban.info',
requires = [
'creole',
'diff_match_patch',
'sorl_thumbnail',
],
packages = find_packages(),
include_package_data = True,
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
zip_safe = False,
)
| # -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import find_packages
setup(
name = 'djiki',
version = '0.2',
description = 'Django Wiki Application',
url = 'https://github.com/emesik/djiki/',
long_description = open('README.rst').read(),
author = 'Michał Sałaban',
author_email = 'michal@salaban.info',
requires = [
'creole',
'diff_match_patch',
'sorl_thumbnail',
],
packages = find_packages(),
include_package_data = True,
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
zip_safe = False,
)
|
Increase test timeout for Gitter beforeEach tests | /* jshint mocha: true */
'use strict';
const assert = require('assert');
const gitter = require('../lib/gitter');
const jsonist = require('jsonist');
let nodes;
let post = jsonist.post;
beforeEach(function() {
this.timeout(10000);
jsonist.post = function() {};
nodes = [
{
name: 'foo',
offline: true,
},{
name: 'bar',
offline: false,
}
];
});
afterEach(function() {
jsonist.post = post;
});
describe('gitter', function() {
it('posts nodes to gitter', function(done) {
let i = 0;
const level = ['error', 'success'];
jsonist.post = function(url, data, opts, cb) {
assert.equal(url, process.env.GITTER_WEBHOOK_URL);
assert.equal(typeof data.message, 'string');
assert.equal(data.level, level[i++]);
cb(null, { success: true }, {});
};
gitter.post(nodes, done);
});
it('returns any errors', function(done) {
jsonist.post = function(url, data, opts, cb) {
cb(new Error('I am borked'));
};
gitter.post(nodes, function(err) {
assert(/I am borked/.test(err));
done();
});
});
});
| /* jshint mocha: true */
'use strict';
const assert = require('assert');
const gitter = require('../lib/gitter');
const jsonist = require('jsonist');
let nodes;
let post = jsonist.post;
beforeEach(function() {
jsonist.post = function() {};
nodes = [
{
name: 'foo',
offline: true,
},{
name: 'bar',
offline: false,
}
];
});
afterEach(function() {
jsonist.post = post;
});
describe('gitter', function() {
it('posts nodes to gitter', function(done) {
let i = 0;
const level = ['error', 'success'];
jsonist.post = function(url, data, opts, cb) {
assert.equal(url, process.env.GITTER_WEBHOOK_URL);
assert.equal(typeof data.message, 'string');
assert.equal(data.level, level[i++]);
cb(null, { success: true }, {});
};
gitter.post(nodes, done);
});
it('returns any errors', function(done) {
jsonist.post = function(url, data, opts, cb) {
cb(new Error('I am borked'));
};
gitter.post(nodes, function(err) {
assert(/I am borked/.test(err));
done();
});
});
});
|
Add support for models that have .account | module.exports = function(app) {
var Role = app.models.Role;
Role.registerResolver('teamMember', function(role, context, cb) {
function reject(msg) {
console.log(msg);
process.nextTick(function() {
cb(null, false);
});
}
var userId = context.accessToken.userId;
if (!userId) {
return reject('Invalid access token');
}
context.model.findById(context.modelId, function provideModel(err, model) {
if (err || !model) {
return reject('No relative model found.');
}
var modelWithUsers = null;
if (model.users) {
modelWithUsers = model;
}
if (model.account) {
modelWithUsers = model.account;
}
if (!modelWithUsers) {
reject('Model cannot be linked to user, so this role should fail.');
}
modelWithUsers.users.findById(userId, function postFind(err, users) {
if (err || !users) {
reject("Unauthorized!");
} else {
cb(null, true);
}
});
});
});
}
| module.exports = function(app) {
var Role = app.models.Role;
Role.registerResolver('teamMember', function(role, context, cb) {
function reject(msg) {
console.log(msg);
process.nextTick(function() {
cb(null, false);
});
}
var userId = context.accessToken.userId;
if (!userId) {
return reject('Invalid access token');
}
context.model.findById(context.modelId, function provideModel(err, model) {
if (err || !model) { return reject('No relative model found.');}
model.users.findById(userId, function postFind(err, users) {
if (err || !users) {
reject("Unauthorized!");
} else {
cb(null, true);
}
});
});
});
};
|
Revert "Only ask for public privileges"
This reverts commit 47b95cb58a00364fd3146c10e12ba4b93ed45f60. | import * as ACTION_TYPES from '../constants/action_types'
function extractToken(hash, oldToken) {
const match = hash.match(/access_token=([^&]+)/)
let token = !!match && match[1]
if (!token) {
token = oldToken
}
return token
}
export function checkAuth(dispatch, oldToken, location) {
const token = extractToken(location.hash, oldToken)
if (window.history && window.history.replaceState) {
window.history.replaceState(window.history.state, document.title, window.location.pathname)
} else {
document.location.hash = '' // this is a fallback for IE < 10
}
if (token) {
dispatch({
type: ACTION_TYPES.ACCESS_TOKEN.SAVE,
payload: token,
})
} else {
const url = 'https://' + ENV.AUTH_DOMAIN + '/api/oauth/authorize.html' +
'?response_type=token' +
'&scope=web_app+public' +
'&client_id=' + ENV.AUTH_CLIENT_ID +
'&redirect_uri=' + ENV.AUTH_REDIRECT_URI
window.location.href = url
}
}
export function resetAuth(dispatch, oldToken, location) {
if (oldToken) {
dispatch({
type: ACTION_TYPES.ACCESS_TOKEN.DELETE,
})
}
checkAuth(dispatch, null, location)
}
| import * as ACTION_TYPES from '../constants/action_types'
function extractToken(hash, oldToken) {
const match = hash.match(/access_token=([^&]+)/)
let token = !!match && match[1]
if (!token) {
token = oldToken
}
return token
}
export function checkAuth(dispatch, oldToken, location) {
const token = extractToken(location.hash, oldToken)
if (window.history && window.history.replaceState) {
window.history.replaceState(window.history.state, document.title, window.location.pathname)
} else {
document.location.hash = '' // this is a fallback for IE < 10
}
if (token) {
dispatch({
type: ACTION_TYPES.ACCESS_TOKEN.SAVE,
payload: token,
})
} else {
const url = 'https://' + ENV.AUTH_DOMAIN + '/api/oauth/authorize.html' +
'?response_type=token' +
'&scope=public' +
'&client_id=' + ENV.AUTH_CLIENT_ID +
'&redirect_uri=' + ENV.AUTH_REDIRECT_URI
window.location.href = url
}
}
export function resetAuth(dispatch, oldToken, location) {
if (oldToken) {
dispatch({
type: ACTION_TYPES.ACCESS_TOKEN.DELETE,
})
}
checkAuth(dispatch, null, location)
}
|
Change assertGet body check from StringType to str | import unittest
import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
hosts = []
def assertGet(self, endpoint="", status_code=200, body=""):
"""
Asserts GET requests on a given endpoint
"""
for host in self.hosts:
response = requests.get(host+endpoint)
self.assertEqual(response.status_code, status_code)
if isinstance(body, str):
self.assertIn(body, response.content)
elif isinstance(body, list):
for content in body:
self.assertIn(content, response.content)
| import types
import unittest
import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
hosts = []
def assertGet(self, endpoint="", status_code=200, body=""):
"""
Asserts GET requests on a given endpoint
"""
for host in self.hosts:
response = requests.get(host+endpoint)
self.assertEqual(response.status_code, status_code)
if isinstance(body, types.StringType):
self.assertIn(body, response.content)
elif isinstance(body, list):
for content in body:
self.assertIn(content, response.content)
|
Update to stream bytes to checksum algo. | package bagutil
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"errors"
"fmt"
"hash"
"io"
"os"
)
// Takes a filepath as a string and produces a checksum.
func FileChecksum(filepath string, algo string) string {
hsh, err := newHash(algo)
if err != nil {
panic(err)
}
file, err := os.Open(filepath)
if err != nil {
panic(err)
}
_, err = io.Copy(hsh, file)
if err != nil {
panic(err)
}
byteSum := hsh.Sum(nil)
return fmt.Sprintf("%x", byteSum) // Convert to base16 on formatting.
}
func newHash(algo string) (hash.Hash, error) {
switch algo {
case "md5":
return md5.New(), nil
case "sha1":
return sha1.New(), nil
case "sha256":
return sha256.New(), nil
case "sha512":
return sha512.New(), nil
}
return nil, errors.New("Unsupported hash value.")
}
| package bagutil
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"errors"
"fmt"
"hash"
"io/ioutil"
"os"
)
// Takes a filepath as a string and produces a checksum.
func FileChecksum(filepath string, algo string) string {
hsh, err := newHash(algo)
if err != nil {
panic(err)
}
file, err := os.Open(filepath)
if err != nil {
panic(err)
}
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
panic(err)
}
hsh.Write(fileBytes)
byteSum := hsh.Sum(nil)
return fmt.Sprintf("%x", byteSum) // Convert to base16 on formatting.
}
func newHash(algo string) (hash.Hash, error) {
switch algo {
case "md5":
return md5.New(), nil
case "sha1":
return sha1.New(), nil
case "sha256":
return sha256.New(), nil
case "sha512":
return sha512.New(), nil
}
return nil, errors.New("Unsupported hash value.")
}
|
Set user for core app service correctly | <?php
namespace SimplyTestable\WebClientBundle\Controller;
class TestNotificationController extends TestViewController
{
public function urlLimitAction($test_id, $website) {
$this->getTestService()->setUser($this->getUser());
$testRetrievalOutcome = $this->getTestRetrievalOutcome($website, $test_id);
if ($testRetrievalOutcome->hasResponse()) {
return $this->sendNotFoundResponse();
}
$this->setTemplate('SimplyTestableWebClientBundle:Partials:test-url-limit-notification.html.twig');
return $this->sendResponse(array(
'is_logged_in' => !$this->getUserService()->isPublicUser($this->getUser()),
'remote_test_summary' => $this->getTestService()->getRemoteTestSummary()
));
}
}
| <?php
namespace SimplyTestable\WebClientBundle\Controller;
class TestNotificationController extends TestViewController
{
public function urlLimitAction($test_id, $website) {
$testRetrievalOutcome = $this->getTestRetrievalOutcome($website, $test_id);
if ($testRetrievalOutcome->hasResponse()) {
return $this->sendNotFoundResponse();
}
$this->getTestService()->setUser($this->getUser());
$this->setTemplate('SimplyTestableWebClientBundle:Partials:test-url-limit-notification.html.twig');
return $this->sendResponse(array(
'is_logged_in' => !$this->getUserService()->isPublicUser($this->getUser()),
'remote_test_summary' => $this->getTestService()->getRemoteTestSummary()
));
}
}
|
Add missing numpy import, and cleanup the rest | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import print_function
import numpy as np
from astropy.tests.helper import remote_data
from astropy.table import Table
import astropy.units as u
from ... import nist
@remote_data
class TestNist:
def test_query_async(self):
response = nist.core.Nist.query_async(4000 * u.nm, 7000 * u.nm)
assert response is not None
def test_query(self):
result = nist.core.Nist.query(4000 * u.nm, 7000 * u.nm)
assert isinstance(result, Table)
# check that no javascript was left in the table
# (regression test for 1355)
assert np.all(result['TP'] == 'T8637')
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import print_function
from astropy.tests.helper import remote_data
from astropy.table import Table
import astropy.units as u
import requests
import imp
from ... import nist
imp.reload(requests)
@remote_data
class TestNist:
def test_query_async(self):
response = nist.core.Nist.query_async(4000 * u.nm, 7000 * u.nm)
assert response is not None
def test_query(self):
result = nist.core.Nist.query(4000 * u.nm, 7000 * u.nm)
assert isinstance(result, Table)
# check that no javascript was left in the table
# (regression test for 1355)
assert np.all(result['TP'] == 'T8637')
|
Fix return type in DocBlock. | <?php
/**
* ExtReferenceConverterInterface class file
*/
namespace Graviton\DocumentBundle\Service;
/**
* Extref converter interface
*
* @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @link http://swisscom.ch
*/
interface ExtReferenceConverterInterface
{
/**
* return the mongodb representation from a extref URL
*
* @param string $url Extref URL
* @return object
* @throws \InvalidArgumentException
*/
public function getDbRef($url);
/**
* return the extref URL
*
* @param object $dbRef DB ref
* @return string
* @throws \InvalidArgumentException
*/
public function getUrl($dbRef);
}
| <?php
/**
* ExtReferenceConverterInterface class file
*/
namespace Graviton\DocumentBundle\Service;
/**
* Extref converter interface
*
* @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @link http://swisscom.ch
*/
interface ExtReferenceConverterInterface
{
/**
* return the mongodb representation from a extref URL
*
* @param string $url Extref URL
* @return array
* @throws \InvalidArgumentException
*/
public function getDbRef($url);
/**
* return the extref URL
*
* @param object $dbRef DB ref
* @return string
* @throws \InvalidArgumentException
*/
public function getUrl($dbRef);
}
|
Update EntityContentRevisions to use es6 class. | /*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2015 Canonical Ltd.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
General Public License for more details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
class EntityContentRevisions extends React.Component {
render() {
const revisions = this.props.revisions;
return (
<div className="revisions section" id="revisions">
<h3 className="section__title">{revisions.length} Revisions</h3>
</div>
);
}
};
EntityContentRevisions.propTypes = {
revisions: React.PropTypes.array.isRequired
};
YUI.add('entity-content-revisions', function() {
juju.components.EntityContentRevisions = EntityContentRevisions;
}, '0.1.0', {requires: []});
| /*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2015 Canonical Ltd.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
General Public License for more details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
const EntityContentRevisions = React.createClass({
propTypes: {
revisions: React.PropTypes.array.isRequired
},
render: function() {
const revisions = this.props.revisions;
return (
<div className="revisions section" id="revisions">
<h3 className="section__title">{revisions.length} Revisions</h3>
</div>
);
}
});
YUI.add('entity-content-revisions', function() {
juju.components.EntityContentRevisions = EntityContentRevisions;
}, '0.1.0', {requires: []});
|
Allow tests to be run with Python <2.6. | # -*- coding: latin-1 -*-
import unittest
from github2.issues import Issue
from github2.client import Github
class ReprTests(unittest.TestCase):
"""__repr__ must return strings, not unicode objects."""
def test_issue(self):
"""Issues can have non-ASCII characters in the title."""
i = Issue(title=u'abcdé')
self.assertEqual(str, type(repr(i)))
class RateLimits(unittest.TestCase):
"""
How should we handle actual API calls such that tests can run?
Perhaps the library should support a ~/.python_github2.conf from which to
get the auth?
"""
def test_delays(self):
import datetime
USERNAME = ''
API_KEY = ''
client = Github(username=USERNAME, api_token=API_KEY,
requests_per_second=.5)
client.users.show('defunkt')
start = datetime.datetime.now()
client.users.show('mojombo')
end = datetime.datetime.now()
delta = end - start
delta_seconds = delta.days * 24 * 60 * 60 + delta.seconds
self.assertTrue(delta_seconds >= 2,
"Expected .5 reqs per second to require a 2 second delay between "
"calls.")
| # -*- coding: latin-1 -*-
import unittest
from github2.issues import Issue
from github2.client import Github
class ReprTests(unittest.TestCase):
"""__repr__ must return strings, not unicode objects."""
def test_issue(self):
"""Issues can have non-ASCII characters in the title."""
i = Issue(title=u'abcdé')
self.assertEqual(str, type(repr(i)))
class RateLimits(unittest.TestCase):
"""
How should we handle actual API calls such that tests can run?
Perhaps the library should support a ~/.python_github2.conf from which to
get the auth?
"""
def test_delays(self):
import datetime
USERNAME = ''
API_KEY = ''
client = Github(username=USERNAME, api_token=API_KEY,
requests_per_second=.5)
client.users.show('defunkt')
start = datetime.datetime.now()
client.users.show('mojombo')
end = datetime.datetime.now()
self.assertGreaterEqual((end - start).total_seconds(), 2.0,
"Expected .5 reqs per second to require a 2 second delay between "
"calls.")
|
FIX: Use another port number because this port is already bound by another test somewhere. | /**
* Modules dependencies
*/
var mocha = require('mocha'),
assert = require('chai').assert,
libPath = process.env['SCRAPINODE_COV'] ? '../lib-cov' : '../lib',
scrapinode = require( libPath + '/scrapinode'),
ScrapinodeError = require(libPath + '/error/scrapinode-error'),
express = require('express'),
filed = require('filed');
// Web server
var app = express();
app.get('/',function(req,res){
setTimeout(function(){
req.pipe(filed(__dirname + '/resources/index.html')).pipe(res);
},1000);
});
app.listen(3080);
// Test suite
describe('scrapinode#createScraper(options,callback)',function(){
beforeEach(function(){
scrapinode.clearRouter();
});
describe('when the options.timeout is defined and the timeout is reached',function(){
it('should return an error Object in the callback as first argument',function(done){
scrapinode.use('localhost:3040','title',function(window){
return window.$('title').text();
});
var options = {
url : 'http://localhost:3080/',
timeout : 200,
retries : 0
};
scrapinode.createScraper(options,function(err,scraper){
assert.instanceOf(err,Error);
done();
});
});
});
}); | /**
* Modules dependencies
*/
var mocha = require('mocha'),
assert = require('chai').assert,
libPath = process.env['SCRAPINODE_COV'] ? '../lib-cov' : '../lib',
scrapinode = require( libPath + '/scrapinode'),
ScrapinodeError = require(libPath + '/error/scrapinode-error'),
express = require('express'),
filed = require('filed');
// Web server
var app = express();
app.get('/',function(req,res){
setTimeout(function(){
req.pipe(filed(__dirname + '/resources/index.html')).pipe(res);
},1000);
});
app.listen(3040);
// Test suite
describe('scrapinode#createScraper(options,callback)',function(){
beforeEach(function(){
scrapinode.clearRouter();
});
describe('when the options.timeout is defined and the timeout is reached',function(){
it('should return an error Object in the callback as first argument',function(done){
scrapinode.use('localhost:3040','title',function(window){
return window.$('title').text();
});
var options = {
url : 'http://localhost:3040/',
timeout : 200,
retries : 0
};
scrapinode.createScraper(options,function(err,scraper){
assert.instanceOf(err,Error);
done();
});
});
});
}); |
Fix stubs not being served correctly | 'use strict';
var path = require('path');
var parseBundle = require('nodecg-bundle-parser');
var express = require('express');
var app = express();
var injectScripts = require('./script_injector');
module.exports = function(bundlePath) {
var bundle = parseBundle(path.resolve(bundlePath));
app.listen(9999);
app.use('/components', express.static(path.resolve(bundle.dir, 'bower_components')));
app.use('/stubs', express.static(path.resolve(__dirname, '../stubs')));
app.get('/:panel', function(req, res, next) {
var panelName = req.params.panel;
var panel = null;
bundle.dashboard.panels.some(function(p) {
if (p.name === panelName) {
panel = p;
return true;
} else {
return false;
}
});
if (!panel) {
next();
return;
}
var fileLocation = path.join(bundle.dashboard.dir, panel.file);
var html = injectScripts(fileLocation);
res.send(html);
});
return app;
};
| 'use strict';
var path = require('path');
var parseBundle = require('nodecg-bundle-parser');
var express = require('express');
var app = express();
var injectScripts = require('./script_injector');
module.exports = function(bundlePath) {
var bundle = parseBundle(path.resolve(bundlePath));
app.listen(9999);
app.use('/components', express.static(path.resolve(__dirname, '../../bower_components')));
app.use('/stubs', express.static('stubs'));
app.get('/:panel', function(req, res, next) {
var panelName = req.params.panel;
var panel = null;
bundle.dashboard.panels.some(function(p) {
if (p.name === panelName) {
panel = p;
return true;
} else {
return false;
}
});
if (!panel) {
next();
return;
}
var fileLocation = path.join(bundle.dashboard.dir, panel.file);
var html = injectScripts(fileLocation);
res.send(html);
});
return app;
};
|
Add id and key props | import React from 'react'
import Table from '../Table'
import TableRow from '../Table/TableRow/index'
import PropTypes from 'prop-types'
const InventoryTable = ({tableRows, addRow, setEditing, saveTableRow}) => {
const columns = [
{name: "Name", type: "text"},
{name: "Amount", type: "number"}
]
const tableRowComponents = tableRows.map((tableRow, index) => {
return <TableRow id={tableRow.id} key={index} saveTableRow={saveTableRow} setEditing={setEditing} cells={tableRow.cells} editing={tableRow.editing} />
})
return(
<Table
columns={columns}
name="maltInventory"
addRow={addRow}
>
{tableRowComponents}
</Table>
)
}
InventoryTable.propTypes = {
tableRows: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number.isRequired,
tableName: PropTypes.string.isRequired,
editing: PropTypes.bool.isRequired,
readOnly: PropTypes.bool,
cells: PropTypes.arrayOf(PropTypes.shape({
tableRowId: PropTypes.number.isRequired,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]).isRequired,
type: PropTypes.string
})).isRequired
})),
addRow: PropTypes.func.isRequired,
setEditing: PropTypes.func.isRequired,
saveTableRow: PropTypes.func.isRequired
}
export default InventoryTable | import React from 'react'
import Table from '../Table'
import PropTypes from 'prop-types'
const InventoryTable = ({tableRows, addRow, setEditing, saveTableRow}) => {
const columns = [
{name: "Name", type: "text"},
{name: "Amount", type: "number"}
]
const tableRowComponents = tableRows.map((tableRow) => {
return <TableRow saveTableRow={saveTableRow} setEditing={setEditing} cells={tableRow.cells} editing={tableRow.editing} />
})
return(
<Table
columns={columns}
name="maltInventory"
addRow={addRow}
>
{tableRowComponents}
</Table>
)
}
InventoryTable.propTypes = {
tableRows: PropTypes.arrayOf(shape({
id: PropTypes.number.isRequired,
tableName: PropTypes.string.isRequired,
editing: PropTypes.bool.isRequired,
readOnly: PropTypes.bool,
cells: PropTypes.arrayOf(shape({
tableRowId: PropTypes.number.isRequired,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]).isRequired,
type: PropTypes.string
})).isRequired
})),
addRow: PropTypes.func.isRequired,
setEditing: PropTypes.func.isRequired,
saveTableRow: PropTypes.func.isRequired
}
export default InventoryTable |
Add 'watch property descriptor' action
Review URL: https://chromiumcodereview.appspot.com/9391018
git-svn-id: 1dc80909446f7a7ee3e21dd4d1b8517df524e9ee@927 fc8a088e-31da-11de-8fef-1f5ae417a2df | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.sdk;
import java.util.List;
import org.chromium.sdk.util.MethodIsBlockingException;
/**
* An object that represents a scope in JavaScript.
* TODO: consider adding object getter for both with and global scopes.
*/
public interface JsScope {
enum Type {
GLOBAL,
LOCAL,
WITH,
CLOSURE,
CATCH,
UNKNOWN
}
/**
* @return type of the scope
*/
Type getType();
/**
* @return optional subtype when type is {@link Type#WITH} and null otherwise
*/
WithScope asWithScope();
/**
* @return the variables known in this scope, in lexicographical order
* @throws MethodIsBlockingException because it may need to load value from remote
*/
List<? extends JsVariable> getVariables() throws MethodIsBlockingException;
/**
* Subtype that exposes the value of the 'with' statement expression (the value might be
* already converted by ToObject).
*/
interface WithScope extends JsScope {
/**
* @throws MethodIsBlockingException because it may need to load value from remote
*/
JsValue getWithArgument() throws MethodIsBlockingException;
}
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.sdk;
import java.util.List;
import org.chromium.sdk.util.MethodIsBlockingException;
/**
* An object that represents a scope in JavaScript.
*/
public interface JsScope {
enum Type {
GLOBAL,
LOCAL,
WITH,
CLOSURE,
CATCH,
UNKNOWN
}
/**
* @return type of the scope
*/
Type getType();
/**
* @return optional subtype when type is {@link Type#WITH} and null otherwise
*/
WithScope asWithScope();
/**
* @return the variables known in this scope, in lexicographical order
* @throws MethodIsBlockingException because it may need to load value from remote
*/
List<? extends JsVariable> getVariables() throws MethodIsBlockingException;
/**
* Subtype that exposes the value of the 'with' statement expression (the value might be
* already converted by ToObject).
*/
interface WithScope extends JsScope {
/**
* @throws MethodIsBlockingException because it may need to load value from remote
*/
JsValue getWithArgument() throws MethodIsBlockingException;
}
}
|
Handle tuple error formatting same as list |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
errors.append({'detail': {key: value}})
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
|
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
errors.append({'detail': {key: value}})
elif isinstance(message, list):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
|
Remove trailing comma from json | module.exports = {
port: 3000,
public_url: 'http://127.0.0.1:3000/',
expire_minutes: 15,
db: {
host: 'localhost',
user: 'root',
password: '',
database: 'nappikauppa2'
},
email: {
mailgun: {
api_key: '###',
domain: ''
},
from: '',
errors_to: '',
errors_from: ''
},
paytrail: {
user: '13466',
password: '6pKF4jkv97zmqBJ3ZL8gUw5DfT2NMQ'
},
auth: {
method: 'static',
groups: {
admin: 'lippukauppa-admin',
checker: 'lippukauppa-tarkistin'
},
confluence: {
url: 'http://localhost:3010/groups/'
},
static: {
//Static authentication configuration
//Each user has static username, md5 hashed password and groups
users: [
{
name: 'admin',
pass: '44d6e57b24917d45e2864fccaf9f8c3c', //nappiadmin5
groups: ['lippukauppa-admin']
}
]
}
}
};
| module.exports = {
port: 3000,
public_url: 'http://127.0.0.1:3000/',
expire_minutes: 15,
db: {
host: 'localhost',
user: 'root',
password: '',
database: 'nappikauppa2'
},
email: {
mailgun: {
api_key: '###',
domain: ''
},
from: '',
errors_to: '',
errors_from: '',
},
paytrail: {
user: '13466',
password: '6pKF4jkv97zmqBJ3ZL8gUw5DfT2NMQ'
},
auth: {
method: 'static',
groups: {
admin: 'lippukauppa-admin',
checker: 'lippukauppa-tarkistin'
},
confluence: {
url: 'http://localhost:3010/groups/'
},
static: {
//Static authentication configuration
//Each user has static username, md5 hashed password and groups
users: [
{
name: 'admin',
pass: '44d6e57b24917d45e2864fccaf9f8c3c', //nappiadmin5
groups: ['lippukauppa-admin']
}
]
}
}
};
|
Return the original file if SVGO fails | 'use strict';
var isSvg = require('is-svg');
var SVGO = require('svgo');
var through = require('through2');
module.exports = function (opts) {
opts = opts || {};
return through.ctor({objectMode: true}, function (file, enc, cb) {
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new Error('Streaming is not supported'));
return;
}
if (!isSvg(file.contents)) {
cb(null, file);
return;
}
try {
var svgo = new SVGO({
multipass: opts.multipass || false,
plugins: opts.plugins || []
});
svgo.optimize(file.contents.toString('utf8'), function (res) {
if (!res.data) {
cb(null, file);
}
if (res.data && res.data.length) {
res.data = res.data.replace(/&(?!amp;)/g, '&');
}
res.data = new Buffer(res.data);
if (res.data.length < file.contents.length) {
file.contents = res.data;
}
cb(null, file);
});
} catch (err) {
cb(err);
}
});
};
| 'use strict';
var isSvg = require('is-svg');
var SVGO = require('svgo');
var through = require('through2');
module.exports = function (opts) {
opts = opts || {};
return through.ctor({objectMode: true}, function (file, enc, cb) {
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new Error('Streaming is not supported'));
return;
}
if (!isSvg(file.contents)) {
cb(null, file);
return;
}
try {
var svgo = new SVGO({
multipass: opts.multipass || false,
plugins: opts.plugins || []
});
svgo.optimize(file.contents.toString('utf8'), function (res) {
if (res.data && res.data.length) {
res.data = res.data.replace(/&(?!amp;)/g, '&');
}
res.data = new Buffer(res.data);
if (res.data.length < file.contents.length) {
file.contents = res.data;
}
cb(null, file);
});
} catch (err) {
cb(err);
}
});
};
|
[chore] Add bower.json and package.json to jshint checks | module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['*.js', 'client/app/*.js', 'server/**/*.js', 'database/**/*.js', '*.json'],
options: {
ignores: [
// (TODO: add lib files here)
]
}
},
uglify: {
my_target: {
files: {
'client/lib/dest/libs.min.js': ['client/lib/angular.js', 'client/lib/angular-ui-router.js']
}
}
},
// TODO: add uglify, concat, cssmin tasks
watch: {
files: ['client/app/*.js', 'server/**/*.js', 'database/**/*.js'],
tasks: ['jshint']
}
});
//Automatic desktop notifications for Grunt errors and warnings
grunt.loadNpmTasks('grunt-notify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
/*************************************************************
Run `$ grunt jshint` before submitting PR
Or run `$ grunt` with no arguments to watch files
**************************************************************/
grunt.registerTask('default', ['watch']);
}; | module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['*.js', 'client/app/*.js', 'server/**/*.js', 'database/**/*.js'],
options: {
ignores: [
// (TODO: add lib files here)
]
}
},
uglify: {
my_target: {
files: {
'client/lib/dest/libs.min.js': ['client/lib/angular.js', 'client/lib/angular-ui-router.js']
}
}
},
// TODO: add uglify, concat, cssmin tasks
watch: {
files: ['client/app/*.js', 'server/**/*.js', 'database/**/*.js'],
tasks: ['jshint']
}
});
//Automatic desktop notifications for Grunt errors and warnings
grunt.loadNpmTasks('grunt-notify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
/*************************************************************
Run `$ grunt jshint` before submitting PR
Or run `$ grunt` with no arguments to watch files
**************************************************************/
grunt.registerTask('default', ['watch']);
}; |
Use correct variable name when logging a less error | Package.describe({
summary: "The dynamic stylesheet language."
});
var less = require('less');
var fs = require('fs');
Package.register_extension(
"less", function (bundle, source_path, serve_path, where) {
serve_path = serve_path + '.css';
var contents = fs.readFileSync(source_path);
try {
less.render(contents.toString('utf8'), function (err, css) {
// XXX why is this a callback? it's not async.
if (err) {
bundle.error(source_path + ": Less compiler error: " + err.message);
return;
}
bundle.add_resource({
type: "css",
path: serve_path,
data: new Buffer(css),
where: where
});
});
} catch (e) {
// less.render() is supposed to report any errors via its
// callback. But sometimes, it throws them instead. This is
// probably a bug in less. Be prepared for either behavior.
bundle.error(source_path + ": Less compiler error: " + e.message);
}
}
);
| Package.describe({
summary: "The dynamic stylesheet language."
});
var less = require('less');
var fs = require('fs');
Package.register_extension(
"less", function (bundle, source_path, serve_path, where) {
serve_path = serve_path + '.css';
var contents = fs.readFileSync(source_path);
try {
less.render(contents.toString('utf8'), function (err, css) {
// XXX why is this a callback? it's not async.
if (err) {
bundle.error(source_path + ": Less compiler error: " + err.message);
return;
}
bundle.add_resource({
type: "css",
path: serve_path,
data: new Buffer(css),
where: where
});
});
} catch (e) {
// less.render() is supposed to report any errors via its
// callback. But sometimes, it throws them instead. This is
// probably a bug in less. Be prepared for either behavior.
bundle.error(source_path + ": Less compiler error: " + err.message);
}
}
);
|
Reset file as no changes were made. Just formatting | const router = require('../router')
const urls = require('../../../lib/urls')
describe('Company router', () => {
it('should define all routes', () => {
const paths = router.stack.filter(r => r.route).map(r => r.route.path)
expect(paths).to.deep.equal([
'/',
'/export',
'/:companyId/archive',
'/:companyId/unarchive',
'/:companyId',
'/:companyId/details',
urls.companies.exports.index.route,
urls.companies.exports.edit.route,
'/:companyId/business-details',
'/:companyId/hierarchies/ghq/search',
'/:companyId/hierarchies/ghq/:globalHqId/add',
'/:companyId/hierarchies/ghq/remove',
'/:companyId/hierarchies/subsidiaries/search',
'/:companyId/hierarchies/subsidiaries/:subsidiaryCompanyId/add',
'/:companyId/contacts',
'/:companyId/orders',
'/:companyId/audit',
'/:companyId/documents',
'/:companyId/manage-company-list',
'/:companyId/subsidiaries',
'/:companyId/subsidiaries/link',
])
})
})
| const router = require('../router')
const urls = require('../../../lib/urls')
describe('Company router', () => {
it('should define all routes', () => {
const paths = router.stack.filter(r => r.route).map(r => r.route.path)
expect(paths).to.deep.equal(
[
'/',
'/export',
'/:companyId/archive',
'/:companyId/unarchive',
'/:companyId',
'/:companyId/details',
urls.companies.exports.index.route,
urls.companies.exports.edit.route,
'/:companyId/business-details',
'/:companyId/hierarchies/ghq/search',
'/:companyId/hierarchies/ghq/:globalHqId/add',
'/:companyId/hierarchies/ghq/remove',
'/:companyId/hierarchies/subsidiaries/search',
'/:companyId/hierarchies/subsidiaries/:subsidiaryCompanyId/add',
'/:companyId/contacts',
'/:companyId/orders',
'/:companyId/audit',
'/:companyId/documents',
'/:companyId/manage-company-list',
'/:companyId/subsidiaries',
'/:companyId/subsidiaries/link',
])
})
})
|
Fix typo in url to github repo inside footer | <footer>
<div class="container">
<div class="row">
<div class="column-1-4">
<div class="footer-div">
<h2 class="orange-border">FOCUS</h2>
<ul>
<li><a href="/contact.php">Contact Us</a></li>
<li><a href="https://github.com/svceglug/focus" target="_blank">Source Code</a></li>
</ul>
</div>
</div>
<div class="column-1-4">
<div class="footer-div">
<h2 class="gray-border">Free Software</h2>
<ul>
<li><a href="http://www.fsmk.org/" target="_blank">Free Software Movement Karnataka</a></li>
</ul>
</div>
</div>
<div class="column-1-4">
<div class="footer-div">
<h2 class="gray-border">Creative Commons</h2>
</div>
</div>
</div>
</div>
</footer>
| <footer>
<div class="container">
<div class="row">
<div class="column-1-4">
<div class="footer-div">
<h2 class="orange-border">FOCUS</h2>
<ul>
<li><a href="/contact.php">Contact Us</a></li>
<li><a href="https://github.com/scveglug" target="_blank">Source Code</a></li>
</ul>
</div>
</div>
<div class="column-1-4">
<div class="footer-div">
<h2 class="gray-border">Free Software</h2>
<ul>
<li><a href="http://www.fsmk.org/" target="_blank">Free Software Movement Karnataka</a></li>
</ul>
</div>
</div>
<div class="column-1-4">
<div class="footer-div">
<h2 class="gray-border">Creative Commons</h2>
</div>
</div>
</div>
</div>
</footer>
|
Enable twopoint in Tuvero Basic | /**
* Basic presets: swiss direct matchings, round similar to chess, and ko
* with a matched cadrage. Simple rankings
*
* @return Presets
* @author Erik E. Lorenz <erik@tuvero.de>
* @license MIT License
* @see LICENSE
*/
define(function() {
var Presets;
Presets = {
target: 'basic',
systems: {
swiss: {
ranking: ['wins', 'headtohead', 'saldo'],
mode: 'ranks'
},
ko: {
mode: 'matched'
},
round: {
ranking: ['wins', 'sonneborn', 'headtohead', 'points']
}
},
ranking: {
components: ['buchholz', 'finebuchholz', 'points', 'saldo', 'sonneborn',
'numgames', 'wins', 'headtohead', 'threepoint', 'twopoint']
},
registration: {
minteamsize: 1,
maxteamsize: 1,
teamsizeicon: false
},
names: {
playernameurl: '',
dbplayername: 'tuverobasicplayers',
apitoken: 'apitoken',
teamsfile: 'tuvero-anmeldungen.txt'
}
};
return Presets;
});
| /**
* Basic presets: swiss direct matchings, round similar to chess, and ko
* with a matched cadrage. Simple rankings
*
* @return Presets
* @author Erik E. Lorenz <erik@tuvero.de>
* @license MIT License
* @see LICENSE
*/
define(function() {
var Presets;
Presets = {
target: 'basic',
systems: {
swiss: {
ranking: ['wins', 'headtohead', 'saldo'],
mode: 'ranks'
},
ko: {
mode: 'matched'
},
round: {
ranking: ['wins', 'sonneborn', 'headtohead', 'points']
}
},
ranking: {
components: ['buchholz', 'finebuchholz', 'points', 'saldo', 'sonneborn',
'numgames', 'wins', 'headtohead', 'threepoint']
},
registration: {
minteamsize: 1,
maxteamsize: 1,
teamsizeicon: false
},
names: {
playernameurl: '',
dbplayername: 'tuverobasicplayers',
apitoken: 'apitoken',
teamsfile: 'tuvero-anmeldungen.txt'
}
};
return Presets;
});
|
Optimize and classify only res.locals.scripts as not found | /*
* Ensures something has been found during the request. Returns 404 if
* res.template is unset, res.locals is empty and statusCode has not been set
* to 204.
*
* Should be placed at the very end of the middleware pipeline,
* after all project specific routes but before the error handler & responder.
*
* @module midwest/middleware/ensure-found
*/
'use strict';
function isEmpty(obj) {
for (const prop in obj) {
if (prop !== 'scripts' && obj.hasOwnProperty(prop)) {
return false;
}
}
return true;
}
module.exports = function ensureFound(req, res, next) {
// it seems most reasonable to check if res.locals is empty before res.statusCode
// because the former is much more common
if (res.template || res.master || !isEmpty(res.locals) || res.statusCode === 204) {
next();
} else {
// generates Not Found error if there is no page to render and no truthy
// values in data
const err = new Error(`Not found: ${req.method.toUpperCase()} ${req.path}`);
err.status = 404;
next(err);
}
};
| /*
* Ensures something has been found during the request. Returns 404 if
* res.template is unset, res.locals is empty and statusCode has not been set
* to 204.
*
* Should be placed at the very end of the middleware pipeline,
* after all project specific routes but before the error handler & responder.
*
* @module midwest/middleware/ensure-found
*/
'use strict';
const _ = require('lodash');
module.exports = function ensureFound(req, res, next) {
// it seems most reasonable to check if res.locals is empty before res.statusCode
// because the former is much more common
if (res.template || res.master || !_.isEmpty(res.locals) || res.statusCode === 204) {
next();
} else {
// generates Not Found error if there is no page to render and no truthy
// values in data
const err = new Error(`Not found: ${req.method.toUpperCase()} ${req.path}`);
err.status = 404;
next(err);
}
};
|
Increment version number now that 0.1.5 release out. | import os
from os.path import relpath, join
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def find_package_data(data_root, package_root):
files = []
for root, dirnames, filenames in os.walk(data_root):
for fn in filenames:
files.append(relpath(join(root, fn), package_root))
return files
setup(
name = "smarty",
version = "0.1.6",
author = "John Chodera, David Mobley, and others",
author_email = "john.chodera@choderalab.org",
description = ("Automated Bayesian atomtype sampling"),
license = "MIT",
keywords = "Bayesian atomtype sampling forcefield parameterization",
url = "http://github.com/open-forcefield-group/smarty",
packages=['smarty', 'smarty/tests', 'smarty/data'],
long_description=read('README.md'),
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"License :: OSI Approved :: MIT",
],
entry_points={'console_scripts': ['smarty = smarty.cli_smarty:main', 'smirky = smarty.cli_smirky:main']},
package_data={'smarty': find_package_data('smarty/data', 'smarty')},
)
| import os
from os.path import relpath, join
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def find_package_data(data_root, package_root):
files = []
for root, dirnames, filenames in os.walk(data_root):
for fn in filenames:
files.append(relpath(join(root, fn), package_root))
return files
setup(
name = "smarty",
version = "0.1.5",
author = "John Chodera, David Mobley, and others",
author_email = "john.chodera@choderalab.org",
description = ("Automated Bayesian atomtype sampling"),
license = "MIT",
keywords = "Bayesian atomtype sampling forcefield parameterization",
url = "http://github.com/open-forcefield-group/smarty",
packages=['smarty', 'smarty/tests', 'smarty/data'],
long_description=read('README.md'),
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"License :: OSI Approved :: MIT",
],
entry_points={'console_scripts': ['smarty = smarty.cli_smarty:main', 'smirky = smarty.cli_smirky:main']},
package_data={'smarty': find_package_data('smarty/data', 'smarty')},
)
|
Add user id param to getUserSettings | package com.hubspot.singularity.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.hubspot.singularity.SingularityService;
import com.hubspot.singularity.SingularityUserSettings;
import com.hubspot.singularity.data.UserManager;
import com.wordnik.swagger.annotations.ApiParam;
@Path(UserResource.PATH)
@Produces({ MediaType.APPLICATION_JSON })
public class UserResource {
public static final String PATH = SingularityService.API_BASE_PATH + "/user";
private final UserManager userManager;
@Inject
public UserResource(UserManager userManager) {
this.userManager = userManager;
}
@GET
@Path("/settings")
public Optional<SingularityUserSettings> getUserSettings(
@ApiParam("The user id to use") @PathParam("id") String id) {
return userManager.getUserSettings(id);
}
}
| package com.hubspot.singularity.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.hubspot.singularity.SingularityService;
import com.hubspot.singularity.SingularityUser;
import com.hubspot.singularity.SingularityUserSettings;
import com.hubspot.singularity.data.UserManager;
@Path(UserResource.PATH)
@Produces({ MediaType.APPLICATION_JSON })
public class UserResource {
public static final String PATH = SingularityService.API_BASE_PATH + "/user";
private final UserManager userManager;
@Inject
public UserResource(UserManager userManager) {
this.userManager = userManager;
}
@GET
@Path("/settings")
public Optional<SingularityUserSettings> getUserSettings() {
if (user.isPresent()) {
return userManager.getUserSettings(user.get().getId());
}
return Optional.absent();
}
}
|
Fix bug with incorrect case in path, damn you HFS | <?php
namespace Pheasant\Tests;
class EnumeratorTest extends \Pheasant\Tests\MysqlTestCase
{
public function setUp()
{
parent::setUp();
}
public function testEnumerating()
{
$dir = __DIR__.'/Examples';
$files = array_map(function($f) { return substr(basename($f),0,-4); },
glob($dir.'/*.php'));
$enumerator = new \Pheasant\Migrate\Enumerator($dir);
$objects = iterator_to_array($enumerator);
foreach($files as $file)
$this->assertContains('\\Pheasant\\Tests\\Examples\\'.$file, $objects);
}
}
| <?php
namespace Pheasant\Tests;
class EnumeratorTest extends \Pheasant\Tests\MysqlTestCase
{
public function setUp()
{
parent::setUp();
}
public function testEnumerating()
{
$dir = __DIR__.'/examples';
$files = array_map(function($f) { return substr(basename($f),0,-4); },
glob($dir.'/*.php'));
$enumerator = new \Pheasant\Migrate\Enumerator($dir);
$objects = iterator_to_array($enumerator);
foreach($files as $file)
$this->assertContains('\\Pheasant\\Tests\\Examples\\'.$file, $objects);
}
}
|
Make showLog and deleteLog admin commands | package com.oldterns.vilebot.handlers.admin;
import ca.szc.keratin.bot.annotation.HandlerContainer;
import ca.szc.keratin.core.event.message.recieve.ReceivePrivmsg;
import com.oldterns.vilebot.db.GroupDB;
import com.oldterns.vilebot.db.LogDB;
import com.oldterns.vilebot.util.Sessions;
import net.engio.mbassy.listener.Handler;
import java.util.regex.Pattern;
/**
* Created by eunderhi on 18/08/15.
*/
@HandlerContainer
public class GetLog {
private static final Pattern showLog = Pattern.compile("!admin showLog$");
private static final Pattern deleteLog = Pattern.compile("!admin deleteLog$");
@Handler
private void getLog(ReceivePrivmsg event) {
String text = event.getText();
String sender = event.getSender();
String username = Sessions.getSession(sender);
boolean showLogMatches = showLog.matcher(text).matches();
boolean deleteLogMatches = deleteLog.matcher(text).matches();
if(GroupDB.isAdmin(username)) {
if (showLogMatches) {
event.reply(LogDB.getLog());
} else if (deleteLogMatches) {
LogDB.deleteLog();
}
}
}
}
| package com.oldterns.vilebot.handlers.admin;
import ca.szc.keratin.bot.annotation.HandlerContainer;
import ca.szc.keratin.core.event.message.recieve.ReceivePrivmsg;
import com.oldterns.vilebot.db.LogDB;
import net.engio.mbassy.listener.Handler;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by eunderhi on 18/08/15.
*/
@HandlerContainer
public class GetLog {
private static final Pattern showLog = Pattern.compile("^!showLog$");
private static final Pattern deleteLog = Pattern.compile("^!deleteLog$");
@Handler
private void getLog(ReceivePrivmsg event) {
String text = event.getText();
boolean showLogMatches = showLog.matcher(text).matches();
boolean deleteLogMatches = deleteLog.matcher(text).matches();
if (showLogMatches) {
event.reply(LogDB.getLog());
}
else if(deleteLogMatches) {
LogDB.deleteLog();
}
}
}
|
Remove extra call to recalculateVisibility | var viewModel = null;
var LogError = null;
// This function is run when the app is ready to start interacting with the host application.
// It ensures the DOM is ready before updating the span elements with values from the current message.
$(document).ready(function () {
LogError = window.parent.LogError;
$(window).resize(onResize);
viewModel = new HeaderModel();
initializeTableUI();
updateStatus(ImportedStrings.mha_loading);
window.parent.SetShowErrorEvent(showError);
window.parent.SetUpdateStatusEvent(updateStatus);
window.parent.SetRenderItemEvent(renderItemEvent);
});
function enableSpinner() {
$("#response").css("background-image", "url(../Resources/loader.gif)");
$("#response").css("background-repeat", "no-repeat");
$("#response").css("background-position", "center");
}
function disableSpinner() {
$("#response").css("background", "none");
}
function hideStatus() {
disableSpinner();
}
function updateStatus(statusText) {
enableSpinner();
$("#status").text(statusText);
if (viewModel !== null) {
viewModel.status = statusText;
}
recalculateVisibility();
}
function renderItemEvent(headers) {
updateStatus(ImportedStrings.mha_foundHeaders);
$("#originalHeaders").text(headers);
viewModel = new HeaderModel(headers);
rebuildTables();
hideStatus();
}
function showError(error, message) {
updateStatus(message);
disableSpinner();
rebuildSections();
} | var viewModel = null;
var LogError = null;
// This function is run when the app is ready to start interacting with the host application.
// It ensures the DOM is ready before updating the span elements with values from the current message.
$(document).ready(function () {
LogError = window.parent.LogError;
$(window).resize(onResize);
viewModel = new HeaderModel();
initializeTableUI();
updateStatus(ImportedStrings.mha_loading);
window.parent.SetShowErrorEvent(showError);
window.parent.SetUpdateStatusEvent(updateStatus);
window.parent.SetRenderItemEvent(renderItemEvent);
});
function enableSpinner() {
$("#response").css("background-image", "url(../Resources/loader.gif)");
$("#response").css("background-repeat", "no-repeat");
$("#response").css("background-position", "center");
}
function disableSpinner() {
$("#response").css("background", "none");
}
function hideStatus() {
disableSpinner();
}
function updateStatus(statusText) {
enableSpinner();
$("#status").text(statusText);
if (viewModel !== null) {
viewModel.status = statusText;
}
recalculateVisibility();
}
function renderItemEvent(headers) {
updateStatus(ImportedStrings.mha_foundHeaders);
$("#originalHeaders").text(headers);
viewModel = new HeaderModel(headers);
rebuildTables();
hideStatus();
recalculateVisibility();
}
function showError(error, message) {
updateStatus(message);
disableSpinner();
rebuildSections();
} |
Fix nearest stops on iOS | <?php
require_once __DIR__.'/../../config.inc.php';
use TPGwidget\Data\Stops;
$file = 'https://prod.ivtr-od.tpg.ch/v1/GetStops.xml?key='.getenv('TPG_API_KEY').'&latitude='.($_GET['latitude'] ?? '').'&longitude='.($_GET['longitude'] ?? '');
$stops = @simplexml_load_file($file);
$output = [];
if ($stops) {
foreach ($stops->stops->stop as $stop) {
$output[] = [
'stopNameOriginal' => (string)$stop->stopName,
'stopNameDisplay' => Stops::format($stop->stopName),
'stopCode' => (string)$stop->stopCode,
];
}
}
header('Content-Type: application/json');
echo json_encode($output);
| <?php
require_once __DIR__.'/../../config.inc.php';
use TPGwidget\Data\Stops;
$file = 'https://prod.ivtr-od.tpg.ch/v1/GetStops.xml?key='.getenv('TPG_API_KEY').'&latitude='.($_GET['latitude'] ?? '').'&longitude='.($_GET['longitude'] ?? '');
$stops = @simplexml_load_file($file);
$output = [];
if ($stops) {
foreach ($stops->stops->stop as $stop) {
$output[] = [
'stopNameOriginal' => $stop->stopName,
'stopNameDisplay' => Stops::format($stop->stopName),
'stopCode' => (string)$stop->stopCode,
];
}
}
header('Content-Type: application/json');
echo json_encode($output);
|
Implement results action in town controller | <?php
namespace Listabierta\Bundle\MunicipalesBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Listabierta\Bundle\MunicipalesBundle\Form\Type\TownStep1Type;
class TownController extends Controller
{
public function indexAction(Request $request = NULL)
{
$this->step1Action($request);
}
public function vote1Action($town = NULL, Request $request = NULL)
{
$form = $this->createForm(new TownStep1Type(), NULL, array(
'action' => $this->generateUrl('municipales_candidacy_step1'),
'method' => 'POST',
)
);
$form->handleRequest($request);
if ($form->isValid())
{
}
return $this->render('MunicipalesBundle:Town:step1.html.twig', array(
'town' => $town,
'form' => $form->createView(),
'errors' => $form->getErrors()
));
}
public function resultsAction($town = NULL, Request $request = NULL)
{
return $this->render('MunicipalesBundle:Town:step_results.html.twig', array(
'town' => $town,
));
}
}
| <?php
namespace Listabierta\Bundle\MunicipalesBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Listabierta\Bundle\MunicipalesBundle\Form\Type\TownStep1Type;
class TownController extends Controller
{
public function indexAction(Request $request = NULL)
{
$this->step1Action($request);
}
public function vote1Action($town = NULL, Request $request = NULL)
{
$form = $this->createForm(new TownStep1Type(), NULL, array(
'action' => $this->generateUrl('municipales_candidacy_step1'),
'method' => 'POST',
)
);
$form->handleRequest($request);
if ($form->isValid())
{
}
return $this->render('MunicipalesBundle:Town:step1.html.twig', array(
'town' => $town,
'form' => $form->createView(),
'errors' => $form->getErrors()
));
}
}
|
Change :id to :username for more clarity | const express = require('express'),
router = express.Router(),
db = require('../models');
router.get('/', function(req, res, next) {
res.render('index');
});
router.get('/new', function(req, res, next) {
res.render('users/new');
});
router.get('/:username', function(req, res, next) {
// db.User.find({username: req.params.username}).then(function(user) {
// res.render('users/show', {user});
// });
var user = req.params.username;
res.render('users/show', {user});
});
router.get('/:username/edit', function(req, res, next) {
db.User.find({username: req.params.username}).then(function(user) {
res.render('users/edit', {user});
});
});
router.post('/', function(req, res, next) {
db.User.create(req.body).then(function() {
res.redirect('/');
});
});
// find not by ID and update
router.patch('/:username', function(req, res, next) {
db.User.findByIdAndUpdate(req.params.username, req.body.newUsername).then(function() {
res.redirect('/:username');
});
});
// find and then remove
router.delete('/:username', function(req, res, next) {
db.User.findByIdAndRemove(req.params.username).then(function() {
res.redirect('/');
});
});
module.exports = router;
| const express = require('express'),
router = express.Router(),
db = require('../models');
router.get('/', function(req, res, next) {
res.render('index');
});
router.get('/new', function(req, res, next) {
res.render('users/new');
});
router.get('/:id/edit', function(req, res, next) {
db.User.findById(req.params.id).then(function(user) {
res.render('users/edit', {user}),
function(err) {
res.send('Error!');
});
});
router.post('/', function(req, res, next) {
db.User.create(req.body).then(function() {
res.redirect('/');
});
});
router.patch('/:id', function(req, res, next) {
db.User.findByIdAndUpdate(req.params.id, req.body.newUsername).then(function() {
res.redirect('/:id');
});
});
router.delete('/:id', function(req, res, next) {
db.User.findByIdAndRemove(req.params.id).then(function() {
res.redirect('/');
});
});
module.exports = router;
|
Fix tags_fts table create migration. | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Owl\Repositories\Eloquent\Models\Tag;
use Owl\Repositories\Eloquent\Models\TagFts;
class CreateTagsFts extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::statement('CREATE VIRTUAL TABLE tags_fts USING fts3(tag_id, words);');
$tags = Tag::get();
foreach($tags as $tag){
$fts = new TagFts;
$fts->tag_id = $tag->id;
$fts->words = FtsUtils::toNgram($tag->name);
$fts->save();
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::statement('DROP TABLE tags_fts ;');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Owl\Models\Tag;
use Owl\Models\TagFts;
class CreateTagsFts extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::statement('CREATE VIRTUAL TABLE tags_fts USING fts3(tag_id, words);');
$tags = Tag::get();
foreach($tags as $tag){
$fts = new TagFts;
$fts->tag_id = $tag->id;
$fts->words = FtsUtils::toNgram($tag->name);
$fts->save();
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::statement('DROP TABLE tags_fts ;');
}
}
|
Use new AccountCreate component for setup. | /**
* Analytics common components.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { default as AccountCreate } from './account-create';
export { default as AccountSelect } from './account-select';
export { default as AnonymizeIPSwitch } from './anonymize-ip-switch';
export { default as ErrorNotice } from './error-notice';
export { default as ExistingTagError } from './existing-tag-error';
export { default as ExistingTagNotice } from './existing-tag-notice';
export { default as ProfileSelect } from './profile-select';
export { default as PropertySelect } from './property-select';
export { default as TrackingExclusionSwitches } from './tracking-exclusion-switches';
export { default as UseSnippetSwitch } from './use-snippet-switch';
| /**
* Analytics common components.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { default as AccountCreate } from './account-create-legacy';
export { default as AccountSelect } from './account-select';
export { default as AnonymizeIPSwitch } from './anonymize-ip-switch';
export { default as ErrorNotice } from './error-notice';
export { default as ExistingTagError } from './existing-tag-error';
export { default as ExistingTagNotice } from './existing-tag-notice';
export { default as ProfileSelect } from './profile-select';
export { default as PropertySelect } from './property-select';
export { default as TrackingExclusionSwitches } from './tracking-exclusion-switches';
export { default as UseSnippetSwitch } from './use-snippet-switch';
|
Allow to get up to 100 issues at once | from __future__ import print_function
import urllib, json, sys
def generate(milestone):
# Find the milestone number for the given name
milestones_json = json.loads(urllib.urlopen('https://api.github.com/repos/CoolProp/CoolProp/milestones').read())
# Map between name and number
title_to_number_map = {stone['title']: stone['number'] for stone in milestones_json}
# Find the desired number
number = title_to_number_map[milestone]
# Get the issues associated with the milestone
issues = json.loads(urllib.urlopen('https://api.github.com/repos/CoolProp/CoolProp/issues?state=all&per_page=100&milestone='+str(number)).read())
# Make sure all issues are closed in this milestone
for issue in issues:
if issue['state'] != 'closed': raise ValueError('This issue is still open: ' + issue['title'])
rst = 'Issues Closed:\n\n'+'\n'.join(['* `#{n:d} <http://github.com/CoolProp/CoolProp/issues/{n:d}>`_ : {t:s}'.format(n = issue['number'], t = issue['title']) for issue in issues])
return rst
if __name__=='__main__':
if len(sys.argv) != 2:
raise ValueError('This script should be called like this: python milestone2rst.py v5')
print(generate(sys.argv[1])) | from __future__ import print_function
import urllib, json, sys
def generate(milestone):
# Find the milestone number for the given name
milestones_json = json.loads(urllib.urlopen('https://api.github.com/repos/CoolProp/CoolProp/milestones').read())
# Map between name and number
title_to_number_map = {stone['title']: stone['number'] for stone in milestones_json}
# Find the desired number
number = title_to_number_map[milestone]
# Get the issues associated with the milestone
issues = json.loads(urllib.urlopen('https://api.github.com/repos/CoolProp/CoolProp/issues?state=all&milestone='+str(number)).read())
# Make sure all issues are closed in this milestone
for issue in issues:
if issue['state'] != 'closed': raise ValueError('This issue is still open: ' + issue['title'])
rst = 'Issues Closed:\n\n'+'\n'.join(['* `#{n:d} <http://github.com/CoolProp/CoolProp/issues/{n:d}>`_ : {t:s}'.format(n = issue['number'], t = issue['title']) for issue in issues])
return rst
if __name__=='__main__':
if len(sys.argv) != 2:
raise ValueError('This script should be called like this: python milestone2rst.py v5')
print(generate(sys.argv[1])) |
Use a workerpool for configuration file updates
Co-Authored-By: Jakob <0708d49e9b6eea40f2835438410a265908e17890@users.noreply.github.com> | package server
import (
"github.com/gammazero/workerpool"
"runtime"
)
// Parent function that will update all of the defined configuration files for a server
// automatically to ensure that they always use the specified values.
func (s *Server) UpdateConfigurationFiles() {
pool := workerpool.New(runtime.GOMAXPROCS(0))
files := s.ProcessConfiguration().ConfigurationFiles
for _, cf := range files {
f := cf
pool.Submit(func() {
p, err := s.Filesystem.SafePath(f.FileName)
if err != nil {
s.Log().WithField("error", err).Error("failed to generate safe path for configuration file")
return
}
if err := f.Parse(p, false); err != nil {
s.Log().WithField("error", err).Error("failed to parse and update server configuration file")
}
})
}
pool.StopWait()
} | package server
import (
"github.com/pterodactyl/wings/parser"
"sync"
)
// Parent function that will update all of the defined configuration files for a server
// automatically to ensure that they always use the specified values.
func (s *Server) UpdateConfigurationFiles() {
wg := new(sync.WaitGroup)
files := s.ProcessConfiguration().ConfigurationFiles
for _, v := range files {
wg.Add(1)
go func(f parser.ConfigurationFile, server *Server) {
defer wg.Done()
p, err := server.Filesystem.SafePath(f.FileName)
if err != nil {
server.Log().WithField("error", err).Error("failed to generate safe path for configuration file")
return
}
if err := f.Parse(p, false); err != nil {
server.Log().WithField("error", err).Error("failed to parse and update server configuration file")
}
}(v, s)
}
wg.Wait()
} |
Revert "Use Meteor.wrapAsync instead of Fibers."
This reverts commit b7e5328913c05a016ec760dc47431c7320af514a. | // Get our NPM stuff.
var Future = Npm.require("fibers/future");
request = Npm.require("request");
// This is our main wrapping function, using Fibers.
var requestSync = function(uri, options) {
var future = new Future();
request(uri, options, function(error, response, body) {
if (error) {
console.log(error);
throw error;
}
future.return({
response: response,
body: body
});
});
return future.wait();
};
// Use this to extend the prototype
_.extend(request, {
putSync: function(uri, options) {
options.method = "PUT";
return requestSync(uri, options);
},
patchSync: function(uri, options) {
options.method = "PATCH";
return requestSync(uri, options);
},
postSync: function(uri, options) {
options.method = "POST";
return requestSync(uri, options);
},
headSync: function(uri, options) {
options.method = "HEAD";
return requestSync(uri, options);
},
delSync: function(uri, options) {
options.method = "DELETE";
return requestSync(uri, options);
},
getSync: requestSync
}); | // Get our NPM stuff.
request = Npm.require("request");
// Wrap request with something that can be `Meteor.wrapAsync`ed.
var requestAsync = function(uri, options, callback) {
request(uri, options, function(error, response, body) {
if (error) {
console.log(error);
callback(error);
} else {
callback(null, {
response: response,
body: body
});
}
});
};
// Make a sync function out of it.
var requestSync;
if (typeof Meteor.wrapAsync === "function") {
requestSync = Meteor.wrapAsync(requestAsync);
} else {
requestSync = Meteor._wrapAsync(requestAsync);
}
// Use this to extend the prototype
_.extend(request, {
putSync: function(uri, options) {
options.method = "PUT";
return requestSync(uri, options);
},
patchSync: function(uri, options) {
options.method = "PATCH";
return requestSync(uri, options);
},
postSync: function(uri, options) {
options.method = "POST";
return requestSync(uri, options);
},
headSync: function(uri, options) {
options.method = "HEAD";
return requestSync(uri, options);
},
delSync: function(uri, options) {
options.method = "DELETE";
return requestSync(uri, options);
},
getSync: requestSync
}); |
Include the dyno identifier, if available, in the metric key | var Graphite = require('graphite');
var Measured = require('measured');
var reportInterval = 5000;
var graphiteHost = process.env.GRAPHITE_HOST || null;
var graphitePort = process.env.GRAPHITE_PORT || 2003;
var envName = process.env.NODE_ENV || "unknown";
var processIdentifier = process.env.DYNO || "unknown-process";
var timer = null;
var graphite = null;
var data = Measured.createCollection('origami.polyfill.' + envName + '.' + processIdentifier);
if (graphiteHost) {
graphite = Graphite.createClient('plaintext://'+graphiteHost+':'+graphitePort);
timer = setInterval(function() {
graphite.write(data.toJSON(), function(err) {
if (err) {
// Ignore timeouts
if (err.code === 'ETIMEDOUT') return;
console.error(err, err.stack);
console.warn('Disabling graphite reporting due to error');
clearTimeout(timer);
}
});
}, reportInterval);
timer.unref();
}
module.exports = data;
| var Graphite = require('graphite');
var Measured = require('measured');
var reportInterval = 5000;
var graphiteHost = process.env.GRAPHITE_HOST || null;
var graphitePort = process.env.GRAPHITE_PORT || 2003;
var envName = process.env.NODE_ENV || "unknown";
var timer = null;
var graphite = null;
var data = Measured.createCollection('origami.polyfill.' + envName);
if (graphiteHost) {
graphite = Graphite.createClient('plaintext://'+graphiteHost+':'+graphitePort);
timer = setInterval(function() {
graphite.write(data.toJSON(), function(err) {
if (err) {
// Ignore timeouts
if (err.code === 'ETIMEDOUT') return;
console.error(err, err.stack);
console.warn('Disabling graphite reporting due to error');
clearTimeout(timer);
}
});
}, reportInterval);
timer.unref();
}
module.exports = data;
|
Fix bug in read tracking system | def update_read_tracking(topic, user):
tracking = user.readtracking
#if last_read > last_read - don't check topics
if tracking.last_read and tracking.last_read > (topic.last_post.updated or
topic.last_post.created):
return
if isinstance(tracking.topics, dict):
#clear topics if len > 5Kb and set last_read to current time
if len(tracking.topics) > 5120:
tracking.topics = None
tracking.last_read = datetime.now()
tracking.save()
#update topics if new post exists or cache entry is empty
if topic.last_post.pk > tracking.topics.get(str(topic.pk), 0):
tracking.topics[str(topic.pk)] = topic.last_post.pk
tracking.save()
else:
#initialize topic tracking dict
tracking.topics = {topic.pk: topic.last_post.pk}
tracking.save()
| def update_read_tracking(topic, user):
tracking = user.readtracking
#if last_read > last_read - don't check topics
if tracking.last_read and tracking.last_read > (topic.last_post.updated or
topic.last_post.created):
return
if isinstance(tracking.topics, dict):
#clear topics if len > 5Kb and set last_read to current time
if len(tracking.topics) > 5120:
tracking.topics = None
tracking.last_read = datetime.now()
tracking.save()
#update topics if exist new post or does't exist in dict
if topic.last_post.pk > tracking.topics.get(str(topic.pk), 0):
tracking.topics.setdefault(str(topic.pk), topic.last_post.pk)
tracking.save()
else:
#initialize topic tracking dict
tracking.topics = {topic.pk: topic.last_post.pk}
tracking.save()
|
Use full URI for build failure reasons | from __future__ import absolute_import
from jinja2 import Markup
from changes.buildfailures.base import BuildFailure
from changes.utils.http import build_uri
class TestFailure(BuildFailure):
def get_html_label(self, build):
link = build_uri('/projects/{0}/builds/{1}/tests/?result=failed'.format(build.project.slug, build.id.hex))
try:
test_failures = (
s.value for s in build.stats if s.name == 'test_failures'
).next()
except StopIteration:
return Markup('There were an <a href="{link}">unknown number of test failures</a>.'.format(
link=link,
))
return Markup('There were <a href="{link}">{count} failing tests</a>.'.format(
link=link,
count=test_failures,
))
| from __future__ import absolute_import
from jinja2 import Markup
from changes.buildfailures.base import BuildFailure
class TestFailure(BuildFailure):
def get_html_label(self, build):
link = '/projects/{0}/builds/{1}/tests/?result=failed'.format(build.project.slug, build.id.hex)
try:
test_failures = (
s.value for s in build.stats if s.name == 'test_failures'
).next()
except StopIteration:
return Markup('There were an <a href="{link}">unknown number of test failures</a>.'.format(
link=link,
))
return Markup('There were <a href="{link}">{count} failing tests</a>.'.format(
link=link,
count=test_failures,
))
|
Use append mode in case other hooks want to write to build-extras.gradle | #!/usr/bin/env node
// add additional build-extras.gradle file to instruct android's lint to ignore translation errors
// v0.1.c
// causing error in the build --release
// Issue: https://github.com/phonegap/phonegap-plugin-barcodescanner/issues/80
//
// Warning: This solution does not solve the problem only makes it possible to build --release
var fs = require('fs');
var rootdir = process.argv[2];
if(rootdir){
var platforms = (process.env.CORDOVA_PLATFORMS ? process.env.CORDOVA_PLATFORMS.split(',') : []);
for(var x = 0; x < platforms.length; x++){
var platform = platforms[x].trim().toLowerCase();
try{
if(platform == 'android'){
var lintOptions = 'android { \nlintOptions {\ndisable \'MissingTranslation\' \ndisable \'ExtraTranslation\' \n} \n}';
fs.appendFileSync('platforms/android/build-extras.gradle', lintOptions, 'UTF-8');
process.stdout.write('Added build-extras.gradle ');
}
}catch(e){
process.stdout.write(e);
}
}
}
| #!/usr/bin/env node
// add additional build-extras.gradle file to instruct android's lint to ignore translation errors
// v0.1.c
// causing error in the build --release
// Issue: https://github.com/phonegap/phonegap-plugin-barcodescanner/issues/80
//
// Warning: This solution does not solve the problem only makes it possible to build --release
var fs = require('fs');
var rootdir = process.argv[2];
if(rootdir){
var platforms = (process.env.CORDOVA_PLATFORMS ? process.env.CORDOVA_PLATFORMS.split(',') : []);
for(var x = 0; x < platforms.length; x++){
var platform = platforms[x].trim().toLowerCase();
try{
if(platform == 'android'){
var lintOptions = 'android { \nlintOptions {\ndisable \'MissingTranslation\' \ndisable \'ExtraTranslation\' \n} \n}';
fs.writeFileSync('platforms/android/build-extras.gradle', lintOptions, 'UTF-8');
process.stdout.write('Added build-extras.gradle ');
}
}catch(e){
process.stdout.write(e);
}
}
} |
Fix link to the tagged release. | from setuptools import setup
setup(
name = 'PyFVCOM',
packages = ['PyFVCOM'],
version = '1.3.4',
description = ("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."),
author = 'Pierre Cazenave',
author_email = 'pica@pml.ac.uk',
url = 'https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM',
download_url = 'http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref=1.3.4',
keywords = ['fvcom', 'unstructured grid', 'mesh'],
license = 'MIT',
platforms = 'any',
install_requires = ['pyshp', 'jdcal', 'scipy', 'numpy', 'matplotlib', 'netCDF4', 'lxml', 'matplotlib'],
classifiers = []
)
| from setuptools import setup
setup(
name = 'PyFVCOM',
packages = ['PyFVCOM'],
version = '1.3.4',
description = ("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."),
author = 'Pierre Cazenave',
author_email = 'pica@pml.ac.uk',
url = 'https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM',
download_url = 'http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref=1.2.1',
keywords = ['fvcom', 'unstructured grid', 'mesh'],
license = 'MIT',
platforms = 'any',
install_requires = ['pyshp', 'jdcal', 'scipy', 'numpy', 'matplotlib', 'netCDF4', 'lxml', 'matplotlib'],
classifiers = []
)
|
Fix typo in Famo.us require in test | 'use strict';
window.Famous = require('famous');
var test = require('tape');
var BEST = require('../lib/index');
var DataStore = require('../lib/data-store/data-store');
test('---- BEST', function(t) {
t.plan(2);
t.test('exports', function(st) {
st.plan(4);
st.ok(BEST, 'BEST exports');
st.ok(DataStore, 'DataStore exports');
st.ok(BEST.register && BEST.execute && BEST.message && BEST.deploy, 'BEST exports register/execture/message/deploy');
st.ok(BEST.register === BEST.scene && BEST.register === BEST.module && BEST.register === BEST.component, 'BEST aliases `scene`/`module`/`component` to `register`.');
});
t.test('registers modules', function(st) {
st.plan(1);
var name = 'mock-name:mock-module';
var data = {value: 1};
BEST.register(name, data);
st.equal(DataStore.getModule(name).value, data.value, 'registers module with DataStore');
});
});
| 'use strict';
window.Famous = require('../node_modules/famous');
var test = require('tape');
var BEST = require('../lib/index');
var DataStore = require('../lib/data-store/data-store');
test('---- BEST', function(t) {
t.plan(2);
t.test('exports', function(st) {
st.plan(4);
st.ok(BEST, 'BEST exports');
st.ok(DataStore, 'DataStore exports');
st.ok(BEST.register && BEST.execute && BEST.message && BEST.deploy, 'BEST exports register/execture/message/deploy');
st.ok(BEST.register === BEST.scene && BEST.register === BEST.module && BEST.register === BEST.component, 'BEST aliases `scene`/`module`/`component` to `register`.');
});
t.test('registers modules', function(st) {
st.plan(1);
var name = 'mock-name:mock-module';
var data = {value: 1};
BEST.register(name, data);
st.equal(DataStore.getModule(name).value, data.value, 'registers module with DataStore');
});
});
|
Remove Extra EJS Routes Handler and Add Caching Process to AccessToken | 'use strict'
var loopback = require('loopback')
var boot = require('loopback-boot')
var path = require('path')
var bodyParser = require('body-parser')
var app = module.exports = loopback()
// configure body parser
app.use(bodyParser.urlencoded({extended: true}))
app.use(loopback.token({
model: app.models.accessToken,
currentUserLiteral: 'me'
}))
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started')
var baseUrl = app.get('url').replace(/\/$/, '')
console.log('Web server listening at: %s', baseUrl)
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath
console.log('Browse your REST API at %s%s', baseUrl, explorerPath)
}
})
}
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err
// start the server if `$ node server.js`
if (require.main === module)
app.start()
})
| 'use strict';
var loopback = require('loopback');
var boot = require('loopback-boot');
var path = require('path');
var bodyParser = require('body-parser');
var app = module.exports = loopback();
// configure view handler
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// configure body parser
app.use(bodyParser.urlencoded({extended: true}));
app.use(loopback.token());
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err;
// start the server if `$ node server.js`
if (require.main === module)
app.start();
});
|
Update test to use ?state | 'use strict';
require('should');
var request = require('supertest');
var app = require('../app.js');
var helpers = require('./helpers.js');
var config = require('../config/configuration.js');
describe('Auth handlers', function() {
describe('GET /init/connect', function() {
it("should redirect to the AnyFetch grant page", function(done) {
request(app)
.get('/init/connect?state=v2')
.expect(302)
.expect('Location', 'http://localhost:8001/oauth/authorize?client_id=test&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Finit%2Fcallback&state=v2')
.end(done);
});
});
describe('GET /init/callback', function() {
it("should redirect to the 'localhost/done' location with the token", function(done) {
request(app)
.get('/init/callback?code=test')
.expect(302)
.expect('Location', config.doneEndpoint + helpers.MOCK_SERVER_TOKEN)
.end(done);
});
});
});
| 'use strict';
require('should');
var request = require('supertest');
var app = require('../app.js');
var helpers = require('./helpers.js');
var config = require('../config/configuration.js');
describe('Auth handlers', function() {
describe('GET /init/connect', function() {
it("should redirect to the AnyFetch grant page", function(done) {
request(app)
.get('/init/connect')
.expect(302)
.expect('Location', 'http://localhost:8001/oauth/authorize?client_id=test&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Finit%2Fcallback')
.end(done);
});
});
describe('GET /init/callback', function() {
it("should redirect to the 'localhost/done' location with the token", function(done) {
request(app)
.get('/init/callback?code=test')
.expect(302)
.expect('Location', config.doneEndpoint + helpers.MOCK_SERVER_TOKEN)
.end(done);
});
});
});
|
Allow extensions to be sent as well - maybe we should consider just allowing opts.browserifyOpts | var browserify = require('browserify'),
path = require('path');
module.exports = function(opts){
var routerPath;
if (typeof opts.getLocation === 'function') {
var router = opts;
routerPath = router.getLocation();
}else if(opts.router && typeof opts.router.getLocation === 'function'){
var router = opts.router;
routerPath = router.getLocation();
}else if(opts.routerPath){
routerPath = path.resolve(opts.routerPath);
}else{
throw new Error('You did not supply a router '
+'instance or routerPath:[path] option');
}
libRoot = path.resolve(__dirname+'/..');
return browserify(libRoot+'/lib/initClient.js', {
extensions: opts.extensions,
paths: [libRoot+'/node_modules'],
transform: opts.transform,
}).ignore(libRoot+'/classes/Router/serverRouter.js')
.ignore(libRoot+'/classes/Page/serverPage.js')
.ignore(libRoot+'/lib/build.js')
.require(libRoot+'/ice.js', {expose: 'ice-js'})
.require(routerPath, {expose: 'user-router-instance'})
.bundle();
};
| var browserify = require('browserify'),
path = require('path');
module.exports = function(opts){
var routerPath;
if (typeof opts.getLocation === 'function') {
var router = opts;
routerPath = router.getLocation();
}else if(opts.router && typeof opts.router.getLocation === 'function'){
var router = opts.router;
routerPath = router.getLocation();
}else if(opts.routerPath){
routerPath = path.resolve(opts.routerPath);
}else{
throw new Error('You did not supply a router '
+'instance or routerPath:[path] option');
}
libRoot = path.resolve(__dirname+'/..');
return browserify(libRoot+'/lib/initClient.js', {
paths: [libRoot+'/node_modules'],
transform: opts.transform,
}).ignore(libRoot+'/classes/Router/serverRouter.js')
.ignore(libRoot+'/classes/Page/serverPage.js')
.ignore(libRoot+'/lib/build.js')
.require(libRoot+'/ice.js', {expose: 'ice-js'})
.require(routerPath, {expose: 'user-router-instance'})
.bundle();
};
|
Add onConnect and onDisconnect callbacks and return 'connection' object with disconnect option | var WebSocket = require('ws');
var debug = require('debug')('signalk:ws');
function connectDelta(hostname, callback, onConnect, onDisconnect) {
debug("Connecting to " + hostname);
var url = "ws://" + hostname + "/signalk/stream?stream=delta&context=self";
if (typeof Primus != 'undefined') {
debug("Using Primus");
var signalKStream = Primus.connect(url, {
reconnect: {
maxDelay: 15000,
minDelay: 500,
retries: Infinity
}
});
signalKStream.on('data', callback);
return {
disconnect: function() {
signalKStream.destroy();
debug('Disconnected');
}
}
} else {
debug("Using ws");
var connection = new WebSocket(url);
connection.onopen = function(msg) {
debug("open");
onConnect();
};
connection.onerror = function(error) {
debug("error:" + error);
};
connection.onmessage = function(msg) {
callback(JSON.parse(msg.data));
};
return {
disconnect: function() {
connection.close();
debug('Disconnected');
}
}
}
}
module.exports = {
connectDelta: connectDelta
} | var WebSocket = require('ws');
var debug = require('debug')('signalk:ws');
function connectDelta(hostname, callback) {
var url = "ws://" + hostname + "/signalk/stream?stream=delta&context=self";
if (typeof Primus != 'undefined') {
var signalKStream = Primus.connect(url, {
reconnect: {
maxDelay: 15000,
minDelay: 500,
retries: Infinity
}
});
signalKStream.on('data', callback);
} else {
connection = new WebSocket(url);
connection.onopen = function(msg) {
debug("open");
};
connection.onerror = function(error) {
debug("error:" + error);
};
connection.onmessage = function(msg) {
callback(JSON.parse(msg.data));
};
}
}
module.exports = {
connectDelta: connectDelta
} |
Use relative paths for includes. | <?php if ( ! defined('BASEPATH')) exit('Invalid file request.');
/**
* OmniLog module tests.
*
* @author Stephen Lewis <stephen@experienceinternet.co.uk>
* @copyright Experience Internet
* @package Omnilog
*/
require_once dirname(__FILE__) .'/../mcp.omnilog.php';
require_once dirname(__FILE__) .'/../models/omnilog_model.php';
class Test_omnilog extends Testee_unit_test_case {
private $_model;
private $_subject;
/* --------------------------------------------------------------
* PUBLIC METHODS
* ------------------------------------------------------------ */
/**
* Constructor.
*
* @access public
* @return void
*/
public function setUp()
{
parent::setUp();
Mock::generate('Mock_omnilog_model', get_class($this) .'_mock_model');
$this->_ee->omnilog_model = $this->_get_mock('model');
$this->_model = $this->_ee->omnilog_model;
$this->_subject = new Omnilog();
}
}
/* End of file : test.mod_omnilog.php */
/* File location : third_party/omnilog/tests/test.mod_omnilog.php */
| <?php if ( ! defined('BASEPATH')) exit('Invalid file request.');
/**
* OmniLog module tests.
*
* @author Stephen Lewis <stephen@experienceinternet.co.uk>
* @copyright Experience Internet
* @package Omnilog
*/
require_once PATH_THIRD .'omnilog/mcp.omnilog.php';
require_once PATH_THIRD .'omnilog/tests/mocks/mock.omnilog_model.php';
class Test_omnilog extends Testee_unit_test_case {
private $_model;
private $_subject;
/* --------------------------------------------------------------
* PUBLIC METHODS
* ------------------------------------------------------------ */
/**
* Constructor.
*
* @access public
* @return void
*/
public function setUp()
{
parent::setUp();
Mock::generate('Mock_omnilog_model', get_class($this) .'_mock_model');
$this->_ee->omnilog_model = $this->_get_mock('model');
$this->_model = $this->_ee->omnilog_model;
$this->_subject = new Omnilog();
}
}
/* End of file : test.mod_omnilog.php */
/* File location : third_party/omnilog/tests/test.mod_omnilog.php */
|
Fix the trailing slash bug. | from django.conf.urls import include, url
from django.contrib import admin
from visualize import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'state', views.StateViewSet)
urlpatterns = [
url(r'^$', views.index, name='homepage'),
url(r'^state/(?P<state>\D+)/$', views.state, name='state'),
url(r'^json/(?P<state>\D+)/$', views.state_json, name='state_json'),
url(r'^admin/', include(admin.site.urls)),
url(r'^county/(?P<county>\d+)$', views.county, name='county'),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api/', include(router.urls))]
urlpatterns += staticfiles_urlpatterns()
| from django.conf.urls import include, url
from django.contrib import admin
from visualize import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'state', views.StateViewSet)
urlpatterns = [
url(r'^$', views.index, name='homepage'),
url(r'^state/(?P<state>\D+)$', views.state, name='state'),
url(r'^json/(?P<state>\D+)$', views.state_json, name='state_json'),
url(r'^admin/', include(admin.site.urls)),
url(r'^county/(?P<county>\d+)$', views.county, name='county'),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api/', include(router.urls))]
urlpatterns += staticfiles_urlpatterns()
|
Handle response with 0 results | var apiKey = "AIzaSyAj9GGrBLnNPImKnl7MKAuD737t1MHnMT8";
var geocoder = require('node-geocoder') ("google", "https", { apiKey: apiKey });
var csv = require('csv');
process.stdin
.pipe(csv.parse())
.pipe(csv.transform(function(data, callback){
setImmediate(function(){
geocoder.geocode(data[1])
.then(function(res) {
if (res.length === 0) {
data.push(0);
data.push(0);
} else {
data.push(res[0].latitude);
data.push(res[0].longitude);
}
callback(null, data);
})
.catch(function(err) {
console.log(data[0] + " " + err);
});
});}, {parallel: 1}))
.pipe(csv.stringify({quotedString: true}))
.pipe(process.stdout);
| var apiKey = "AIzaSyAj9GGrBLnNPImKnl7MKAuD737t1MHnMT8";
var geocoder = require('node-geocoder') ("google", "https", { apiKey: apiKey });
var csv = require('csv');
process.stdin
.pipe(csv.parse())
.pipe(csv.transform(function(data, callback){
setImmediate(function(){
geocoder.geocode(data[1])
.then(function(res) {
if (res.length === 0) {
data.push(res[0].latitude);
data.push(res[0].longitude);
} else {
data.push(0);
data.push(0);
}
callback(null, data);
})
.catch(function(err) {
console.log(data[0] + " " + err);
});
});}, {parallel: 1}))
.pipe(csv.stringify({quotedString: true}))
.pipe(process.stdout);
|
Use -1 for hashCode, since 0 has the same effect as "no object" in typical cases (e.g. sequences/sets) | package org.bouncycastle.asn1;
import java.io.IOException;
/**
* A NULL object.
*/
public abstract class ASN1Null
extends ASN1Object
{
public ASN1Null()
{
}
public int hashCode()
{
return -1;
}
boolean asn1Equals(
DERObject o)
{
if (!(o instanceof ASN1Null))
{
return false;
}
return true;
}
abstract void encode(DEROutputStream out)
throws IOException;
public String toString()
{
return "NULL";
}
}
| package org.bouncycastle.asn1;
import java.io.IOException;
/**
* A NULL object.
*/
public abstract class ASN1Null
extends ASN1Object
{
public ASN1Null()
{
}
public int hashCode()
{
return 0;
}
boolean asn1Equals(
DERObject o)
{
if (!(o instanceof ASN1Null))
{
return false;
}
return true;
}
abstract void encode(DEROutputStream out)
throws IOException;
public String toString()
{
return "NULL";
}
}
|
Allow unpacking selected fields in specific order | <?php
class SodaTuple {
public function __construct($fields = array()) {
foreach($fields as $field => $value) {
$this->{$field} = $value;
}
}
public function __call($name, $args) {
if(count($args)) return $this->{$name} = $args[0]; // set method
return $this->{$name}; // get method
}
public function unpack($fields = array()) {
$unpacked = array();
$self = (array)$this;
// unpack in the order of fields given
foreach((is_array($fields) ? $fields : func_get_args()) as $field) {
if(isset($self[$field])) $unpacked[] = $self[$field];
}
return count($unpacked) ? $unpacked : $self; // returns all fields if none was specified
}
public function fields() {
return array_keys((array)$this);
}
public function __toString() {
return '[' . join(', ', $this->unpack()) . ']';
}
}
// factory function for creating named tuples
function soda($fields = array()) {
return new SodaTuple($fields);
} | <?php
class SodaTuple {
public function __construct($fields = array()) {
foreach($fields as $field => $value) {
$this->{$field} = $value;
}
}
public function __call($name, $args) {
if(count($args)) return $this->{$name} = $args[0]; /* set method */
return $this->{$name}; /* get method */
}
public function unpack() {
return array_values((array)$this);
}
public function fields() {
return array_keys((array)$this);
}
public function __toString() {
return '[' . join(', ', $this->unpack()) . ']';
}
}
/* Factory function for creating named tuples */
function soda($fields = array()) {
return new SodaTuple($fields);
} |
chromium: Make login name detection more strict
Check that the login name is inside a link pointing to something under
https://profiles.google.com/ | console.log("goa: GOA content script for GMail loading");
function detectLoginInfo() {
console.log("goa: Scraping for login info");
var selector = '//*[@role="navigation"]//*[starts-with(@href, "https://profiles.google.com/")]//text()[contains(.,"@")]';
var r = document.evaluate(selector, document.body, null, XPathResult.STRING_TYPE, null);
var loginName = r.stringValue;
if (!loginName)
return false;
var msg = {
type: 'login-detected',
data: {
identity: loginName,
provider: 'google',
services: ['mail'],
authenticationDomain: 'google.com'
}
};
console.log("goa: Detected login info:", msg);
chrome.extension.sendMessage(msg);
return true;
}
// Run detectLoginInfo() on any DOM change if not ready yet
if (!detectLoginInfo()) {
var t = {};
t.observer = new WebKitMutationObserver(function(mutations, observer) {
if (detectLoginInfo()) {
observer.disconnect();
clearTimeout(t.timeout);
}
});
t.observer.observe(document.body, { childList: true, subtree: true, characterData: true });
t.timeout = setTimeout(function() {
console.log("goa: Give up, unable to find any login info");
t.observer.disconnect();
}, 10000);
};
| console.log("goa: GOA content script for GMail loading");
function detectLoginInfo() {
console.log("goa: Scraping for login info");
var r = document.evaluate('//*[@role="navigation"]//text()[contains(.,"@")]', document.body, null, XPathResult.STRING_TYPE, null);
var loginName = r.stringValue;
if (!loginName)
return false;
var msg = {
type: 'login-detected',
data: {
identity: loginName,
provider: 'google',
services: ['mail'],
authenticationDomain: 'google.com'
}
};
console.log("goa: Detected login info:", msg);
chrome.extension.sendMessage(msg);
return true;
}
// Run detectLoginInfo() on any DOM change if not ready yet
if (!detectLoginInfo()) {
var t = {};
t.observer = new WebKitMutationObserver(function(mutations, observer) {
if (detectLoginInfo()) {
observer.disconnect();
clearTimeout(t.timeout);
}
});
t.observer.observe(document.body, { childList: true, subtree: true, characterData: true });
t.timeout = setTimeout(function() {
console.log("goa: Give up, unable to find any login info");
t.observer.disconnect();
}, 10000);
};
|
Add initializaton of Cloud Firestore instance for use accross all scripts. | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Initialize Firebase and its related product we use using the provided
// Firebase project configuation.
var firebaseConfig = {
apiKey: "AIzaSyAAJgRhJY_rRn_q_On1HdA3hx15YHSkEJg",
authDomain: "step53-2020.firebaseapp.com",
databaseURL: "https://step53-2020.firebaseio.com",
projectId: "step53-2020",
storageBucket: "step53-2020.appspot.com",
messagingSenderId: "905834221913",
appId: "1:905834221913:web:25e711f1132b2c0537fc48",
measurementId: "G-PLVY991DHW"
};
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
| // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Initialize Firebase and its related product we use using the provided
// Firebase project configuation.
var firebaseConfig = {
apiKey: "AIzaSyAAJgRhJY_rRn_q_On1HdA3hx15YHSkEJg",
authDomain: "step53-2020.firebaseapp.com",
databaseURL: "https://step53-2020.firebaseio.com",
projectId: "step53-2020",
storageBucket: "step53-2020.appspot.com",
messagingSenderId: "905834221913",
appId: "1:905834221913:web:25e711f1132b2c0537fc48",
measurementId: "G-PLVY991DHW"
};
firebase.initializeApp(firebaseConfig);
|
Copy the main paragraph 3x | <!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>teodizzo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="frameworks/bootstrap_dist/css/bootstrap.css" rel="stylesheet" type="text/css"/>
<script src="frameworks/bootstrap_dist/js/bootstrap.min.js" type="text/javascript"></script>
</head>
<body>
<div class="container text-center">
<h3>Welcome to Teodizzo</h3>
<p class="text-muted">We hope that you enjoy your stay.</p>
<p class="text-muted">We hope that you enjoy your stay.</p>
<p class="text-muted">We hope that you enjoy your stay.</p>
</div>
</body>
</html>
| <!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>teodizzo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="frameworks/bootstrap_dist/css/bootstrap.css" rel="stylesheet" type="text/css"/>
<script src="frameworks/bootstrap_dist/js/bootstrap.min.js" type="text/javascript"></script>
</head>
<body>
<div class="container text-center">
<h3>Welcome to Teodizzo</h3>
<p class="text-muted">We hope that you enjoy your stay.</p>
</div>
</body>
</html>
|
Subsets and Splits