text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
FIX BUILD compiler error in 509selector unit test
git-svn-id: f26ccc5efe72c2bd8e1c40f599fe313f2692e4de@6293 a612230a-c5fa-0310-af8b-88eea846685b
|
/*
*
*
* Copyright (C) 2006 SIPfoundry Inc.
* Licensed by SIPfoundry under the LGPL license.
*
* Copyright (C) 2006 Pingtel Corp.
* Licensed to SIPfoundry under a Contributor Agreement.
*
* $
*/
package org.sipfoundry.sipxconfig.common;
import org.sipfoundry.sipxconfig.common.X509Selector;
import junit.framework.TestCase;
public class X509SelectorTest extends TestCase {
public void testAvailableAlgorithm() {
String alg = new X509Selector().getAvailableAlgorithm();
// only works w/2 VM vendors. If others are known to work, add here
assertTrue(alg.equals("SunX509") || alg.equals("IbmX509"));
}
public void testUnavailableAlgorithm() {
assertNull(new X509Selector().getAvailableAlgorithm(new String[] { "bogus" }));
}
}
|
/*
*
*
* Copyright (C) 2006 SIPfoundry Inc.
* Licensed by SIPfoundry under the LGPL license.
*
* Copyright (C) 2006 Pingtel Corp.
* Licensed to SIPfoundry under a Contributor Agreement.
*
* $
*/
package org.sipfoundry.sipxconfig.common;
import org.sipfoundry.sipxconfig.common.X509Selector;
import junit.framework.TestCase;
public class X509SelectorTest extends TestCase {
public void testAvailableAlgorithm() {
String alg = new X509Selector.getAvailableAlgorithm();
// only works w/2 VM vendors. If others are known to work, add here
assertTrue(alg.equals("SunX509") || alg.equals("IbmX509"));
}
public void testUnavailableAlgorithm() {
assertNull(new X509Selector().getAvailableAlgorithm(new String[] { "bogus" }));
}
}
|
Make Fields type more concrete.
|
/* @flow */
import type { Decoder, Decode } from "./Decoder"
import { Error, TypeError, ThrownError } from "./Error"
import { FieldError } from "./Field"
import * as Variant from "./Decoder"
export type Record<a> = Decoder<$ObjMap<a, <b>(Decoder<b>) => b>>
export type Fields<a> = $ObjMap<a, <b>(b) => Decoder<b>> & {
[string]: Decoder<*>
}
export interface RecordDecoder<a> {
type: "Record";
fields: Fields<a>;
}
export default class RecordReader<a> implements RecordDecoder<a> {
type: "Record" = "Record"
fields: Fields<a>
constructor(fields: Fields<a>) {
this.fields = fields
}
static decode<a: {}>(fields: Fields<a>, input: mixed): Decode<a> {
if (typeof input === "object" && input !== null) {
const result: Object = {}
for (let key of Object.keys(fields)) {
try {
const value = Variant.decode(fields[key], input[key])
if (value instanceof Error) {
return new FieldError(key, value)
} else {
result[key] = value
}
} catch (error) {
return new FieldError(key, new ThrownError(error))
}
}
return result
} else {
return new TypeError("object", input)
}
}
}
|
/* @flow */
import type { Decoder, Decode } from "./Decoder"
import { Error, TypeError, ThrownError } from "./Error"
import { FieldError } from "./Field"
import * as Variant from "./Decoder"
export type Record<a> = Decoder<$ObjMap<a, <b>(Decoder<b>) => b>>
export type Fields<a> = $ObjMap<a, <b>(b) => Decoder<b>>
export interface RecordDecoder<a> {
type: "Record";
fields: Fields<a>;
}
export default class RecordReader<a> implements RecordDecoder<a> {
type: "Record" = "Record"
fields: Fields<a>
constructor(fields: Fields<a>) {
this.fields = fields
}
static decode<a: {}>(fields: Fields<a>, input: mixed): Decode<a> {
if (typeof input === "object" && input !== null) {
const result: Object = {}
for (let key of Object.keys(fields)) {
try {
const value = Variant.decode(fields[key], input[key])
if (value instanceof Error) {
return new FieldError(key, value)
} else {
result[key] = value
}
} catch (error) {
return new FieldError(key, new ThrownError(error))
}
}
return result
} else {
return new TypeError("object", input)
}
}
}
|
Throw error if an EtchComponent subclass doesn't implement render()
|
/** @babel */
/** @jsx etch.dom */
import {Emitter} from 'atom'
import etch from 'etch'
export default class EtchComponent {
constructor (props) {
this.props = props
etch.initialize(this)
this.setScheduler(atom.views)
this.emitter = new Emitter()
this.emitter.emit('component-did-mount')
}
componentDidMount (callback) {
this.emitter.on('component-did-mount', callback)
}
setScheduler (scheduler) {
etch.setScheduler(scheduler)
}
getScheduler () {
return etch.getScheduler()
}
update (props) {
let oldProps = this.props
this.props = {
...oldProps,
...props
}
return etch.update(this)
}
destroy () {
etch.destroy(this)
}
render () {
throw new Error('Etch components must implement a `render` method')
}
}
|
/** @babel */
/** @jsx etch.dom */
import {Emitter} from 'atom'
import etch from 'etch'
export default class EtchComponent {
constructor (props) {
this.props = props
etch.initialize(this)
this.setScheduler(atom.views)
this.emitter = new Emitter()
this.emitter.emit('component-did-mount')
}
componentDidMount (callback) {
this.emitter.on('component-did-mount', callback)
}
setScheduler (scheduler) {
etch.setScheduler(scheduler)
}
getScheduler () {
return etch.getScheduler()
}
update (props) {
let oldProps = this.props
this.props = {
...oldProps,
...props
}
return etch.update(this)
}
destroy () {
etch.destroy(this)
}
// Must be implemented by subclass
render () {
return
}
}
|
Return a freshly defined error class.
|
(function(root) {
if (typeof exports !== 'undefined') {
var _ = require('underscore');
var util = require('./util')
} else {
var util = Substance.util;
}
var errors = {};
SubstanceError = function(name, code, message) {
this.message = message;
this.name = name;
this.code = code;
this.stack = util.callstack(1);
};
SubstanceError.prototype = {
toString: function() {
return this.name+":"+this.message;
},
toJSON: function() {
return {
name: this.name,
message: this.message,
code: this.code,
stack: this.stack
};
},
printStackTrace: function() {
for (var idx = 0; idx < this.stack.length; idx++) {
var s = this.stack[idx];
console.log(s.file+":"+s.line+":"+s.col, "("+s.func+")");
}
}
}
errors.define = function(className, code) {
errors[className] = SubstanceError.bind(null, className, code);
errors[className].prototype = SubstanceError.prototype;
return errors[className];
}
if (typeof exports === 'undefined') {
if (!root.Substance) root.Substance = {};
root.Substance.errors = errors;
} else {
module.exports = errors;
}
})(this);
|
(function(root) {
if (typeof exports !== 'undefined') {
var _ = require('underscore');
var util = require('./util')
} else {
var util = Substance.util;
}
var errors = {};
SubstanceError = function(name, code, message) {
this.message = message;
this.name = name;
this.code = code;
this.stack = util.callstack(1);
};
SubstanceError.prototype = {
toString: function() {
return this.name+":"+this.message;
},
toJSON: function() {
return {
name: this.name,
message: this.message,
code: this.code,
stack: this.stack
};
},
printStackTrace: function() {
for (var idx = 0; idx < this.stack.length; idx++) {
var s = this.stack[idx];
console.log(s.file+":"+s.line+":"+s.col, "("+s.func+")");
}
}
}
errors.define = function(className, code) {
errors[className] = SubstanceError.bind(null, className, code);
errors[className].prototype = SubstanceError.prototype;
}
if (typeof exports === 'undefined') {
if (!root.Substance) root.Substance = {};
root.Substance.errors = errors;
} else {
module.exports = errors;
}
})(this);
|
Allow control char as rule "variable"
|
// L-System Rule Parser
function RuleParser(str) {
this.str = str;
this.rules = {};
this.parse = function() {
var c, d;
var env = 0;
var rule_str;
var variable;
for (var i = 0; i < this.str.length; i++) {
c = this.str[i];
if (i > 0) {
d = this.str[i-1];
} else {
d = null;
}
if (c == '(') {
env = 1;
rule_str = "";
} else if ((c.search(/[A-Z]/) == 0 || c.search(/[\+\-\[\]]/) == 0)
&& env == 1) {
variable = c;
} else if (c == '>' && d == '-') {
env = 2;
} else if ((c.search(/[A-Z]/) == 0 || c.search(/[\+-\[\]]/) == 0)
&& env == 2) {
rule_str += c;
} else if (c == ')') {
this.rules[variable] = rule_str;
env = 0;
}
}
return this.rules;
}
}
module.exports = RuleParser;
|
// L-System Rule Parser
function RuleParser(str) {
this.str = str;
this.rules = {};
this.parse = function() {
var c, d;
var env = 0;
var rule_str;
var variable;
for (var i = 0; i < this.str.length; i++) {
c = this.str[i];
if (i > 0) {
d = this.str[i-1];
} else {
d = null;
}
if (c == '(') {
env = 1;
rule_str = "";
} else if (c.search(/[A-Z]/) == 0 && env == 1) {
variable = c;
} else if (c == '>' && d == '-') {
env = 2;
} else if ((c.search(/[A-Z]/) == 0 || c.search(/[\+-\[\]]/) == 0)
&& env == 2) {
rule_str += c;
} else if (c == ')') {
this.rules[variable] = rule_str;
env = 0;
}
}
return this.rules;
}
}
module.exports = RuleParser;
|
Fix case, it's not ARGV it's argv for php
|
#!/usr/local/bin/php -f
<?php
/* upgrade embedded users serial console */
require_once("globals.inc");
require_once("config.inc");
require_once("functions.inc");
if(file_exists("/usr/local/bin/git") && isset($config['system']['gitsync']['synconupgrade'])) {
if(!empty($config['system']['gitsync']['repositoryurl']))
exec("cd /root/pfsense/pfSenseGITREPO/pfSenseGITREPO && git config remote.origin.url " . escapeshellarg($config['system']['gitsync']['repositoryurl']));
if(!empty($config['system']['gitsync']['branch']))
system("pfSsh.php playback gitsync " . escapeshellarg($config['system']['gitsync']['branch']) . " --upgrading");
}
if($g['platform'] == "embedded") {
$config['system']['enableserial'] = true;
write_config();
}
$newslicedir = "";
if ($argv[1] != "")
$newslicedir = '/tmp/' . $argv[1];
system("echo \"Adding serial port settings ({$newslicedir})...\" >> /conf/upgrade_log.txt");
setup_serial_port("upgrade", $newslicedir);
$files_to_process = file("/etc/pfSense.obsoletedfiles");
foreach($files_to_process as $filename)
if(file_exists($filename))
exec("/bin/rm -f $filename");
?>
|
#!/usr/local/bin/php -f
<?php
/* upgrade embedded users serial console */
require_once("globals.inc");
require_once("config.inc");
require_once("functions.inc");
if(file_exists("/usr/local/bin/git") && isset($config['system']['gitsync']['synconupgrade'])) {
if(!empty($config['system']['gitsync']['repositoryurl']))
exec("cd /root/pfsense/pfSenseGITREPO/pfSenseGITREPO && git config remote.origin.url " . escapeshellarg($config['system']['gitsync']['repositoryurl']));
if(!empty($config['system']['gitsync']['branch']))
system("pfSsh.php playback gitsync " . escapeshellarg($config['system']['gitsync']['branch']) . " --upgrading");
}
if($g['platform'] == "embedded") {
$config['system']['enableserial'] = true;
write_config();
}
$newslicedir = "";
if ($ARGV[1] != "")
$newslicedir = '/tmp/' . $ARGV[1];
system("echo \"Adding serial port settings ({$newslicedir})...\" >> /conf/upgrade_log.txt");
setup_serial_port("upgrade", $newslicedir);
$files_to_process = file("/etc/pfSense.obsoletedfiles");
foreach($files_to_process as $filename)
if(file_exists($filename))
exec("/bin/rm -f $filename");
?>
|
Rename the 'contain' TestCase to TestContain
|
import unittest
from robber import expect
from robber.matchers.contain import Contain
class TestContain(unittest.TestCase):
def test_matches(self):
expect(Contain({'key': 'value'}, 'key').matches()) == True
expect(Contain([1, 2, 3], 2).matches()) == True
expect(Contain((1, 2, 3), 3).matches()) == True
expect(Contain({'key': 'value'}, 'other').matches()) == False
expect(Contain([1, 2, 3], 4).matches()) == False
expect(Contain((1, 2, 3), 4).matches()) == False
def test_failure_message(self):
contain = Contain([1, 2, 3], 4)
expect(contain.failure_message()) == 'Expected {0} to contain 4'.format([1, 2, 3])
def test_register(self):
expect(expect.matcher('contain')) == Contain
|
import unittest
from robber import expect
from robber.matchers.contain import Contain
class TestAbove(unittest.TestCase):
def test_matches(self):
expect(Contain({'key': 'value'}, 'key').matches()) == True
expect(Contain([1, 2, 3], 2).matches()) == True
expect(Contain((1, 2, 3), 3).matches()) == True
expect(Contain({'key': 'value'}, 'other').matches()) == False
expect(Contain([1, 2, 3], 4).matches()) == False
expect(Contain((1, 2, 3), 4).matches()) == False
def test_failure_message(self):
contain = Contain([1, 2, 3], 4)
expect(contain.failure_message()) == 'Expected {0} to contain 4'.format([1, 2, 3])
def test_register(self):
expect(expect.matcher('contain')) == Contain
|
Adjust check for sites running under a subdir
|
<?php
namespace Croogo\Core\Routing\Filter;
use Cake\Core\Configure;
use Cake\Event\Event;
use Cake\Routing\DispatcherFilter;
use Croogo\Core\Utility\StringConverter;
/**
* Class HomePageFilter
*/
class HomePageFilter extends DispatcherFilter
{
/**
* Priority setting.
*
* This filter should be run just after the routing filter
*
* @var int
*/
protected $_priority = 15;
/**
* Applies Routing and additionalParameters to the request to be dispatched.
* If Routes have not been loaded they will be loaded, and config/routes.php will be run.
*
* @param \Cake\Event\Event $event containing the request, response and additional params
* @return \Cake\Network\Response|null A response will be returned when a redirect route is encountered.
*/
public function beforeDispatch(Event $event)
{
$request = $event->data['request'];
if ($request->here !== $request->webroot || $request->param('prefix') === 'admin') {
return;
}
$homeUrl = Configure::read('Site.home_url');
if ($homeUrl && strpos($homeUrl, ':') !== false) {
$converter = new StringConverter();
$url = $converter->linkStringToArray($homeUrl);
$request->addParams($url);
}
}
}
|
<?php
namespace Croogo\Core\Routing\Filter;
use Cake\Core\Configure;
use Cake\Event\Event;
use Cake\Routing\DispatcherFilter;
use Croogo\Core\Utility\StringConverter;
/**
* Class HomePageFilter
*/
class HomePageFilter extends DispatcherFilter
{
/**
* Priority setting.
*
* This filter should be run just after the routing filter
*
* @var int
*/
protected $_priority = 15;
/**
* Applies Routing and additionalParameters to the request to be dispatched.
* If Routes have not been loaded they will be loaded, and config/routes.php will be run.
*
* @param \Cake\Event\Event $event containing the request, response and additional params
* @return \Cake\Network\Response|null A response will be returned when a redirect route is encountered.
*/
public function beforeDispatch(Event $event)
{
$request = $event->data['request'];
if ($request->here !== '/' || $request->param('prefix') === 'admin') {
return;
}
$homeUrl = Configure::read('Site.home_url');
if ($homeUrl && strpos($homeUrl, ':') !== false) {
$converter = new StringConverter();
$url = $converter->linkStringToArray($homeUrl);
$request->addParams($url);
}
}
}
|
Use ol.has.TOUCH to check if the device support touch events
|
import $ from 'jquery';
import angular from 'angular';
import {TOUCH} from 'ol/has.js';
function bootstrap(module) {
const interface_ = $('meta[name=interface]')[0].getAttribute('content');
const dynamicUrl_ = $('meta[name=dynamicUrl]')[0].getAttribute('content');
const dynamicUrl = `${dynamicUrl_}?interface=${interface_}&query=${encodeURIComponent(document.location.search)}`;
const request = $.ajax(dynamicUrl, {
'dataType': 'json',
'xhrFields': {
withCredentials: false
}
});
request.fail((jqXHR, textStatus) => {
window.alert(`Failed to get the dynamic: ${textStatus}`);
});
request.done((dynamic) => {
if (dynamic['doRedirect']) {
const small_screen = window.matchMedia ? window.matchMedia('(max-width: 1024px)') : false;
if (small_screen && TOUCH) {
window.location = dynamic['redirectUrl'];
}
}
for (const name in dynamic['constants']) {
module.constant(name, dynamic['constants'][name]);
}
angular.bootstrap(document, [`App${interface_}`]);
});
}
export default bootstrap;
|
// FIXME DocumentTouch is deprecated, see:
// https://developer.mozilla.org/en-US/docs/Web/API/DocumentTouch
/* global DocumentTouch */
import $ from 'jquery';
import angular from 'angular';
function bootstrap(module) {
const interface_ = $('meta[name=interface]')[0].getAttribute('content');
const dynamicUrl_ = $('meta[name=dynamicUrl]')[0].getAttribute('content');
const dynamicUrl = `${dynamicUrl_}?interface=${interface_}&query=${encodeURIComponent(document.location.search)}`;
const request = $.ajax(dynamicUrl, {
'dataType': 'json',
'xhrFields': {
withCredentials: false
}
});
request.fail((jqXHR, textStatus) => {
window.alert(`Failed to get the dynamic: ${textStatus}`);
});
request.done((dynamic) => {
if (dynamic['doRedirect']) {
const small_screen = window.matchMedia ? window.matchMedia('(max-width: 1024px)') : false;
if (small_screen && (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch)) {
window.location = dynamic['redirectUrl'];
}
}
for (const name in dynamic['constants']) {
module.constant(name, dynamic['constants'][name]);
}
angular.bootstrap(document, [`App${interface_}`]);
});
}
export default bootstrap;
|
Fix : replace deprecated request.param() api by request.params
|
const express = require('express');
const router = express.Router();
const puppeteer = require('puppeteer');
router.get('/', function (req, res, next) {
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
page.setViewport({
width: req.params.width ? parseInt(req.params.width, 10) : 1024,
height: req.params.heigh ? parseInt(req.params.height, 10) : 768
});
await page.goto(req.query.url, {timeout: 60000});
const shot = await page.screenshot({});
await browser.close();
res.setHeader('Content-Type', 'image/png');
res.status(200).send(shot);
}).catch(e => {
console.error(e);
res.status(500).send({error: 'Could not take screenshot'});
});
});
module.exports = router;
|
const express = require('express');
const router = express.Router();
const puppeteer = require('puppeteer');
router.get('/', function (req, res, next) {
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
page.setViewport({
width: req.param('width') ? parseInt(req.param('width'), 10) : 1024,
height: req.param('height') ? parseInt(req.param('height'), 10) : 768
});
await page.goto(req.query.url, {timeout: 60000});
const shot = await page.screenshot({});
await browser.close();
res.setHeader('Content-Type', 'image/png');
res.status(200).send(shot);
}).catch(e => {
console.error(e);
res.status(500).send({error: 'Could not take screenshot'});
});
});
module.exports = router;
|
Update manifest paths to use variables
|
<?php
namespace CFPropertyList;
require_once( 'cfpropertylist-2.0.1/CFPropertyList.php' );
// Get the munki repo directory
$plist = new CFPropertyList( '/Library/Preferences/com.github.munki.plist' );
$arrPref = $plist->toArray();
$munki_repo = $arrPref['MUNKI_REPO'];
// Get the varibles passed by the enroll script
$identifier = $_GET["identifier"];
$hostname = $_GET["hostname"];
// Set the path to the manifests
$parent_manifest = $munki_repo . '/manifests/' . $identifier
$machine_manifest = $munki_repo . '/manifests/' . $hostname
// Check if manifest already exists for this machine
if ( file_exists( $machine_manifest ) )
{
echo "Computer manifest already exists.";
}
else
{
echo "Computer manifest does not exist.";
// Create the new manifest plist
$plist = new CFPropertyList();
$plist->add( $dict = new CFDictionary() );
// Add manifest to production catalog by default
$dict->add( 'catalogs', $array = new CFArray() );
$array->add( new CFString( 'production' ) );
// Add parent manifest to included_manifests to achieve waterfall effect
$dict->add( 'included_manifests', $array = new CFArray() );
$array->add( new CFString( $identifier ) );
// Save the newly created plist
$plist->saveXML( $machine_manifest );
}
?>
|
<?php
namespace CFPropertyList;
require_once( 'cfpropertylist-2.0.1/CFPropertyList.php' );
// Get the munki repo directory
$plist = new CFPropertyList( '/Library/Preferences/com.github.munki.plist' );
$arrPref = $plist->toArray();
$munki_repo = $arrPref['MUNKI_REPO'];
// Get the varibles passed by the enroll script
$identifier = $_GET["identifier"];
$hostname = $_GET["hostname"];
// Check if manifest already exists for this machine
if ( file_exists( $munki_repo . '/manifests/' . $hostname ) )
{
echo "Computer manifest already exists.";
}
else
{
echo "Computer manifest does not exist.";
// Create the new manifest plist
$plist = new CFPropertyList();
$plist->add( $dict = new CFDictionary() );
// Add manifest to production catalog by default
$dict->add( 'catalogs', $array = new CFArray() );
$array->add( new CFString( 'production' ) );
// Add parent manifest to included_manifests to achieve waterfall effect
$dict->add( 'included_manifests', $array = new CFArray() );
$array->add( new CFString( $identifier ) );
// Save the newly created plist
$plist->saveXML( $munki_repo . '/manifests/' . $hostname );
}
?>
|
Set up for showing schedule
|
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Import blockmodels file
import BlockModels
# this is some template "hello world" code
import webapp2
# imports jinja2
import jinja2
import os
jinja_environment = jinja2.Environment(autoescape=True,
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
class MainHandler(webapp2.RequestHandler):
def get(self):
schedule = schedule()
template_values = {
'schedule': schedule,
}
template = jinja_environment.get_template('frontendproto.html')
self.response.out.write(template.render(template_values))
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
|
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# 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.
#
# this is some template "hello world" code
import webapp2
# imports jinja2
import jinja2
import os
jinja_environment = jinja2.Environment(autoescape=True,
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
current_block = '7'
class MainHandler(webapp2.RequestHandler):
def get(self):
template_values = {
'block': current_block,
}
template = jinja_environment.get_template('frontendproto.html')
self.response.out.write(template.render(template_values))
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
for block in Blocks:
block.name =
|
Add description to rst plugin
|
"""Check that files contains valid ReStructuredText."""
import os
import fnmatch
import restructuredtext_lint
DEFAULTS = {
'files': '*.rst',
}
def make_message(error):
return '%s %s:%s %s\n' % (
error.type, error.source, error.line, error.message,
)
def check(file_staged_for_commit, options):
basename = os.path.basename(file_staged_for_commit.path)
if not fnmatch.fnmatch(basename, options.rst_files):
return True
errors = restructuredtext_lint.lint(
file_staged_for_commit.contents,
file_staged_for_commit.path,
)
if errors:
print('\n'.join(make_message(e) for e in errors))
return False
else:
return True
|
import os
import fnmatch
import restructuredtext_lint
DEFAULTS = {
'files': '*.rst',
}
def make_message(error):
return '%s %s:%s %s\n' % (
error.type, error.source, error.line, error.message,
)
def check(file_staged_for_commit, options):
basename = os.path.basename(file_staged_for_commit.path)
if not fnmatch.fnmatch(basename, options.rst_files):
return True
errors = restructuredtext_lint.lint(
file_staged_for_commit.contents,
file_staged_for_commit.path,
)
if errors:
print('\n'.join(make_message(e) for e in errors))
return False
else:
return True
|
Use hash based location type for now to support IE9 / ember bug
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'hash',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.baseURL = '/ember-css-transitions'
}
return ENV;
};
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.baseURL = '/ember-css-transitions'
}
return ENV;
};
|
Fix naming bug in doc test
|
from unittest import TestCase
import importlib
def get_undocumented_wildcards(modulename):
namespace = importlib.import_module(modulename)
loc = namespace.__dict__
undocumented = []
for key, val in loc.items():
if (key[0] != "_") and (key not in {"_", "In", "Out", "get_ipython", "exit", "quit", "join", "S", }):
description = val.__doc__
if not description:
undocumented.append(key)
return undocumented, len(loc.items())
class TestFlow(TestCase):
def test_phi_flow(self):
modulename = "phi.flow"
undocumented, loc_len = get_undocumented_wildcards(modulename)
undocumented_fraction = len(undocumented) / loc_len
self.assertLess(undocumented_fraction, 0.25, f"{len(undocumented)/loc_len:.2%} of {modulename} imports undocumented. Missing Docstrings in {len(undocumented)}/{loc_len}:\n- " + "\n- ".join(undocumented))
|
from unittest import TestCase
import importlib
def get_undocumented_wildcards(modulename):
namespace = importlib.import_module(modulename)
loc = namespace.__dict__
undocumented = []
for key, val in loc.items():
if (key[0] != "_") and (key not in {"_", "In", "Out", "get_ipython", "exit", "quit", "join", "S", }):
description = val.__doc__
if not description:
undocumented.append(key)
return undocumented, len(loc.items())
class TestFlow(TestCase):
def check_phi_flow(self):
modulename = "phi.flow"
undocumented, loc_len = get_undocumented_wildcards(modulename)
undocumented_fraction = len(undocumented) / loc_len
self.assertLess(undocumented_fraction, 0.25, f"{len(undocumented)/loc_len:.2%} of {modulename} imports undocumented. Missing Docstrings in {len(undocumented)}/{loc_len}:\n- " + "\n- ".join(undocumented))
|
Use the correct base path.
|
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
__all__ = [
'DEFAULT_LOGGING_CONF_PATH'
]
BASE_PATH = os.path.dirname(os.path.abspath((__file__)))
DEFAULT_LOGGING_CONF_PATH = os.path.join(BASE_PATH, '../conf/base.logging.conf')
DEFAULT_LOGGING_CONF_PATH = os.path.abspath(DEFAULT_LOGGING_CONF_PATH)
|
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
__all__ = [
'DEFAULT_LOGGING_CONF_PATH'
]
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
DEFAULT_LOGGING_CONF_PATH = os.path.join(BASE_PATH, '../conf/base.logging.conf')
DEFAULT_LOGGING_CONF_PATH = os.path.abspath(DEFAULT_LOGGING_CONF_PATH)
|
Replace the take name error with one that made more sense to display on the login view.
|
'use strict';
var Q = require('q');
module.exports = {
findByName: function(name) {
var deferred = Q.defer();
if(name === null || name === undefined) {
deferred.reject('What are we supposed to name you?');
return deferred.promise;
}
User.findOne({ name: name }).exec(function(err, user) {
if(user) {
deferred.reject('Sorry, someone already claimed that name!');
return;
}
if(err) {
deferred.reject(err);
return;
}
User.create({ name: name }).exec(function(err, user) {
if(err) {
deferred.reject(err);
}
deferred.resolve(user);
});
});
return deferred.promise;
},
removeByUser: function(user) {
var deferred = Q.defer();
User.destroy({ id: user.id }).exec(function(err) {
if(err) {
deferred.reject(err);
}
else {
deferred.resolve();
}
});
return deferred.promise;
}
};
|
'use strict';
var Q = require('q');
module.exports = {
findByName: function(name) {
var deferred = Q.defer();
if(name === null || name === undefined) {
deferred.reject('What are we supposed to name you?');
return deferred.promise;
}
User.findOne({ name: name }).exec(function(err, user) {
if(user) {
deferred.reject('You can\'t take a name already in use.');
return;
}
if(err) {
deferred.reject(err);
return;
}
User.create({ name: name }).exec(function(err, user) {
if(err) {
deferred.reject(err);
}
deferred.resolve(user);
});
});
return deferred.promise;
},
removeByUser: function(user) {
var deferred = Q.defer();
User.destroy({ id: user.id }).exec(function(err) {
if(err) {
deferred.reject(err);
}
else {
deferred.resolve();
}
});
return deferred.promise;
}
};
|
Add units and different translation types to translate from position effect
|
import { SplashEffect } from "./effect.js";
import { Linear } from "../interpolation.js";
export class TranslateFromPosition extends SplashEffect {
constructor(element, options) {
super(element);
options = options || {};
this.x = options.x || 0;
this.y = options.y || 0;
// Can be whatever, but the effect won't do
// anything if it isn't a valid css unit.
this.unit = options.unit || "px";
// Can be either "transform" or "position"
this.translationType = options.translationType || "transform";
this.interpolation = options.interpolation || new Linear();
}
in(value) {
this._set(
this.interpolation.in(value * -1 + 1) * this.x,
this.interpolation.in(value * -1 + 1) * this.y
);
}
out(value) {
this._set(
this.interpolation.out(value) * this.x,
this.interpolation.out(value) * this.y
);
}
_set(x, y) {
if (this.translationType = "transform") {
this.setTransform("translateX", x + this.unit);
this.setTransform("translateY", y + this.unit);
} else if (this.translationType = "position") {
this.setStyle("left", x + this.unit);
this.setStyle("top", y + this.unit);
} else {
console.error("Unknown translation type: " + this.translationType);
}
}
}
|
import { SplashEffect } from "./effect.js";
import { Linear } from "../interpolation.js";
export class TranslateFromPosition extends SplashEffect {
constructor(element, options) {
super(element);
options = options || {};
this.x = options.x || 0;
this.y = options.y || 0;
this.interpolation = options.interpolation || new Linear();
}
in(value) {
let x = this.interpolation.in(value * -1 + 1) * this.x,
y = this.interpolation.in(value * -1 + 1) * this.y;
this.setStyle("left", x + "px");
this.setStyle("top", y + "px");
}
out(value) {
let x = this.interpolation.out(value) * this.x,
y = this.interpolation.out(value) * this.y;
this.setStyle("left", x + "px");
this.setStyle("top", y + "px");
}
}
|
Define block "code" for highlighting
|
var Prism = require('prismjs');
var path = require('path');
var prismCSS = require.resolve('prismjs/themes/prism.css');
var DEFAULT_LANGUAGE = 'javascript';
var MAP_LANGUAGES = {
'py': 'python',
'js': 'javascript',
'json': 'javascript',
'rb': 'ruby',
'csharp': 'cs',
};
var assets = {
assets: path.dirname(prismCSS),
css: [path.basename(prismCSS)]
};
module.exports = {
book: assets,
ebook: assets,
blocks: {
code: function(block) {
// Normalize language id
var lang = block.kwargs.language || DEFAULT_LANGUAGE;
lang = MAP_LANGUAGES[lang] || lang;
// Get languages from prism
lang = Prism.languages[lang] || Prism.languages[DEFAULT_LANGUAGE];
return Prism.highlight(block.body, lang);
}
}
};
|
var Prism = require('prismjs');
var cheerio = require('cheerio');
var path = require('path');
var prismCSS = require.resolve('prismjs/themes/prism.css');
module.exports = {
book: {
assets: path.dirname(prismCSS),
css: [path.basename(prismCSS)]
},
hooks: {
page: function (page) {
page.sections.forEach(function (section) {
var $ = cheerio.load(section.content);
$('code').each(function() {
var text = $(this).text();
var highlighted = Prism.highlight(text, Prism.languages.javascript);
$(this).html(highlighted);
});
section.content = $.html();
});
return page;
}
}
};
|
T7646: Fix buildplan ac on Herald.
Summary: Fixes T7646.
Test Plan: Repeat steps described in T7646 and expect disabled build plans not displayed.
Reviewers: epriestley, #blessed_reviewers
Reviewed By: epriestley, #blessed_reviewers
Subscribers: Korvin, epriestley
Maniphest Tasks: T7646
Differential Revision: https://secure.phabricator.com/D12133
|
<?php
final class HarbormasterBuildPlanDatasource
extends PhabricatorTypeaheadDatasource {
public function getPlaceholderText() {
return pht('Type a build plan name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorHarbormasterApplication';
}
public function loadResults() {
$viewer = $this->getViewer();
$raw_query = $this->getRawQuery();
$results = array();
$plans = id(new HarbormasterBuildPlanQuery())
->setViewer($viewer)
->execute();
foreach ($plans as $plan) {
$closed = null;
if ($plan->isDisabled()) {
$closed = pht('Disabled');
}
$results[] = id(new PhabricatorTypeaheadResult())
->setName($plan->getName())
->setClosed($closed)
->setPHID($plan->getPHID());
}
return $results;
}
}
|
<?php
final class HarbormasterBuildPlanDatasource
extends PhabricatorTypeaheadDatasource {
public function getPlaceholderText() {
return pht('Type a build plan name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorHarbormasterApplication';
}
public function loadResults() {
$viewer = $this->getViewer();
$raw_query = $this->getRawQuery();
$results = array();
$plans = id(new HarbormasterBuildPlanQuery())
->setViewer($viewer)
->execute();
foreach ($plans as $plan) {
$results[] = id(new PhabricatorTypeaheadResult())
->setName($plan->getName())
->setPHID($plan->getPHID());
}
return $results;
}
}
|
Fix the calculation of SpyReport.ValidUntil
|
package entities
import (
"fmt"
"time"
"github.com/Vladimiroff/vec2d"
)
type SpyReport struct {
Player string
Name string
Owner string
Position *vec2d.Vector
ShipCount int32
ValidUntil int64
CreatedAt int64
}
// Database key.
func (s *SpyReport) Key() string {
return fmt.Sprintf("spy_report.%s_%d", s.Player, s.CreatedAt)
}
// It has to be there in order to implement Entity
func (s *SpyReport) AreaSet() string {
return ""
}
func (s *SpyReport) IsValid() bool {
return s.ValidUntil > time.Now().Unix()
}
func CreateSpyReport(target *Planet, mission *Mission) *SpyReport {
now := time.Now().Unix()
report := &SpyReport{
Player: mission.Player,
Name: target.Name,
Owner: target.Owner,
Position: target.Position,
ShipCount: target.ShipCount,
CreatedAt: now,
ValidUntil: now + SPY_REPORT_VALIDITY,
}
Save(report)
return report
}
|
package entities
import (
"fmt"
"time"
"github.com/Vladimiroff/vec2d"
)
type SpyReport struct {
Player string
Name string
Owner string
Position *vec2d.Vector
ShipCount int32
ValidUntil int64
CreatedAt int64
}
// Database key.
func (s *SpyReport) Key() string {
return fmt.Sprintf("spy_report.%s_%d", s.Player, s.CreatedAt)
}
// It has to be there in order to implement Entity
func (s *SpyReport) AreaSet() string {
return ""
}
func (s *SpyReport) IsValid() bool {
return s.ValidUntil > time.Now().UnixNano()/1e6
}
func CreateSpyReport(target *Planet, mission *Mission) *SpyReport {
now := time.Now().UnixNano() / 1e6
report := &SpyReport{
Player: mission.Player,
Name: target.Name,
Owner: target.Owner,
Position: target.Position,
ShipCount: target.ShipCount,
CreatedAt: now,
ValidUntil: now + SPY_REPORT_VALIDITY*1000,
}
Save(report)
return report
}
|
Add colormap option to show().
|
import code
import collections
import logging
import sys
import numpy
import rasterio
logger = logging.getLogger('rasterio')
Stats = collections.namedtuple('Stats', ['min', 'max', 'mean'])
def main(banner, dataset):
def show(source, cmap='gray'):
"""Show a raster using matplotlib.
The raster may be either an ndarray or a (dataset, bidx)
tuple.
"""
import matplotlib.pyplot as plt
if isinstance(source, tuple):
arr = source[0].read_band(source[1])
else:
arr = source
plt.imshow(arr, cmap=cmap)
plt.show()
def stats(source):
"""Return a tuple with raster min, max, and mean.
"""
if isinstance(source, tuple):
arr = source[0].read_band(source[1])
else:
arr = source
return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr))
code.interact(
banner, local=dict(locals(), src=dataset, np=numpy, rio=rasterio))
return 0
|
import code
import collections
import logging
import sys
import numpy
import rasterio
logger = logging.getLogger('rasterio')
Stats = collections.namedtuple('Stats', ['min', 'max', 'mean'])
def main(banner, dataset):
def show(source):
"""Show a raster using matplotlib.
The raster may be either an ndarray or a (dataset, bidx)
tuple.
"""
import matplotlib.pyplot as plt
if isinstance(source, tuple):
arr = source[0].read_band(source[1])
else:
arr = source
plt.imshow(arr)
plt.gray()
plt.show()
def stats(source):
"""Return a tuple with raster min, max, and mean.
"""
if isinstance(source, tuple):
arr = source[0].read_band(source[1])
else:
arr = source
return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr))
code.interact(
banner, local=dict(locals(), src=dataset, np=numpy, rio=rasterio))
return 0
|
Add the promisification in the service in order to be treated by the view.
|
/* global Promise */
var Reference = require('../models/reference');
var References = require('../models/references');
var Promisify = require('../models/promisify');
/*Instances of both model and collection of virtual machines.*/
var promiseReference = Promisify.Convert.Model(new Reference());
var promiseReferences = Promisify.Convert.Collection(new References());
function saveReference(model) {
reference.clear({
silent: true
});
new Promise(function(resolve, reject) {
reference.save(model.toJSON(), {
success: resolve,
error: reject
});
}).then(function success(argument) {
console.log("Success", argument);
}, function(error) {
console.log("error", error);
});
}
//Load all the references of the application
function loadReferences() {
promiseReferences.reset(null, {silent: true});
return promiseReferences.fetch();
}
module.exports = {
save: saveReference,
loadAll: loadReferences
};
|
/* global Promise */
var Reference = require('../models/reference');
var reference = new Reference();
// var References = require('../models/references');
// var references = new References();
var Promisify = require('../models/promisify');
var promiseCollection = new Promisify.Collection();
promiseCollection.url = reference.url;
function saveReference(model) {
reference.clear({
silent: true
});
new Promise(function(resolve, reject) {
reference.save(model.toJSON(), {
success: resolve,
error: reject
});
}).then(function success(argument) {
console.log("Success", argument);
}, function(error) {
console.log("error", error);
});
}
function loadReferences(collection) {
promiseCollection.reset(collection.toJSON());
promiseCollection.fetch().then(function success(jsonResponse) {
console.log('success promisify fetch', jsonResponse);
collection.reset(jsonResponse);
}, function error(err) {
console.log("error promisify fetch", err);
});
// new Promise(function(resolve, reject) {
// collection.fetch({
// success: resolve,
// error: reject
// });
// }).then(function success(argument) {
// console.log('success promise fetch', argument);
// collection.reset(argument.toJSON());
// }, function error(err) {
// console.log("error promise fetch", err);
// });
}
module.exports = {
save: saveReference,
loadAll: loadReferences
};
|
Enable form submit by pressing enter
|
module.exports = (model, dispatch) => {
const root = document.createElement('div');
if (model.channelOnEdit === null) {
return root;
}
const c = model.channelOnEdit;
const title = model.channels[c].title;
const row = document.createElement('div');
row.classList.add('row');
row.classList.add('row-input');
const form = document.createElement('form');
const text = document.createElement('input');
text.type = 'text';
text.value = title;
form.appendChild(text);
const okBtn = document.createElement('button');
okBtn.type = 'button';
okBtn.innerHTML = 'OK';
form.appendChild(okBtn);
row.appendChild(form);
root.appendChild(row);
// Events
setTimeout(() => {
text.focus();
}, 200);
form.addEventListener('submit', ev => {
ev.preventDefault();
dispatch({
type: 'EDIT_CHANNEL_TITLE',
channel: c,
title: text.value
});
});
okBtn.addEventListener('click', ev => {
dispatch({
type: 'EDIT_CHANNEL_TITLE',
channel: c,
title: text.value
});
});
return root;
}
|
module.exports = (model, dispatch) => {
const root = document.createElement('div');
if (model.channelOnEdit === null) {
return root;
}
const c = model.channelOnEdit;
const title = model.channels[c].title;
const row = document.createElement('div');
row.classList.add('row');
row.classList.add('row-input');
const form = document.createElement('form');
const text = document.createElement('input');
text.type = 'text';
text.value = title;
form.appendChild(text);
const okBtn = document.createElement('button');
okBtn.innerHTML = 'OK';
okBtn.addEventListener('click', ev => {
dispatch({
type: 'EDIT_CHANNEL_TITLE',
channel: c,
title: text.value
});
});
form.appendChild(okBtn);
row.appendChild(form);
root.appendChild(row);
return root;
}
|
Fix bug in mondegreen rule
(The correct versions should all be in the left column.)
|
# -*- coding: utf-8 -*-
"""Mondegreens.
---
layout: post
source: Garner's Modern American Usage
source_url: http://amzn.to/15wF76r
title: mondegreens
date: 2014-06-10 12:31:19
categories: writing
---
Points out preferred form.
"""
from tools import memoize, preferred_forms_check
@memoize
def check(text):
"""Suggest the preferred forms."""
err = "garner.mondegreens"
msg = "'{}' is the preferred form."
list = [
["a girl with kaleidascope eyes", "a girl with colitis goes by"],
["a partridge in a pear tree", "a part-red gingerbread tree"],
["attorney and not a republic", "attorney and notary public"],
["beck and call", "beckon call"],
["for all intents and purposes", "for all intensive purposes"],
["laid him on the green", "Lady Mondegreen"],
["Olive, the other reindeer", "all of the other reindeer"],
["to the manner born", "to the manor born"],
]
return preferred_forms_check(text, list, err, msg)
|
# -*- coding: utf-8 -*-
"""Mondegreens.
---
layout: post
source: Garner's Modern American Usage
source_url: http://amzn.to/15wF76r
title: mondegreens
date: 2014-06-10 12:31:19
categories: writing
---
Points out preferred form.
"""
from tools import memoize, preferred_forms_check
@memoize
def check(text):
"""Suggest the preferred forms."""
err = "garner.mondegreens"
msg = "'{}' is the preferred form."
list = [
["a girl with colitis goes by", "a girl with kaleidascope eyes"],
["a partridge in a pear tree", "a part-red gingerbread tree"],
["attorney and not a republic", "attorney and notary public"],
["beck and call", "beckon call"],
["for all intents and purposes", "for all intensive purposes"],
["laid him on the green", "Lady Mondegreen"],
["Olive, the other reindeer", "all of the other reindeer"],
["to the manner born", "to the manor born"],
]
return preferred_forms_check(text, list, err, msg)
|
Use default logger when not in dev
|
"use strict";
var express = require("express"),
helpers = require("./src/helpers");
module.exports = function () {
var app = express();
app.use( express.compress() );
// development only
if ("development" == app.get("env")) {
app.use(express.logger("dev"));
} else {
app.use(express.logger("default"));
}
// Set up the default response
app.use(function (req, res, next) {
// By default don't cache anything (much easier when working with CloudFront)
res.header( "Cache-Control", helpers.cacheControl(0) );
// Allow all domains to request data (see CORS for more details)
res.header("Access-Control-Allow-Origin", "*");
next();
});
// Load the sub-apps
app.use("/country", require("./src/country"));
app.use("/books", require("./src/books"));
app.use("/echo", require("./src/echo"));
// 404 everything that was not caught above
app.all("*", function (req, res) {
res.status(404);
res.jsonp({ error: "404 - page not found" });
});
// Default error handling - TODO change to JSON
app.use(express.errorHandler());
return app;
};
|
"use strict";
var express = require("express"),
helpers = require("./src/helpers");
module.exports = function () {
var app = express();
app.use( express.compress() );
// development only
if ("development" == app.get("env")) {
app.use(express.logger("dev"));
}
// Set up the default response
app.use(function (req, res, next) {
// By default don't cache anything (much easier when working with CloudFront)
res.header( "Cache-Control", helpers.cacheControl(0) );
// Allow all domains to request data (see CORS for more details)
res.header("Access-Control-Allow-Origin", "*");
next();
});
// Load the sub-apps
app.use("/country", require("./src/country"));
app.use("/books", require("./src/books"));
app.use("/echo", require("./src/echo"));
// 404 everything that was not caught above
app.all("*", function (req, res) {
res.status(404);
res.jsonp({ error: "404 - page not found" });
});
// Default error handling - TODO change to JSON
app.use(express.errorHandler());
return app;
};
|
Add wrapper for event data elem
|
from __future__ import print_function
import boto3
import json
import os
import btr3baseball
jobTable = os.environ['JOB_TABLE']
jobQueue = os.environ['JOB_QUEUE']
queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue)
jobRepo = btr3baseball.JobRepository(jobTable)
dsRepo = btr3baseball.DatasourceRepository()
def main(event, context):
method = event['method']
if method == 'submitJob':
return submitJob(event['data'], context)
elif method == 'getJob':
return getJob(event['data'], context)
elif method == 'listDatasources':
return listDatasources(event['data'], context)
elif method == 'getDatasource':
return getDatasource(event['data'], context)
else:
return None
def submitJob(event, context):
# Put initial entry in dynamo db
jobId = jobRepo.createJob(event)
# Put the job ID on the SQS queue
response = queue.send_message(MessageBody=jobId)
# Update the DB entry with sqs message ID for traceability
return jobRepo.updateWithMessageId(jobId, response.get('MessageId'))
def getJob(event, context):
return jobRepo.getJob(event['jobId'])
def listDatasources(event, context):
return dsRepo.listDatasources()
def getDatasource(event, context):
return dsRepo.getDatasource(event['datasourceId'])
|
from __future__ import print_function
import boto3
import json
import os
import btr3baseball
jobTable = os.environ['JOB_TABLE']
jobQueue = os.environ['JOB_QUEUE']
queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue)
jobRepo = btr3baseball.JobRepository(jobTable)
dsRepo = btr3baseball.DatasourceRepository()
def main(event, context):
method = event['method']
if method == 'submitJob':
return submitJob(event, context)
elif method == 'getJob':
return getJob(event, context)
elif method == 'listDatasources':
return listDatasources(event, context)
elif method == 'getDatasource':
return getDatasource(event, context)
else:
return null
def submitJob(event, context):
# Put initial entry in dynamo db
jobId = jobRepo.createJob(event)
# Put the job ID on the SQS queue
response = queue.send_message(MessageBody=jobId)
# Update the DB entry with sqs message ID for traceability
return jobRepo.updateWithMessageId(jobId, response.get('MessageId'))
def getJob(event, context):
return jobRepo.getJob(event['jobId'])
def listDatasources(event, context):
return dsRepo.listDatasources()
def getDatasource(event, context):
return dsRepo.getDatasource(event['datasourceId'])
|
Fix Compilation Error in React Native 0.47.0
|
package com.rt2zz.reactnativecontacts;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ReactNativeContacts implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new ContactsManager(reactContext));
return modules;
}
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList();
}
}
|
package com.rt2zz.reactnativecontacts;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ReactNativeContacts implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new ContactsManager(reactContext));
return modules;
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList();
}
}
|
Rename variables used for setting up logging
|
import logging
import sys
logger = logging.getLogger()
formatter = logging.Formatter("%(message)s")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
UNDERLINE_SYMBOL = "-"
def log_title(logline):
logger.info(logline)
logger.info(len(logline) * UNDERLINE_SYMBOL)
def log_blank_line():
logger.info("")
def log(
installed,
packages_not_needed_by_other,
packages_needed_by_other,
package_dependencies,
):
log_title("Installed packages:")
logger.info(", ".join(sorted(installed)))
log_blank_line()
log_title("No package depends on these packages:")
logger.info(", ".join(sorted(packages_not_needed_by_other)))
log_blank_line()
log_title("These packages are needed by other packages:")
for package, needed_by in sorted(packages_needed_by_other.items()):
logger.info("Package {} is needed by: {}".format(package, ", ".join(needed_by)))
log_blank_line()
log_title("These packages depend on other packages:")
for package, package_dependencies in sorted(package_dependencies.items()):
logger.info(
"Package {} depends on: {}".format(package, ", ".join(package_dependencies))
)
log_blank_line()
|
import logging
import sys
logger = logging.getLogger()
logFormatter = logging.Formatter("%(message)s")
consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(logFormatter)
logger.addHandler(consoleHandler)
logger.setLevel(logging.INFO)
UNDERLINE_SYMBOL = "-"
def log_title(logline):
logger.info(logline)
logger.info(len(logline) * UNDERLINE_SYMBOL)
def log_blank_line():
logger.info("")
def log(
installed,
packages_not_needed_by_other,
packages_needed_by_other,
package_dependencies,
):
log_title("Installed packages:")
logger.info(", ".join(sorted(installed)))
log_blank_line()
log_title("No package depends on these packages:")
logger.info(", ".join(sorted(packages_not_needed_by_other)))
log_blank_line()
log_title("These packages are needed by other packages:")
for package, needed_by in sorted(packages_needed_by_other.items()):
logger.info("Package {} is needed by: {}".format(package, ", ".join(needed_by)))
log_blank_line()
log_title("These packages depend on other packages:")
for package, package_dependencies in sorted(package_dependencies.items()):
logger.info(
"Package {} depends on: {}".format(package, ", ".join(package_dependencies))
)
log_blank_line()
|
Simplify test to check for no aerialway property
|
# http://www.openstreetmap.org/way/219071307
assert_has_feature(
16, 10478, 25338, 'roads',
{ 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' })
# http://www.openstreetmap.org/way/258020271
assert_has_feature(
16, 11077, 25458, 'roads',
{ 'id': 258020271, 'kind': 'aerialway', 'aerialway': 't_bar' })
# http://www.openstreetmap.org/way/256717307
assert_has_feature(
16, 18763, 24784, 'roads',
{ 'id': 256717307, 'kind': 'aerialway', 'aerialway': 'j_bar' })
# http://www.openstreetmap.org/way/258132198
assert_has_feature(
16, 10910, 25120, 'roads',
{ 'id': 258132198, 'kind': 'aerialway', 'aerialway': type(None) })
|
# http://www.openstreetmap.org/way/219071307
assert_has_feature(
16, 10478, 25338, 'roads',
{ 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' })
# http://www.openstreetmap.org/way/258020271
assert_has_feature(
16, 11077, 25458, 'roads',
{ 'id': 258020271, 'kind': 'aerialway', 'aerialway': 't_bar' })
# http://www.openstreetmap.org/way/256717307
assert_has_feature(
16, 18763, 24784, 'roads',
{ 'id': 256717307, 'kind': 'aerialway', 'aerialway': 'j_bar' })
# http://www.openstreetmap.org/way/258132198
# verify that no aerialway subkind exists when its value is yes
with features_in_tile_layer(16, 10910, 25120, 'roads') as features:
for feature in features:
props = feature['properties']
if props['id'] == 258132198:
assert props['kind'] == 'aerialway'
assert 'aerialway' not in props
break
else:
assert 0, 'No feature with id 258132198 found'
|
Add comments to function and loop for clarity
|
/*This function will take the updated index number
from my loop, apply these rules, and then output
ping, pong, pingpong or the index number into
the outputList */
var pingPongType = function(i) {
if ((i % 5 === 0) || (i % 3 === 0) || (i % 15 === 0)) {
if (i % 15 === 0) {
return "pingpong";
} else if (i % 5 === 0) {
return "pong";
} else {
return "ping";
}
} else {
return i;
}
}
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
var warning = "Whoops! Please enter a number (decimals will be rounded)!"
if (Number.isNaN(number) === true) {
alert(warning);
}
/*This loop will count from 1 to the user input number,
run each index number through the pingPongType function,
then output the results into the outputList*/
for (var i = 1; i <= number; i += 1) {
var output = pingPongType(i)
$('#outputList').append("<li>" + output + "</li>")
}
event.preventDefault();
});
});
|
var pingPongType = function(i) {
if ((i % 5 === 0) || (i % 3 === 0) || (i % 15 === 0)) {
if (i % 15 === 0) {
return "pingpong";
} else if (i % 5 === 0) {
return "pong";
} else {
return "ping";
}
} else {
return i;
}
}
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
var warning = "Whoops! Please enter a number (decimals will be rounded)!"
if (Number.isNaN(number) === true) {
alert(warning);
}
for (var i = 1; i <= number; i += 1) {
var output = pingPongType(i)
$('#outputList').append("<li>" + output + "</li>")
}
event.preventDefault();
});
});
|
Make +s actually definitely clear the cdata dictionary
|
from txircd.modbase import Mode
class SecretMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
cdata = data["cdata"]
if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
data["cdata"].clear()
# other +s stuff is hiding in other modules.
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.mode_s = None
def spawn(self):
self.mode_s = SecretMode()
return {
"modes": {
"cns": self.mode_s
},
"actions": {
"commandextra": [self.mode_s.listOutput]
}
}
def cleanup(self):
self.ircd.removeMode("cns")
self.ircd.actions["commandextra"].remove(self.mode_s.listOutput)
|
from txircd.modbase import Mode
class SecretMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
cdata = data["cdata"]
if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
data["cdata"] = {}
# other +s stuff is hiding in other modules.
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.mode_s = None
def spawn(self):
self.mode_s = SecretMode()
return {
"modes": {
"cns": self.mode_s
},
"actions": {
"commandextra": [self.mode_s.listOutput]
}
}
def cleanup(self):
self.ircd.removeMode("cns")
self.ircd.actions["commandextra"].remove(self.mode_s.listOutput)
|
Increase UpdateUserWorker: 1 -> 3
|
package com.github.k0kubun.github_ranking;
import com.github.k0kubun.github_ranking.config.Config;
import com.github.k0kubun.github_ranking.worker.UpdateUserWorker;
import com.github.k0kubun.github_ranking.worker.WorkerManager;
import javax.sql.DataSource;
public class Main
{
private static final int NUM_UPDATE_USER_WORKERS = 3;
public static void main(String[] args)
{
Config config = new Config(System.getenv());
WorkerManager workers = buildWorkers(config);
Runtime.getRuntime().addShutdownHook(new Thread(workers::stop));
workers.start();
}
private static WorkerManager buildWorkers(Config config)
{
DataSource dataSource = config.getDatabaseConfig().getDataSource();
WorkerManager workers = new WorkerManager();
for (int i = 0; i < NUM_UPDATE_USER_WORKERS; i++) {
workers.add(new UpdateUserWorker(dataSource));
}
return workers;
}
}
|
package com.github.k0kubun.github_ranking;
import com.github.k0kubun.github_ranking.config.Config;
import com.github.k0kubun.github_ranking.worker.UpdateUserWorker;
import com.github.k0kubun.github_ranking.worker.WorkerManager;
import javax.sql.DataSource;
public class Main
{
public static void main(String[] args)
{
Config config = new Config(System.getenv());
WorkerManager workers = buildWorkers(config);
Runtime.getRuntime().addShutdownHook(new Thread(workers::stop));
workers.start();
}
private static WorkerManager buildWorkers(Config config)
{
DataSource dataSource = config.getDatabaseConfig().getDataSource();
WorkerManager workers = new WorkerManager();
workers.add(new UpdateUserWorker(dataSource));
return workers;
}
}
|
Fix deprecation for symfony/config 4.2+
|
<?php
namespace Hype\MailchimpBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface {
public function getConfigTreeBuilder() {
$treeBuilder = new TreeBuilder('hype_mailchimp');
$rootNode = \method_exists(TreeBuilder::class, 'getRootNode') ? $treeBuilder->getRootNode() : $treeBuilder->root('hype_mailchimp');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
$rootNode->children()
->scalarNode('api_key')->isRequired()->cannotBeEmpty()->end()
->scalarNode('default_list')->isRequired()->cannotBeEmpty()->end()
->booleanNode('ssl')->defaultTrue()->end()
->integerNode('timeout')->defaultValue(20)->end()
->end();
return $treeBuilder;
}
}
|
<?php
namespace Hype\MailchimpBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface {
public function getConfigTreeBuilder() {
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('hype_mailchimp');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
$rootNode->children()
->scalarNode('api_key')->isRequired()->cannotBeEmpty()->end()
->scalarNode('default_list')->isRequired()->cannotBeEmpty()->end()
->booleanNode('ssl')->defaultTrue()->end()
->integerNode('timeout')->defaultValue(20)->end()
->end();
return $treeBuilder;
}
}
|
Put function in scope & corect object usage
|
// Defining Module
var demoApp = angular.module('demoApp', ['ngRoute']);
// Defining Module Routes
demoApp.config(function($routeProvider) {
$routeProvider
.when('/view1', {
controller: 'simpleController',
templateUrl: 'partials/view1.html'
})
.when('/view2', {
controller: 'simpleController',
templateUrl: 'partials/view2.html'
})
.otherwise({
redirectTo: '/view1'
});
});
// Defining Controller
demoApp.controller('simpleController', function($scope) {
$scope.customers = [{
name: 'Dave Jones',
city: 'Phoenix'
}, {
name: 'Jamie Riley',
city: 'Atlanta'
}, {
name: 'Heedy Wahlin',
city: 'Chandler'
}, {
name: 'Thomas Wahlin',
city: 'Seattle'
}];
// Defining addCustomer for Adding New Customers
$scope.addCustomer = function() {
$scope.customers.push({
name: $scope.newCustomer.name,
city: $scope.newCustomer.city
});
};
});
|
// Defining Module
var demoApp = angular.module('demoApp', ['ngRoute']);
// Defining Module Routes
demoApp.config(function($routeProvider) {
$routeProvider
.when('/view1', {
controller: 'simpleController',
templateUrl: 'partials/view1.html'
})
.when('/view2', {
controller: 'simpleController',
templateUrl: 'partials/view2.html'
})
.otherwise({
redirectTo: '/view1'
});
});
// Defining Controller
demoApp.controller('simpleController', function($scope) {
$scope.customers = [{
name: 'Dave Jones',
city: 'Phoenix'
}, {
name: 'Jamie Riley',
city: 'Atlanta'
}, {
name: 'Heedy Wahlin',
city: 'Chandler'
}, {
name: 'Thomas Wahlin',
city: 'Seattle'
}];
});
// Defining addCustomer for Adding New Customers
$scope.addCustomer = function() {
$scope.customer.push({
name: $scope.newCustomer.name,
city: $scope.newCustomer.city
});
};
|
Add list of category codes to offices
|
from rest_framework import serializers
from rest_framework_gis import serializers as gis_serializers
from .models import Location, Office, Organisation
class DistanceField(serializers.ReadOnlyField):
def to_representation(self, obj):
# miles
return obj.mi
class OrganisationSerializer(serializers.ModelSerializer):
class Meta:
model = Organisation
fields = ('name', 'website',)
class LocationSerializer(gis_serializers.GeoModelSerializer):
class Meta:
model = Location
fields = (
'address', 'city', 'postcode', 'point', 'type')
class OfficeSerializer(gis_serializers.GeoModelSerializer):
location = LocationSerializer()
organisation = OrganisationSerializer()
distance = DistanceField()
categories = serializers.SlugRelatedField(
slug_field='code', many=True, read_only=True)
class Meta:
model = Office
fields = (
'telephone', 'location', 'organisation', 'distance',
'categories')
|
from rest_framework import serializers
from rest_framework_gis import serializers as gis_serializers
from .models import Location, Office, Organisation
class DistanceField(serializers.ReadOnlyField):
def to_representation(self, obj):
# miles
return obj.mi
class OrganisationSerializer(serializers.ModelSerializer):
class Meta:
model = Organisation
fields = ('name', 'website',)
class LocationSerializer(gis_serializers.GeoModelSerializer):
class Meta:
model = Location
fields = (
'address', 'city', 'postcode', 'point', 'type')
class OfficeSerializer(gis_serializers.GeoModelSerializer):
location = LocationSerializer()
organisation = OrganisationSerializer()
distance = DistanceField()
class Meta:
model = Office
fields = (
'telephone', 'location', 'organisation', 'distance')
|
BAP-10771: Migrate data audit command to be executed in new message queue
- fix tests
|
<?php
namespace Oro\Bundle\DataAuditBundle\Migrations\Schema\v1_7;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class AddCollectionTypeColumn implements Migration
{
/**
* {@inheritdoc}
*/
public function up(Schema $schema, QueryBag $queries)
{
$auditFieldTable = $schema->getTable('oro_audit_field');
$auditFieldTable->addColumn('collection_diffs', 'json_array', [
'notnull' => false,
'comment' => '(DC2Type:json_array)',
]);
}
}
|
<?php
namespace Oro\Bundle\DataAuditBundle\Migrations\Schema\v1_7;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class AddCollectionTypeColumn implements Migration
{
/**
* {@inheritdoc}
*/
public function up(Schema $schema, QueryBag $queries)
{
$auditFieldTable = $schema->createTable('oro_audit_field');
$auditFieldTable->addColumn('collection_diffs', 'json_array', [
'notnull' => false,
'comment' => '(DC2Type:json_array)',
]);
}
}
|
Rename datetime to dateTime to keep consistency.
|
<?php
namespace CatLab\Requirements\Enums;
/**
* Interface PropertyType
* @package CatLab\RESTResource\Contracts
*/
class PropertyType
{
const INTEGER = 'integer';
const STRING = 'string';
const DATETIME = 'dateTime';
const NUMBER = 'number';
const BOOL = 'boolean';
const OBJECT = 'object';
/**
* @param $type
* @return bool
*/
public static function isNative($type)
{
return in_array($type, [
self::INTEGER,
self::STRING,
self::DATETIME,
self::NUMBER,
self::BOOL
]);
}
/**
* @param $type
* @return bool
*/
public static function isNumeric($type)
{
return in_array($type, [
self::INTEGER,
self::NUMBER
]);
}
}
|
<?php
namespace CatLab\Requirements\Enums;
/**
* Interface PropertyType
* @package CatLab\RESTResource\Contracts
*/
class PropertyType
{
const INTEGER = 'integer';
const STRING = 'string';
const DATETIME = 'datetime';
const NUMBER = 'number';
const BOOL = 'boolean';
const OBJECT = 'object';
/**
* @param $type
* @return bool
*/
public static function isNative($type)
{
return in_array($type, [
self::INTEGER,
self::STRING,
self::DATETIME,
self::NUMBER,
self::BOOL
]);
}
/**
* @param $type
* @return bool
*/
public static function isNumeric($type)
{
return in_array($type, [
self::INTEGER,
self::NUMBER
]);
}
}
|
Add visible version number in bottom corner of pages.
|
import React from 'react';
import styles from '../styles/core.scss';
import GlobalHeader from 'components/GlobalHeader';
var pjson = require('../../package.json');
// Note: Stateless/function components *will not* hot reload!
// react-transform *only* works on component classes.
//
// Since layouts rarely change, they are a good place to
// leverage React's new Statelesss Functions:
// https://facebook.github.io/react/docs/reusable-components.html#stateless-functions
//
// CoreLayout is a pure function of it's props, so we can
// define it with a plain javascript function...
function CoreLayout ({ children }) {
return (
<div className={styles['page-container']}>
<div className={styles['app-menu']}>
<GlobalHeader/>
</div>
<div className={styles['view-container']}>
{children}
</div>
<span style={{position: 'fixed', right: 2, bottom: 2, color: '#aaa', fontSize: '0.7em'}}>v{pjson.version}</span>
</div>
);
}
CoreLayout.propTypes = {
children: React.PropTypes.element
};
export default CoreLayout;
|
import React from 'react';
import styles from '../styles/core.scss';
import GlobalHeader from 'components/GlobalHeader';
// Note: Stateless/function components *will not* hot reload!
// react-transform *only* works on component classes.
//
// Since layouts rarely change, they are a good place to
// leverage React's new Statelesss Functions:
// https://facebook.github.io/react/docs/reusable-components.html#stateless-functions
//
// CoreLayout is a pure function of it's props, so we can
// define it with a plain javascript function...
function CoreLayout ({ children }) {
return (
<div className={styles['page-container']}>
<div className={styles['app-menu']}>
<GlobalHeader/>
</div>
<div className={styles['view-container']}>
{children}
</div>
</div>
);
}
CoreLayout.propTypes = {
children: React.PropTypes.element
};
export default CoreLayout;
|
Fix CSP errors in dummy app
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
contentSecurityPolicy: {
'font-src': "'self' http://*.herokucdn.com"
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
Fix startup error message when vendor directory not found
|
<?php
use app\core\router\Router;
use josegonzalez\Dotenv\Loader;
use app\core\logging\Logger;
define('APP_ROOT_DIR', realpath('..'));
define('APP_LIB_DIR', APP_ROOT_DIR . '/app/lib');
if (!file_exists(APP_ROOT_DIR . '/vendor/autoload.php')) {
http_response_code(500);
echo '<h1>"vendor" directory not found!</h1>';
exit();
}
if (empty($_SERVER['PHP_AUTH_USER']) || empty($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_USER'] != "guest" || $_SERVER['PHP_AUTH_PW'] != "please") {
header('WWW-Authenticate: Basic realm="Site is under construction"');
header('HTTP/1.0 401 Unauthorized');
echo "Sorry, you haven't access to this resource.";
exit;
}
$used_before = memory_get_usage();
require_once "../app/loader.php";
require_once "../vendor/autoload.php";
if (file_exists(APP_ROOT_DIR . '/.env')) {
$loader = new Loader(APP_ROOT_DIR . '/.env');
$loader->parse();
$loader->toEnv(true);
}
$router = Router::getInstance();
$router->run();
$used_after = memory_get_usage();
Logger::printf("Memory used: %d", $used_after - $used_before);
|
<?php
use app\core\router\Router;
use josegonzalez\Dotenv\Loader;
use app\core\logging\Logger;
define('APP_ROOT_DIR', realpath('..'));
define('APP_LIB_DIR', APP_ROOT_DIR . '/app/lib');
if (empty($_SERVER['PHP_AUTH_USER']) || empty($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_USER'] != "guest" || $_SERVER['PHP_AUTH_PW'] != "please") {
header('WWW-Authenticate: Basic realm="Site is under construction"');
header('HTTP/1.0 401 Unauthorized');
echo "Sorry, you haven't access to this resource.";
exit;
}
$used_before = memory_get_usage();
require_once "../app/loader.php";
require_once "../vendor/autoload.php";
if (file_exists(APP_ROOT_DIR . '/.env')) {
$loader = new Loader(APP_ROOT_DIR . '/.env');
$loader->parse();
$loader->toEnv(true);
}
$router = Router::getInstance();
$router->run();
$used_after = memory_get_usage();
Logger::printf("Memory used: %d", $used_after - $used_before);
|
Fix of hardcoded alias on JjUsers.UserUser
|
<?php
class UserUser extends JjUsersAppModel {
var $name = 'UserUser';
var $actsAs = array(
'Containable',
'Acl' => array('type' => 'requester'),
'JjUsers.AddAliasToAcl' => array('type' => 'requester', 'field' => 'username')
);
var $validate = array(
'user_group_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'username' => array(
'notempty' => array(
'rule' => array('notempty')
),
),
'password' => array(
'notempty' => array(
'rule' => array('notempty')
),
),
);
var $belongsTo = array(
'UserGroup' => array(
'className' => 'UserGroup',
'foreignKey' => 'user_group_id'
)
);
function parentNode()
{
if (!$this->id && empty($this->data))
return null;
$data = $this->data;
if (empty($this->data))
$data = $this->read();
return array('UserGroup' => array('id' => $data[$this->alias]['user_group_id']));
}
}
?>
|
<?php
class UserUser extends JjUsersAppModel {
var $name = 'UserUser';
var $actsAs = array(
'Containable',
'Acl' => array('type' => 'requester'),
'JjUsers.AddAliasToAcl' => array('type' => 'requester', 'field' => 'username')
);
var $validate = array(
'user_group_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'username' => array(
'notempty' => array(
'rule' => array('notempty')
),
),
'password' => array(
'notempty' => array(
'rule' => array('notempty')
),
),
);
var $belongsTo = array(
'UserGroup' => array(
'className' => 'UserGroup',
'foreignKey' => 'user_group_id'
)
);
function parentNode()
{
if (!$this->id && empty($this->data))
return null;
$data = $this->data;
if (empty($this->data))
$data = $this->read();
return array('UserGroup' => array('id' => $data['UserUser']['user_group_id']));
}
}
?>
|
Add helper method to VM
|
/*
* 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.
*/
package com.google.android.gnd.ui.editobservation;
import android.app.Application;
import androidx.lifecycle.MutableLiveData;
import com.google.android.gnd.model.observation.MultipleChoiceResponse;
import com.google.android.gnd.rx.Nil;
import java8.util.Optional;
import javax.inject.Inject;
public class MultipleChoiceFieldViewModel extends AbstractFieldViewModel {
private final MutableLiveData<Nil> showDialogClicks = new MutableLiveData<>();
@Inject
MultipleChoiceFieldViewModel(Application application) {
super(application);
}
public void onShowDialog() {
showDialogClicks.setValue(Nil.NIL);
}
MutableLiveData<Nil> getShowDialogClicks() {
return showDialogClicks;
}
Optional<MultipleChoiceResponse> getCurrentResponse() {
return getResponse().getValue() == null
? Optional.empty()
: getResponse().getValue().map(response -> (MultipleChoiceResponse) response);
}
}
|
/*
* 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.
*/
package com.google.android.gnd.ui.editobservation;
import android.app.Application;
import androidx.lifecycle.MutableLiveData;
import com.google.android.gnd.rx.Nil;
import javax.inject.Inject;
public class MultipleChoiceFieldViewModel extends AbstractFieldViewModel {
private final MutableLiveData<Nil> showDialogClicks = new MutableLiveData<>();
@Inject
MultipleChoiceFieldViewModel(Application application) {
super(application);
}
public void onShowDialog() {
showDialogClicks.setValue(Nil.NIL);
}
MutableLiveData<Nil> getShowDialogClicks() {
return showDialogClicks;
}
}
|
Fix <\textarea> in codeeditor breaks out of the editors textarea
|
@if ($this->previewMode)
<div class="form-control-static">{!! $value !!}</div>
@else
<div
class="field-codeeditor size-{{ $size }}"
data-control="code-editor"
data-mode="{{ $mode }}"
data-theme="{{ $theme }}"
data-line-separator="{{ $lineSeparator }}"
data-read-only="{{ $readOnly }}"
data-height="{{ $size == 'small' ? 250 : 520 }}"
>
<textarea
name="{{ $name }}"
id="{{ $this->getId('textarea') }}"
rows="20"
class="form-control"
>{{ trim($value) }}</textarea>
</div>
@endif
|
@if ($this->previewMode)
<div class="form-control-static">{!! $value !!}</div>
@else
<div
class="field-codeeditor size-{{ $size }}"
data-control="code-editor"
data-mode="{{ $mode }}"
data-theme="{{ $theme }}"
data-line-separator="{{ $lineSeparator }}"
data-read-only="{{ $readOnly }}"
data-height="{{ $size == 'small' ? 250 : 520 }}"
>
<textarea
name="{{ $name }}"
id="{{ $this->getId('textarea') }}"
rows="20"
class="form-control"
>{!! trim($value) !!}</textarea>
</div>
@endif
|
Fix commented out avatar in profile-cards-react-with-styles
|
/* eslint-disable react/prop-types */
import React from 'react';
import { Image, View, Text } from 'react-sketchapp';
import { css, withStyles } from '../withStyles';
const Profile = ({ user, styles }) => (
<View {...css(styles.container)}>
<Image source={user.profile_image_url} {...css(styles.avatar)} />
<View {...css(styles.titleWrapper)}>
<Text {...css(styles.title)}>{user.name}</Text>
<Text {...css(styles.subtitle)}>{`@${user.screen_name}`}</Text>
</View>
<Text {...css(styles.body)}>{user.description}</Text>
<Text {...css(styles.body)}>{user.location}</Text>
<Text {...css(styles.body)}>{user.url}</Text>
</View>
);
export default withStyles(({ colors, fonts, spacing }) => ({
container: {
backgroundColor: colors.Haus,
padding: spacing,
width: 260,
marginRight: spacing,
},
avatar: {
height: 220,
resizeMode: 'contain',
marginBottom: spacing * 2,
borderRadius: 10,
},
titleWrapper: {
marginBottom: spacing,
},
title: { ...fonts['Title 2'] },
subtitle: { ...fonts['Title 3'] },
body: { ...fonts.Body },
}))(Profile);
|
/* eslint-disable react/prop-types */
import React from 'react';
import { Image, View, Text } from 'react-sketchapp';
import { css, withStyles } from '../withStyles';
const Profile = ({ user, styles }) => (
<View {...css(styles.container)}>
{/* <Image source={user.profile_image_url} {...css(styles.avatar)} /> */}
<View {...css(styles.titleWrapper)}>
<Text {...css(styles.title)}>{user.name}</Text>
<Text {...css(styles.subtitle)}>{`@${user.screen_name}`}</Text>
</View>
<Text {...css(styles.body)}>{user.description}</Text>
<Text {...css(styles.body)}>{user.location}</Text>
<Text {...css(styles.body)}>{user.url}</Text>
</View>
);
export default withStyles(({ colors, fonts, spacing }) => ({
container: {
backgroundColor: colors.Haus,
padding: spacing,
width: 260,
marginRight: spacing,
},
avatar: {
height: 220,
resizeMode: 'contain',
marginBottom: spacing * 2,
borderRadius: 10,
},
titleWrapper: {
marginBottom: spacing,
},
title: { ...fonts['Title 2'] },
subtitle: { ...fonts['Title 3'] },
body: { ...fonts.Body },
}))(Profile);
|
Index of the list should be an int
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPairs(len(data_list), sample_size)
return tuple((data_list[int(k1)], data_list[int(k2)]) for k1, k2 in random_pairs)
def blockData(data_d, blocker):
blocks = dedupe.core.OrderedDict({})
record_blocks = dedupe.core.OrderedDict({})
key_blocks = dedupe.core.OrderedDict({})
blocker.tfIdfBlocks(data_d.iteritems())
for (record_id, record) in data_d.iteritems():
for key in blocker((record_id, record)):
blocks.setdefault(key, {}).update({record_id : record})
blocked_records = tuple(block for block in blocks.values())
return blocked_records
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPairs(len(data_list), sample_size)
return tuple((data_list[k1], data_list[k2]) for k1, k2 in random_pairs)
def blockData(data_d, blocker):
blocks = dedupe.core.OrderedDict({})
record_blocks = dedupe.core.OrderedDict({})
key_blocks = dedupe.core.OrderedDict({})
blocker.tfIdfBlocks(data_d.iteritems())
for (record_id, record) in data_d.iteritems():
for key in blocker((record_id, record)):
blocks.setdefault(key, {}).update({record_id : record})
blocked_records = tuple(block for block in blocks.values())
return blocked_records
|
[Tmpl] Add predefined type for temporary varibles.
|
package goutils
import (
"bytes"
"text/template"
"github.com/hoveychen/go-utils/gomap"
)
var (
textTmplCache = gomap.New()
)
type Var map[string]interface{}
func Sprintt(textTmpl string, data interface{}) string {
ret := textTmplCache.GetOrCreate(textTmpl, func() interface{} {
tpl, err := template.New("test").Parse(textTmpl)
if err != nil {
LogError(err)
return nil
}
return tpl
})
if ret == nil {
// Not valid text template.
return ""
}
tmpl := (ret).(*template.Template)
buf := &bytes.Buffer{}
err := tmpl.Execute(buf, data)
if err != nil {
LogError(err)
return ""
}
return buf.String()
}
|
package goutils
import (
"bytes"
"text/template"
"github.com/hoveychen/go-utils/gomap"
)
var (
textTmplCache = gomap.New()
)
func Sprintt(textTmpl string, data interface{}) string {
ret := textTmplCache.GetOrCreate(textTmpl, func() interface{} {
tpl, err := template.New("test").Parse(textTmpl)
if err != nil {
LogError(err)
return nil
}
return tpl
})
if ret == nil {
// Not valid text template.
return ""
}
tmpl := (ret).(*template.Template)
buf := &bytes.Buffer{}
err := tmpl.Execute(buf, data)
if err != nil {
LogError(err)
return ""
}
return buf.String()
}
|
Make elections URLs match less
|
from django.conf.urls import url
from elections import views
from elections.helpers import ElectionIDSwitcher
urlpatterns = [
url(
"^elections/$",
views.ElectionListView.as_view(),
name="election_list_view",
),
url(
"^elections/(?P<election>[^/]+)/$",
ElectionIDSwitcher(
election_view=views.ElectionView, ballot_view=views.BallotPaperView
),
name="election_view",
),
url(
r"^elections/(?P<election>[^/]+)/unlocked/",
views.UnlockedBallotsForElectionListView.as_view(),
name="constituencies-unlocked",
),
url(
r"^election/(?P<ballot_id>[^/]+)/lock/",
views.LockBallotView.as_view(),
name="constituency-lock",
),
url(
r"^elections/(?P<ballot_id>[^/]+).csv",
views.BallotPaperCSVView.as_view(),
name="ballot_paper_csv",
),
]
|
from django.conf.urls import url
from elections import views
from elections.helpers import ElectionIDSwitcher
urlpatterns = [
url(
"elections/$",
views.ElectionListView.as_view(),
name="election_list_view",
),
url(
"elections/(?P<election>[^/]+)/$",
ElectionIDSwitcher(
election_view=views.ElectionView, ballot_view=views.BallotPaperView
),
name="election_view",
),
url(
r"^elections/(?P<election>[^/]+)/unlocked/",
views.UnlockedBallotsForElectionListView.as_view(),
name="constituencies-unlocked",
),
url(
r"^election/(?P<ballot_id>[^/]+)/lock/",
views.LockBallotView.as_view(),
name="constituency-lock",
),
url(
r"^elections/(?P<ballot_id>[^/]+).csv",
views.BallotPaperCSVView.as_view(),
name="ballot_paper_csv",
),
]
|
Remove version number from Python shebang.
On special request from someone trying to purge python2.2 from code indexed
internally at Google.
git-svn-id: http://src.chromium.org/svn/trunk/src@7071 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 6b204b6013b516c1f312ac19097dcdc068f85b93
|
#!/usr/bin/python
# Copyright (c) 2006-2008 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.
import md5
"""64-bit fingerprint support for strings.
Usage:
from extern import FP
print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!')
"""
def UnsignedFingerPrint(str, encoding='utf-8'):
"""Generate a 64-bit fingerprint by taking the first half of the md5
of the string."""
hex128 = md5.new(str).hexdigest()
int64 = long(hex128[:16], 16)
return int64
def FingerPrint(str, encoding='utf-8'):
fp = UnsignedFingerPrint(str, encoding=encoding)
# interpret fingerprint as signed longs
if fp & 0x8000000000000000L:
fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1)
return fp
|
#!/usr/bin/python2.2
# Copyright (c) 2006-2008 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.
import md5
"""64-bit fingerprint support for strings.
Usage:
from extern import FP
print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!')
"""
def UnsignedFingerPrint(str, encoding='utf-8'):
"""Generate a 64-bit fingerprint by taking the first half of the md5
of the string."""
hex128 = md5.new(str).hexdigest()
int64 = long(hex128[:16], 16)
return int64
def FingerPrint(str, encoding='utf-8'):
fp = UnsignedFingerPrint(str, encoding=encoding)
# interpret fingerprint as signed longs
if fp & 0x8000000000000000L:
fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1)
return fp
|
Split Webpack build to main and vendor chunks
|
const webpack = require("webpack");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
module.exports = {
entry: "./src/index.ts",
resolve: {
extensions: [".tsx", ".ts", ".js"]
},
output: {
path: __dirname + "/dist",
filename: "[name]-[hash].js"
},
module: {
rules: [
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader"
}
]
},
{
test: /\.css$/,
use: [{ loader: "style-loader" }, { loader: "css-loader" }]
},
{
test: /\.(woff2?|ttf|eot|svg)$/,
loader: "url-loader"
}
]
},
optimization: {
splitChunks: {
chunks: "all"
}
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: "src/index.ejs",
filename: "index.html"
}),
new CopyWebpackPlugin([{ from: "src/images", to: "images" }])
]
};
|
const webpack = require("webpack");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
module.exports = {
entry: "./src/index.ts",
resolve: {
extensions: [".tsx", ".ts", ".js"]
},
output: {
path: __dirname + "/dist",
filename: "[name]-[hash].js"
},
module: {
rules: [
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader"
}
]
},
{
test: /\.css$/,
use: [{ loader: "style-loader" }, { loader: "css-loader" }]
},
{
test: /\.(woff2?|ttf|eot|svg)$/,
loader: "url-loader"
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: "src/index.ejs",
filename: "index.html",
inject: true,
hash: true
}),
new CopyWebpackPlugin([{ from: "src/images", to: "images" }])
]
};
|
Switch to use keyup, but only perform lookup on input change.
|
var BookLookup = { }
BookLookup.find_by_isbn = function(isbn, callback) {
$.getJSON('/books/isbn/'+ encodeURI(isbn), callback);
}
BookLookup.find_and_render = function(isbn) {
if (isbn == "") {
$('#book-placeholder').html('');
return;
}
$('#book-placeholder').addClass('loading').html('Searching for book...');
BookLookup.find_by_isbn(isbn, function(data){
output = Mustache.render($('#book-preview-template').html(), data);
$('#book-placeholder').removeClass('loading').html( output );
});
}
$(document).ready(function() {
var book_lookup_timeout;
var previous_query = '';
$('#new_book input[name=commit]').remove();
$('#book_isbn').keyup( function(e) {
var isbn = $('#book_isbn').val();
if (isbn !== previous_query) {
$('#book-placeholder').addClass('loading').html('Searching for book...');
clearTimeout(book_lookup_timeout);
book_lookup_timeout = setTimeout(function() {
previous_query = isbn;
BookLookup.find_and_render(isbn);
}, 500);
}
});
var isbn = $('#book_isbn').val();
if (isbn != '') {
BookLookup.find_and_render(isbn);
}
});
|
var BookLookup = { }
BookLookup.find_by_isbn = function(isbn, callback) {
$.getJSON('/books/isbn/'+ encodeURI(isbn), callback);
}
BookLookup.find_and_render = function(isbn) {
if (isbn == "") {
$('#book-placeholder').html('');
return;
}
$('#book-placeholder').addClass('loading').html('Searching for book...');
BookLookup.find_by_isbn(isbn, function(data){
output = Mustache.render($('#book-preview-template').html(), data);
$('#book-placeholder').removeClass('loading').html( output );
});
}
$(document).ready(function() {
var book_lookup_timeout;
$('#new_book input[name=commit]').remove();
$('#book_isbn').change( function(e) {
var isbn = $('#book_isbn').val();
$('#book-placeholder').addClass('loading').html('Searching for book...');
clearTimeout(book_lookup_timeout);
book_lookup_timeout = setTimeout(function() {
BookLookup.find_and_render(isbn);
}, 500);
});
var isbn = $('#book_isbn').val();
if (isbn != '') {
BookLookup.find_and_render(isbn);
}
});
|
Rename "marker" to "nextAvailableIndex" for better readability
* Initialize poolSize with 1 (doubling 0 is not smart :)
|
(function () {
'use strict';
function ObjectPoolMaker(Constructor, size) {
var objectPool = [],
nextAvailableIndex = 0,
poolSize = size || 1;
if (poolSize) {
expandPool(poolSize);
}
function expandPool(newSize) {
var i;
for (i = 0; i < newSize - poolSize; i++) {
objectPool.push(new Constructor());
}
poolSize = newSize;
}
return {
create: function () {
if (nextAvailableIndex >= poolSize) {
expandPool(poolSize * 2);
}
var obj = objectPool[nextAvailableIndex];
obj.index = nextAvailableIndex;
nextAvailableIndex += 1;
obj.constructor.apply(obj, arguments);
return obj;
},
destroy: function (obj) {
nextAvailableIndex -= 1;
var lastObj = objectPool[nextAvailableIndex],
lastObjIndex = lastObj.index;
objectPool[nextAvailableIndex] = obj;
objectPool[obj.index] = lastObj;
lastObj.index = obj.index;
obj.index = lastObjIndex;
}
};
}
// make ObjectPoolMaker available globally
window.ObjectPoolMaker = ObjectPoolMaker;
}());
|
(function () {
'use strict';
function ObjectPoolMaker(Constructor, size) {
var objectPool = [],
marker = 0,
poolSize = size || 0;
if (poolSize) {
expandPool(poolSize);
}
function expandPool(newSize) {
var i;
for (i = 0; i < newSize - poolSize; i++) {
objectPool.push(new Constructor());
}
poolSize = newSize;
}
return {
create: function () {
if (marker >= poolSize) {
expandPool(poolSize * 2);
}
var obj = objectPool[marker];
obj.index = marker;
marker += 1;
obj.constructor.apply(obj, arguments);
return obj;
},
destroy: function (obj) {
marker -= 1;
var lastObj = objectPool[marker],
lastObjIndex = lastObj.index;
objectPool[marker] = obj;
objectPool[obj.index] = lastObj;
lastObj.index = obj.index;
obj.index = lastObjIndex;
}
};
}
// make ObjectPoolMaker available globally
window.ObjectPoolMaker = ObjectPoolMaker;
}());
|
Update featured image Interchange queries
Removed 'default' named media query which
does not exist in Foundation 6.
http://foundation.zurb.com/sites/docs/interchange.html#named-media-queries
|
<?php
// If a feature image is set, get the id, so it can be injected as a css background property
if (has_post_thumbnail($post->ID) ) :
$feat_img_id = get_post_thumbnail_id();
$hero_img_alt = get_post_meta($feat_img_id, '_wp_attachment_image_alt', true); // get alt attribute
/* Use ID to get the attachment object */
$lg_hero_array = wp_get_attachment_image_src($feat_img_id, 'fp-large', true); // Large Hero
$md_hero_array = wp_get_attachment_image_src($feat_img_id, 'fp-medium', true); // Medium Hero
$sm_hero_array = wp_get_attachment_image_src($feat_img_id, 'fp-small', true); // Mobile Hero
/* Grab the url from the attachment object */
$hero_lg = $lg_hero_array[0]; // Large Hero
$hero_md = $md_hero_array[0]; // Medium Hero
$hero_sm = $sm_hero_array[0]; // Mobile Hero
?>
<header id="featured-hero" role="banner"
data-interchange="[<?php echo $hero_sm; ?>, small], [<?php echo $hero_md; ?>, medium], [<?php echo $hero_lg; ?>, large]">
</header>
<?php endif;
|
<?php
// If a feature image is set, get the id, so it can be injected as a css background property
if (has_post_thumbnail($post->ID) ) :
$feat_img_id = get_post_thumbnail_id();
$hero_img_alt = get_post_meta($feat_img_id, '_wp_attachment_image_alt', true); // get alt attribute
/* Use ID to get the attachment object */
$lg_hero_array = wp_get_attachment_image_src($feat_img_id, 'fp-large', true); // Large Hero
$md_hero_array = wp_get_attachment_image_src($feat_img_id, 'fp-medium', true); // Medium Hero
$sm_hero_array = wp_get_attachment_image_src($feat_img_id, 'fp-small', true); // Mobile Hero
/* Grab the url from the attachment object */
$hero_lg = $lg_hero_array[0]; // Large Hero
$hero_md = $md_hero_array[0]; // Medium Hero
$hero_sm = $sm_hero_array[0]; // Mobile Hero
?>
<header id="featured-hero" role="banner"
data-interchange="[<?php echo $hero_lg; ?>, default], [<?php echo $hero_sm; ?>, small], [<?php echo $hero_md; ?>, medium], [<?php echo $hero_lg; ?>, large]">
</header>
<?php endif;
|
Add missing return value type hint
|
from typing import Any, Callable, Dict, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]) -> None:
field_schema.update(type="string", format="binary")
|
from typing import Any, Callable, Dict, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]):
field_schema.update(type="string", format="binary")
|
Add a dependency that got dropped.
|
"""Setup data for aib2ofx."""
from setuptools import setup
setup(
name='aib2ofx',
description='Download data from aib.ie in OFX format',
version='0.6',
author='Jakub Turski',
author_email='yacoob@gmail.com',
url='http://github.com/yacoob/aib2ofx',
packages=['aib2ofx'],
entry_points={
'console_scripts': ['aib2ofx = aib2ofx.main:main'],
},
dependency_links=[
'git+https://github.com/MechanicalSoup/MechanicalSoup'
'#egg=mechanicalsoup --process-dependency-links'
],
install_requires=[
'mechanicalsoup',
'python-dateutil',
],
)
|
"""Setup data for aib2ofx."""
from setuptools import setup
setup(
name='aib2ofx',
description='Download data from aib.ie in OFX format',
version='0.6',
author='Jakub Turski',
author_email='yacoob@gmail.com',
url='http://github.com/yacoob/aib2ofx',
packages=['aib2ofx'],
entry_points={
'console_scripts': ['aib2ofx = aib2ofx.main:main'],
},
dependency_links=[
'git+https://github.com/MechanicalSoup/MechanicalSoup'
'#egg=mechanicalsoup --process-dependency-links'
],
install_requires=[
'mechanicalsoup',
],
)
|
[PhpUnitBridge] Enforce @-silencing of deprecation notices according to new policy
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Yaml\Tests;
use Symfony\Component\Yaml\Yaml;
class YamlTest extends \PHPUnit_Framework_TestCase
{
public function testParseAndDump()
{
$data = array('lorem' => 'ipsum', 'dolor' => 'sit');
$yml = Yaml::dump($data);
$parsed = Yaml::parse($yml);
$this->assertEquals($data, $parsed);
}
/**
* @group legacy
*/
public function testLegacyParseFromFile()
{
$filename = __DIR__.'/Fixtures/index.yml';
$contents = file_get_contents($filename);
$parsedByFilename = Yaml::parse($filename);
$parsedByContents = Yaml::parse($contents);
$this->assertEquals($parsedByFilename, $parsedByContents);
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Yaml\Tests;
use Symfony\Component\Yaml\Yaml;
class YamlTest extends \PHPUnit_Framework_TestCase
{
public function testParseAndDump()
{
$data = array('lorem' => 'ipsum', 'dolor' => 'sit');
$yml = Yaml::dump($data);
$parsed = Yaml::parse($yml);
$this->assertEquals($data, $parsed);
}
/**
* @group legacy
*/
public function testLegacyParseFromFile()
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$filename = __DIR__.'/Fixtures/index.yml';
$contents = file_get_contents($filename);
$parsedByFilename = Yaml::parse($filename);
$parsedByContents = Yaml::parse($contents);
$this->assertEquals($parsedByFilename, $parsedByContents);
}
}
|
Remove todo on lissu php ajax call. It returns and empty array in case of problems
|
sites_to_check = [
{
"name": "Lissu Monitor",
"url": "http://lissu.tampere.fi/monitor.php?stop=0014",
"acceptable_statuses": [200],
"mandatory_strings": [
"table2"
]
},
{
"name": "Siri API",
"url": "https://siri.ij2010.tampere.fi/ws",
"acceptable_statuses": [401],
"mandatory_strings": [
"Full authentication is required to access this resource",
"Apache Tomcat"
]
}
]
|
sites_to_check = [
{
"name": "Lissu Monitor",
"url": "http://lissu.tampere.fi/monitor.php?stop=0014",
"acceptable_statuses": [200],
"mandatory_strings": [
"table2"
]
},
{
"name": "Siri API",
"url": "https://siri.ij2010.tampere.fi/ws",
"acceptable_statuses": [401],
"mandatory_strings": [
"Full authentication is required to access this resource",
"Apache Tomcat"
]
}
# TODO Next time when api is down, check below url:
# http://lissu.tampere.fi/ajax_servers/busLocations.php
]
|
Revert previous commit adding storage methods
git-svn-id: 522c0d53943162a6437d919c1900af0a20491c0c@962477 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.amber.server;
/**
* An OAuth Server provides the functionality required to deliver OAuth Provider
* functionality. It can be exposed by wrapping it in an HTTP layer, e.g. that
* provided by the Servlet Spec or perhaps directly exposed by a custom HTTP
* server.
*
* @version $Id$
*/
public abstract class OAuthServer implements OAuthnServer, OAuthzServer {
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.amber.server;
/**
* An OAuth Server provides the functionality required to deliver OAuth Provider
* functionality. It can be exposed by wrapping it in an HTTP layer, e.g. that
* provided by the Servlet Spec or perhaps directly exposed by a custom HTTP
* server.
*
* @version $Id$
*/
public abstract class OAuthServer implements OAuthnServer, OAuthzServer {
/**
* @return access storage
*/
protected abstract AccessStorage getAccessStorage();
/**
* @return consumer storage
*/
protected abstract ConsumerStorage getConsumerStorage();
/**
* @return token storage
*/
protected abstract TokenStorage getTokenStorage();
}
|
Enable markdown for PyPI README
|
import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='gis_metadata_parser',
description='Parser for GIS metadata standards including FGDC and ISO-19115',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser',
version='1.1.3',
packages=[
'gis_metadata', 'gis_metadata.tests'
],
install_requires=[
'parserutils>=1.1', 'six>=1.9.0'
],
url='https://github.com/consbio/gis-metadata-parser',
license='BSD',
cmdclass={'test': RunTests}
)
|
import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='gis_metadata_parser',
description='Parser for GIS metadata standards including FGDC and ISO-19115',
long_description=long_description,
keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser',
version='1.1.2',
packages=[
'gis_metadata', 'gis_metadata.tests'
],
install_requires=[
'parserutils>=1.1', 'six>=1.9.0'
],
url='https://github.com/consbio/gis-metadata-parser',
license='BSD',
cmdclass={'test': RunTests}
)
|
Support for a LOT of tests
|
var stresstest = require('stresstest');
var timeouttest = require('timeouttest');
var win = Ti.UI.createWindow({});
var list = Ti.UI.createScrollView({
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
layout: 'vertical'
});
win.add(list);
[
{
title: 'Execute Stress Test',
handle: stresstest
},
{
title: 'Timeout test',
handle: timeouttest
}
].forEach(function (action) {
var button = Ti.UI.createButton({
title: action.title
});
var running = false;
button.addEventListener('click', function () {
running = true;
button.enabled = false;
button.disabled = true;
action.handle(function (err) {
running = false;
button.enabled = true;
button.disabled = false;
if (err) {
throw err;
}
else {
alert('Done');
}
});
});
list.add(button);
});
win.open();
|
var stresstest = require('stresstest');
var timeouttest = require('timeouttest');
var win = Ti.UI.createWindow({});
var list = Ti.UI.createView({
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
layout: 'vertical'
});
win.add(list);
[
{
title: 'Execute Stress Test',
handle: stresstest
},
{
title: 'Timeout test',
handle: timeouttest
}
].forEach(function (action) {
var button = Ti.UI.createButton({
title: action.title
});
var running = false;
button.addEventListener('click', function () {
running = true;
button.enabled = false;
button.disabled = true;
action.handle(function (err) {
running = false;
button.enabled = true;
button.disabled = false;
if (err) {
throw err;
}
else {
alert('Done');
}
});
});
list.add(button);
});
win.open();
|
Add browserSync notification upon compilation step
|
var _ = require('lodash');
var browserSync = require('browser-sync');
function BrowserSyncPlugin(browserSyncOptions, options) {
var self = this;
var defaultOptions = {
reload: true,
name: 'bs-webpack-plugin',
callback: undefined
};
self.browserSyncOptions = _.extend({}, browserSyncOptions);
self.options = _.extend({}, defaultOptions, options);
self.browserSync = browserSync.create(self.options.name);
self.webpackIsWatching = false;
self.browserSyncIsRunning = false;
}
BrowserSyncPlugin.prototype.apply = function (compiler) {
var self = this;
compiler.plugin('watch-run', function (watching, callback) {
self.webpackIsWatching = true;
callback(null, null);
});
compiler.plugin('compilation', function () {
self.browserSync.notify('Rebuilding');
});
compiler.plugin('done', function (stats) {
if (self.webpackIsWatching) {
if (self.browserSyncIsRunning) {
if (self.options.reload) {
self.browserSync.reload();
}
} else {
if (_.isFunction(self.options.callback)) {
self.browserSync.init(self.browserSyncOptions, self.options.callback);
} else {
self.browserSync.init(self.browserSyncOptions);
}
self.browserSyncIsRunning = true;
}
}
});
};
module.exports = BrowserSyncPlugin;
|
var _ = require('lodash');
var browserSync = require('browser-sync');
function BrowserSyncPlugin(browserSyncOptions, options) {
var self = this;
var defaultOptions = {
reload: true,
name: 'bs-webpack-plugin',
callback: undefined
};
self.browserSyncOptions = _.extend({}, browserSyncOptions);
self.options = _.extend({}, defaultOptions, options);
self.browserSync = browserSync.create(self.options.name);
self.webpackIsWatching = false;
self.browserSyncIsRunning = false;
}
BrowserSyncPlugin.prototype.apply = function (compiler) {
var self = this;
compiler.plugin('watch-run', function (watching, callback) {
self.webpackIsWatching = true;
callback(null, null);
});
compiler.plugin('done', function (stats) {
if (self.webpackIsWatching) {
if (self.browserSyncIsRunning) {
if (self.options.reload) {
self.browserSync.reload();
}
} else {
if (_.isFunction(self.options.callback)) {
self.browserSync.init(self.browserSyncOptions, self.options.callback);
} else {
self.browserSync.init(self.browserSyncOptions);
}
self.browserSyncIsRunning = true;
}
}
});
};
module.exports = BrowserSyncPlugin;
|
Add a dataprovider for tab completion test
Add a couple more complicated `new` invocations.
|
<?php
namespace Psy\Test\Readline;
use Psy\Readline\TabCompletion;
use Psy\Context;
class TabCompletionTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider classesInput
*/
public function testClassesCompletion($word, $index, $line, $point, $end, $expect)
{
$context = new Context();
$tabCompletion = new TabCompletion($context);
$code = $tabCompletion->processCallback($word, $index, array(
'line_buffer' => $line,
'point' => $point,
'end' => $end,
));
$this->assertContains($expect, $code);
}
public function classesInput()
{
return array(
array('stdC', 4, 'new stdC', 7, 7, 'stdClass()'),
array('stdC', 5, 'new \stdC', 8, 8, 'stdClass()'),
array('stdC', 5, '(new stdC', 8, 8, 'stdClass()'),
array('s', 7, 'new \a\\s', 8, 8, 'stdClass()'),
);
}
}
|
<?php
namespace Psy\Test\Readline;
use Psy\Readline\TabCompletion;
use Psy\Context;
/**
* Class TabCompletionTest
* @package Psy\Test\Readline
*/
class TabCompletionTest extends \PHPUnit_Framework_TestCase
{
public function testClassesCompletion()
{
class_alias('\Psy\Test\Readline\TabCompletionTest', 'Foo');
$context = new Context();
$tabCompletion = new TabCompletion($context);
$code = $tabCompletion->processCallback('stdC', 4, array(
"line_buffer" => "new stdC",
"point" => 7,
"end" => 7,
));
$this->assertContains('stdClass()', $code);
}
}
|
Allow dynamic event handlers to throw checked exceptions
|
/*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.event;
/**
* Represents a handler accepting events of a specified type.
*
* @param <T> The type of the event
*/
public interface EventHandler<T extends Event> {
/**
* Called when a event registered to this handler is called.
*
* @param event The called event
* @throws Exception If an error occurs
*/
void handle(T event) throws Exception;
}
|
/*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.event;
/**
* Represents a handler accepting events of a specified type.
*
* @param <T> The type of the event
*/
public interface EventHandler<T extends Event> {
/**
* Called when a event registered to this handler is called.
*
* @param event The called event
*/
void handle(T event);
}
|
Remove test for sessions for Coursera API
|
import unittest
from mooc_aggregator_restful_api import coursera
class CourseraTestCase(unittest.TestCase):
'''
Unit Tests for module udacity
'''
def setUp(self):
self.coursera_test_object = coursera.CourseraAPI()
def test_coursera_api_courses_response(self):
self.assertEqual(self.coursera_test_object.response_courses.status_code, 200)
def test_coursera_api_universities_response(self):
self.assertEqual(self.coursera_test_object.response_universities.status_code, 200)
def test_coursera_api_categories_response(self):
self.assertEqual(self.coursera_test_object.response_categories.status_code, 200)
def test_coursera_api_instructors_response(self):
self.assertEqual(self.coursera_test_object.response_instructors.status_code, 200)
def test_coursera_api_mongofy_courses(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
|
import unittest
from mooc_aggregator_restful_api import coursera
class CourseraTestCase(unittest.TestCase):
'''
Unit Tests for module udacity
'''
def setUp(self):
self.coursera_test_object = coursera.CourseraAPI()
def test_coursera_api_courses_response(self):
self.assertEqual(self.coursera_test_object.response_courses.status_code, 200)
def test_coursera_api_universities_response(self):
self.assertEqual(self.coursera_test_object.response_universities.status_code, 200)
def test_coursera_api_categories_response(self):
self.assertEqual(self.coursera_test_object.response_categories.status_code, 200)
def test_coursera_api_instructors_response(self):
self.assertEqual(self.coursera_test_object.response_instructors.status_code, 200)
def test_coursera_api_sessions_response(self):
self.assertEqual(self.coursera_test_object.response_sessions.status_code, 200)
def test_coursera_api_mongofy_courses(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
|
Disable Python 3 conversion until it's been tested.
|
import sys
from setuptools import setup
meta = dict(
name="stacklogger",
version="0.1.0",
description="A stack-aware logging extension",
author="Will Maier",
author_email="willmaier@ml1.net",
py_modules=["stacklogger"],
test_suite="tests.py",
install_requires=["setuptools"],
keywords="logging stack frame",
url="http://packages.python.org/stacklogger",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Programming Language :: Python"
"Topic :: System :: Logging",
],
)
# Automatic conversion for Python 3 requires distribute.
if False and sys.version_info >= (3,):
meta.update(dict(
use_2to3=True,
))
setup(**meta)
|
import sys
from setuptools import setup
meta = dict(
name="stacklogger",
version="0.1.0",
description="A stack-aware logging extension",
author="Will Maier",
author_email="willmaier@ml1.net",
py_modules=["stacklogger"],
test_suite="tests.py",
install_requires=["setuptools"],
keywords="logging stack frame",
url="http://packages.python.org/stacklogger",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Programming Language :: Python"
"Topic :: System :: Logging",
],
)
# Automatic conversion for Python 3 requires distribute.
if sys.version_info >= (3,):
meta.update(dict(
use_2to3=True,
))
setup(**meta)
|
Make password not to show in status bar
|
<?php if(!isset($conn)) die; ?><header>
<h1>Super-Simple-Vunlerable-Guestbook</h1>
<ul class="nav">
<?php
function protect($url, $pwd) {
return "javascript:(/********************************************************************************/prompt('Password') == '{$pwd}') && (location.href = '{$url}') || void(0);";
}
$navs = [
[ 'Home', './'],
[ 'New Post', './?mod=new' ],
[ 'Hack', protect('./?mod=hack', 'h@ckme') ],
[ 'Hash', './?mod=hash' ],
];
foreach ($navs as $item)
echo "<li><a href=\"{$item[1]}\">{$item[0]}</a></li>";
?>
</ul>
</header>
|
<?php if(!isset($conn)) die; ?><header>
<h1>Super-Simple-Vunlerable-Guestbook</h1>
<ul class="nav">
<?php
function protect($url, $pwd) {
return "javascript:(prompt('Password') == '{$pwd}') && (location.href = '{$url}') || void(0);";
}
$navs = [
[ 'Home', './'],
[ 'New Post', './?mod=new' ],
[ 'Hack', protect('./?mod=hack', 'h@ckme') ],
[ 'Hash', './?mod=hash' ],
];
foreach ($navs as $item)
echo "<li><a href=\"{$item[1]}\">{$item[0]}</a></li>";
?>
</ul>
</header>
|
Remove old method of adding datafiles.
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup
setup(name='pynxc',
version='0.1.7',
description='A Python to NXC Converter for programming '
'LEGO MINDSTORMS Robots',
author='Brian Blais',
author_email='bblais@bryant.edu',
maintainer='Marek Šuppa',
maintainer_email='marek@suppa.sk',
url='https://github.com/xlcteam/pynxc',
packages=['pynxc'],
data_files=[('tests', ['pynxc/tests/tests.py']),
('', ['pynxc/defs.h'])],
entry_points = {
'console_scripts': [
'pynxc = pynxc:main'
]
}
)
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup
setup(name='pynxc',
version='0.1.7',
description='A Python to NXC Converter for programming '
'LEGO MINDSTORMS Robots',
author='Brian Blais',
author_email='bblais@bryant.edu',
maintainer='Marek Šuppa',
maintainer_email='marek@suppa.sk',
url='https://github.com/xlcteam/pynxc',
packages=['pynxc'],
#include_package_data=True,
data_files=[('tests', ['pynxc/tests/tests.py']),
('', ['pynxc/defs.h'])],
entry_points = {
'console_scripts': [
'pynxc = pynxc:main'
]
}
)
|
Use fix module names to abstract from account base controller.
|
<?php
namespace account\base;
use Yii;
class Controller extends \luya\web\Controller
{
public function getRules()
{
return [
[
'allow' => true,
'actions' => [], // apply to all actions by default
'roles' => ['@'],
],
];
}
public function behaviors()
{
return [
'access' => [
'class' => \yii\filters\AccessControl::className(),
'user' => Yii::$app->getModule('account')->getUserIdentity(),
'rules' => $this->getRules(),
],
];
}
public function isGuest()
{
return Yii::$app->getModule('account')->getUserIdentity()->isGuest;
}
}
|
<?php
namespace account\base;
class Controller extends \luya\web\Controller
{
public function getRules()
{
return [
[
'allow' => true,
'actions' => [], // apply to all actions by default
'roles' => ['@'],
],
];
}
public function behaviors()
{
return [
'access' => [
'class' => \yii\filters\AccessControl::className(),
'user' => $this->module->getUserIdentity(),
'rules' => $this->getRules(),
],
];
}
public function isGuest()
{
return $this->module->getUserIdentity()->isGuest;
}
}
|
Add due and change names of boilerplates
Close #58
|
import React from 'react';
import {Decorator as Cerebral} from 'cerebral-view-react';
import styles from './styles.css';
const boilerplates = {
'react': 'React',
'cerebral': 'Cerebral',
'redux': 'Redux',
'cycle': 'Cycle JS',
'vue': 'Vue JS'
};
@Cerebral()
class Boilerplates extends React.Component {
render() {
return (
<div className={styles.wrapper}>
{Object.keys(boilerplates).map((key, index) => {
return (
<div
className={styles.boilerplate}
key={index}
onClick={() => this.props.signals.bin.boilerplateClicked({name: key})}>
{boilerplates[key]}
</div>
);
})}
</div>
);
}
}
export default Boilerplates;
|
import React from 'react';
import {Decorator as Cerebral} from 'cerebral-view-react';
import styles from './styles.css';
const boilerplates = {
'react': 'React',
'cerebral': 'Cerebral with React',
'redux': 'Redux Counter',
'cycle': 'Cycle JS'
};
@Cerebral()
class Boilerplates extends React.Component {
render() {
return (
<div className={styles.wrapper}>
{Object.keys(boilerplates).map((key, index) => {
return (
<div
className={styles.boilerplate}
key={index}
onClick={() => this.props.signals.bin.boilerplateClicked({name: key})}>
{boilerplates[key]}
</div>
);
})}
</div>
);
}
}
export default Boilerplates;
|
Initialize seq without type in take test class
|
package com.jmonad.seq;
import org.junit.Test;
public class SeqTakeTest {
private Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
private Seq<Integer> elements = new Seq<>(numbers);
@Test public void takeListElementsTest() {
assert elements.take(5).toArrayList().toString().equals("[1, 2, 3, 4, 5]");
}
@Test public void takeElementsWithNoAmountTest() {
assert elements.take(0).toArrayList().toString().equals("[]");
}
@Test public void takeElementsWithNegativeAmountTest() {
assert elements.take(-1).toArrayList().toString().equals("[]");
}
@Test public void takeElementsWithAmountHigherThanListSizeTest() {
assert elements.take(20).toArrayList().toString().equals("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]");
}
}
|
package com.jmonad.seq;
import org.junit.Test;
public class SeqTakeTest {
private Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
private Seq<Integer> elements = new Seq<Integer>(numbers);
@Test public void takeListElementsTest() {
assert elements.take(5).toArrayList().toString().equals("[1, 2, 3, 4, 5]");
}
@Test public void takeElementsWithNoAmountTest() {
assert elements.take(0).toArrayList().toString().equals("[]");
}
@Test public void takeElementsWithNegativeAmountTest() {
assert elements.take(-1).toArrayList().toString().equals("[]");
}
@Test public void takeElementsWithAmountHigherThanListSizeTest() {
assert elements.take(20).toArrayList().toString().equals("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]");
}
}
|
Add explanatory and TODO notes
|
'use strict';
var request = require('request');
var opts = {
uri: 'https://api.github.com' + '/users/' + parseParams(process.argv[2]) + '/events',
json: true,
method: 'GET',
headers: {
'User-Agent': 'nodejs script'
}
}
request(opts, function (err, res, body) {
if (err) throw new Error(err);
var format = '[%s]: %s %s %s %s';
for (var i = 0; i < body.length; i++) {
/*
* TODO return something like this as JSON
* for caller consumption (useful for servers).
*/
console.log(format
, body[i].created_at
, body[i].type
, body[i].actor.login
, body[i].repo.name);
}
});
/*
* Verify param is present, and just return it.
* TODO
* Check for multiple params, and check validity
* as well as presence.
*/
function parseParams(params) {
if (! params) {
console.log('Usage: nodejs gevents.js <user-name>');
process.exit(0);
}
return params;
}
|
'use strict';
var request = require('request');
var opts = {
uri: 'https://api.github.com' + '/users/' + parseParams(process.argv[2]) + '/events',
json: true,
method: 'GET',
headers: {
'User-Agent': 'nodejs script'
}
}
request(opts, function (err, res, body) {
if (err) throw new Error(err);
var format = '[%s]: %s %s %s %s';
for (var i = 0; i < body.length; i++) {
/*
* TODO return something like this as JSON
* for caller consumption (useful for servers).
*/
console.log(format
, body[i].created_at
, body[i].type
, body[i].actor.login
, body[i].repo.name);
}
});
function parseParams(params) {
if (! params) {
console.log('Usage: nodejs gevents.js <user-name>');
process.exit(0);
}
return params;
}
|
[TACHYON-1559] Update doc to reference method directly and defend against IDE refactors
|
/*
* Licensed to the University of California, Berkeley under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package tachyon.client;
import org.junit.Test;
import org.junit.Assert;
/**
* Tests {@link ClientUtils}.
*/
public final class ClientUtilsTest {
/**
* Tests if output of {@link ClientUtils#getRandomNonNegativeLong()} is non-negative.
*/
@Test
public void getRandomNonNegativeLongTest() throws Exception {
Assert.assertTrue(ClientUtils.getRandomNonNegativeLong() > 0);
}
}
|
/*
* Licensed to the University of California, Berkeley under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package tachyon.client;
import org.junit.Test;
import org.junit.Assert;
/**
* Tests {@link ClientUtils}.
*/
public final class ClientUtilsTest {
/**
* Tests if output of getRandomNonNegativeLong from {@link ClientUtils} is non-negative.
*/
@Test
public void getRandomNonNegativeLongTest() throws Exception {
Assert.assertTrue(ClientUtils.getRandomNonNegativeLong() > 0);
}
}
|
Make done a top-level function rather than a nested one.
|
#!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, port
class Options(usage.Options):
optParameters = [
["host", "h", "localhost", "server hostname"],
["port", "p", port, "server port"],
]
def done(result):
print 'Got roll:', result
reactor.stop()
def roll_die(host, port):
clientcreator = ClientCreator(reactor, amp.AMP)
d1 = clientcreator.connectTCP(host, port)
d1.addCallback(lambda p: p.callRemote(RollDice, sides=6))
d1.addCallback(lambda result: result['result'])
d1.addCallback(done)
d1.addErrback(failure)
def failure(error):
print "failed", str(error)
reactor.stop()
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
host = options["host"]
port = int(options["port"])
roll_die(host, port)
reactor.run()
|
#!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, port
class Options(usage.Options):
optParameters = [
["host", "h", "localhost", "server hostname"],
["port", "p", port, "server port"],
]
def roll_die(host, port):
clientcreator = ClientCreator(reactor, amp.AMP)
d1 = clientcreator.connectTCP(host, port)
d1.addCallback(lambda p: p.callRemote(RollDice, sides=6))
d1.addCallback(lambda result: result['result'])
def done(result):
print 'Got roll:', result
reactor.stop()
d1.addCallback(done)
d1.addErrback(failure)
def failure(error):
print "failed", str(error)
reactor.stop()
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
host = options["host"]
port = int(options["port"])
roll_die(host, port)
reactor.run()
|
Fix unit tests for arg_parser
|
import unittest
from tailorscad.arg_parser import parse_args
class TestArgParser(unittest.TestCase):
def test_parse_args_none(self):
args = []
argv = []
args = parse_args(argv)
self.assertFalse(args.config)
def test_parse_args_inknown(self):
args = []
argv = ['-a', 'word']
args = parse_args(argv)
self.assertFalse(args.config)
def test_parse_args_known(self):
args = []
argv = ['-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args.config, 'test')
def test_parse_args_unkown_and_known(self):
args = []
argv = ['-a', 'word', '-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args.config, 'test')
|
import unittest
from tailorscad.arg_parser import parse_args
class TestArgParser(unittest.TestCase):
def test_parse_args_none(self):
args = []
argv = []
args = parse_args(argv)
self.assertFalse(args)
def test_parse_args_inknown(self):
args = []
argv = ['-a', 'word']
args = parse_args(argv)
self.assertFalse(args)
def test_parse_args_known(self):
args = []
argv = ['-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args, ['test'])
def test_parse_args_unkown_and_known(self):
args = []
argv = ['-a', 'word', '-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args, ['test'])
|
Change the update method for receive the layout attribute
|
<?php
/**
*Base class to persist data
*
*@author Vinicius Pinheiro <viny-pinheiro@hotmail.com>
*@license MIT License
*@link http://eletronjun.com.br/controller/updateCategory.php
*/
require_once __DIR__ . "/../class/autoload.php";
use \model\Category as Category;
use \dao\CategoryDAO as CategoryDAO;
use \exception\CategoryException as CategoryException;
use \exception\DatabaseException as DatabaseException;
use \utilities\Session as Session;
$session = new Session();
$session->verifyIfSessionIsStarted();
try {
$category = new Category($_GET['name'], $_GET['id']);
$category_dao = new CategoryDAO($category);
$category_dao->update($_GET['new_name'], $_GET['new_layout']);
echo "Atualizado com sucesso!";
} catch (Exception $msg) {
echo $msg;
}
|
<?php
/**
*Base class to persist data
*
*@author Vinicius Pinheiro <viny-pinheiro@hotmail.com>
*@license MIT License
*@link http://eletronjun.com.br/controller/updateCategory.php
*/
require_once __DIR__ . "/../class/autoload.php";
use \model\Category as Category;
use \dao\CategoryDAO as CategoryDAO;
use \exception\CategoryException as CategoryException;
use \exception\DatabaseException as DatabaseException;
use \utilities\Session as Session;
$session = new Session();
$session->verifyIfSessionIsStarted();
try {
$category = new Category($_GET['name'], $_GET['id']);
$category_dao = new CategoryDAO($category);
$category_dao->update($_GET['new_name']);
echo "Atualizado com sucesso!";
} catch (Exception $msg) {
echo $msg;
}
|
Update component name after rebase
|
import Vue from "vue/dist/vue.esm";
import VueRouter from 'vue-router';
Vue.use(VueRouter);
Vue.config.productionTip = process.env.NODE_ENV == "development";
import store from "../store/index";
import "../config/axios";
import "../directives/selectionchange";
import contenteditableDirective from "vue-contenteditable-directive";
Vue.use(contenteditableDirective);
import TheResource from "../components/TheResource";
document.addEventListener("DOMContentLoaded", () => {
const routes = [
{ path: '/casebooks/:id/resources/:resource_id/', component: TheResource }
];
const router = new VueRouter({
routes
});
const app = new Vue({
el: "#app",
store,
router,
components: {
TheResource
}
});
window.app = app;
});
|
import Vue from "vue/dist/vue.esm";
import VueRouter from 'vue-router';
Vue.use(VueRouter);
Vue.config.productionTip = process.env.NODE_ENV == "development";
import store from "../store/index";
import "../config/axios";
import "../directives/selectionchange";
import contenteditableDirective from "vue-contenteditable-directive";
Vue.use(contenteditableDirective);
import TheResource from "../components/TheResource";
document.addEventListener("DOMContentLoaded", () => {
const routes = [
{ path: '/casebooks/:id/resources/:resource_id/', component: TheResourceBody}
];
const router = new VueRouter({
routes
});
const app = new Vue({
el: "#app",
store,
router,
components: {
TheResource
}
});
window.app = app;
});
|
Fix electron file to der-reader dist
|
'use strict';
var webspeechapi, vibrateWebApi, DerReader;
const env = require('./env/env.json').env;
if (env === 'dev') {
webspeechapi = require('../modules/tts.webapi/tts.webapi.js');
vibrateWebApi = require('../modules/vibrate.webapi/vibrate.webapi.js');
DerReader = require('../modules/der-reader/dist/der-reader.js');
} else {
webspeechapi = require('tts.webapi');
vibrateWebApi = require('vibrate.webapi');
DerReader = require('der-reader');
}
var remote = require('electron').remote;
window.nodeRequire = require;
delete window.require;
delete window.exports;
delete window.module;
function exit() {
var window = remote.getCurrentWindow();
window.close();
}
DerReader.init({
container: 'der-reader',
derFile: null,
tts: webspeechapi,
vibrate: vibrateWebApi,
defaultMode: 0,
format: 'A3',
exit: exit
});
window.app = {
env: env,
version: process.env.npm_package_version
};
|
'use strict';
var webspeechapi, vibrateWebApi, DerReader;
const env = require('./env/env.json').env;
if (env === 'dev') {
webspeechapi = require('./../modules/tts.webapi/tts.webapi.js');
vibrateWebApi = require('./../modules/vibrate.webapi/vibrate.webapi.js');
DerReader = require('./../modules/der-reader/der-reader.js');
} else {
webspeechapi = require('tts.webapi');
vibrateWebApi = require('vibrate.webapi');
DerReader = require('der-reader');
}
var remote = require('electron').remote;
window.nodeRequire = require;
delete window.require;
delete window.exports;
delete window.module;
function exit() {
var window = remote.getCurrentWindow();
window.close();
}
DerReader.init({
container: 'der-reader',
derFile: null,
tts: webspeechapi,
vibrate: vibrateWebApi,
defaultMode: 0,
format: 'A3',
exit: exit
});
window.app = {
env: env,
version: process.env.npm_package_version
};
|
Add conf arg to check function
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from collections import Counter
import math
__author__ = "Austin West"
__license__ = "MPL 2.0"
TYPE = "Metadata"
NAME = "entropy"
def check(conf=DEFAULTCONF):
return True
def scan(filelist):
'''Calculate entropy of a string'''
results = []
for fname in filelist:
with open(fname, 'rb') as f:
text = f.read()
chars, lns = Counter(text), float(len(text))
result = -sum(count/lns * math.log(count/lns, 2) for count in chars.values())
results.append((fname, result))
metadata = {}
metadata["Name"] = NAME
metadata["Type"] = TYPE
metadata["Include"] = False
return (results, metadata)
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from collections import Counter
import math
__author__ = "Austin West"
__license__ = "MPL 2.0"
TYPE = "Metadata"
NAME = "entropy"
def check():
return True
def scan(filelist):
'''Calculate entropy of a string'''
results = []
for fname in filelist:
with open(fname, 'rb') as f:
text = f.read()
chars, lns = Counter(text), float(len(text))
result = -sum(count/lns * math.log(count/lns, 2) for count in chars.values())
results.append((fname, result))
metadata = {}
metadata["Name"] = NAME
metadata["Type"] = TYPE
metadata["Include"] = False
return (results, metadata)
|
Add a todo in the file.
|
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.util.*;
import machine.learning.ARL;
public class Programme {
//TODO fixe the exemple in java
public static void main(String[] args) throws FileNotFoundException {
ArrayList array = new ArrayList<Double>();
Scanner lineReader = new Scanner(new File("data/EURUSD.dat"));
while(lineReader.hasNext()){
String line = lineReader.nextLine();
String[] tmp = line.split("/")[0].split(" ");
array.add(Double.parseDouble(tmp[tmp.length - 1]));
}
ARL arl = new ARL(13);
// arl.loop(array.subList(200000,260000), 1000);
// arl.loop(array.subList(260000,270000), 1000);
System.out.println(arl.toString());
}
}
|
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.util.*;
import machine.learning.ARL;
public class Programme {
public static void main(String[] args) throws FileNotFoundException {
ArrayList array = new ArrayList<Double>();
Scanner lineReader = new Scanner(new File("data/EURUSD.dat"));
while(lineReader.hasNext()){
String line = lineReader.nextLine();
String[] tmp = line.split("/")[0].split(" ");
array.add(Double.parseDouble(tmp[tmp.length - 1]));
}
ARL arl = new ARL(13);
// arl.loop(array.subList(200000,260000), 1000);
// arl.loop(array.subList(260000,270000), 1000);
System.out.println(arl.toString());
}
}
|
Use the reset adder from the banks properly
|
import importlib
import os
import sys
import unittest
import code
import struct
code_path = os.path.dirname(__file__)
code_path = os.path.join(code_path, os.pardir)
sys.path.append(code_path)
import MOS6502
class TestCartHeaderParsing(unittest.TestCase):
def testMagic(self):
cpu = MOS6502.CPU()
cpu.loadRom("../smb1.nes")
self.assertEqual(cpu.rom != None, True)
def testRomBanks(self):
cpu = MOS6502.CPU()
cpu.loadRom("../smb1.nes")
self.assertEqual(cpu.rom.numRomBanks, 2)
self.assertEqual(cpu.rom.numVromBanks, 1)
startAddr = cpu.ReadMemWord(cpu.reset)
firstByte = cpu.ReadMemory(startAddr)
self.assertEqual(firstByte, 0x78)
if __name__ == '__main__':
unittest.main()
|
import importlib
import os
import sys
import unittest
import code
import struct
code_path = os.path.dirname(__file__)
code_path = os.path.join(code_path, os.pardir)
sys.path.append(code_path)
import MOS6502
class TestCartHeaderParsing(unittest.TestCase):
def testMagic(self):
cpu = MOS6502.CPU()
cpu.loadRom("../smb1.nes")
self.assertEqual(cpu.rom != None, True)
def testRomBanks(self):
cpu = MOS6502.CPU()
cpu.loadRom("../smb1.nes")
self.assertEqual(cpu.rom.numRomBanks, 2)
self.assertEqual(cpu.rom.numVromBanks, 1)
if __name__ == '__main__':
unittest.main()
|
Use players 0 and 1 instead of 1 and 2
Makes it easier to communicate with ANN, as 1 is truthy and 0 is falsy.
Players are also slightly more clear when Connect4 is printed.
|
class Connect4(object):
def __init__(self):
self.pieces = [[] for i in xrange(7)]
self.turn = 0
def move(self, column):
self.pieces[column % 7].append(self.turn)
self.turn = 1 - self.turn
def __str__(self):
output = ''
for i in xrange(6):
output += i and '\n ' or ' '
for piece_column in self.pieces:
try:
output += str(piece_column[5 - i]) + ' '
except IndexError:
output += ' '
return output
def start():
pass
|
class Connect4(object):
def __init__(self):
self.pieces = [[] for i in xrange(7)]
self.turn = 1
def move(self, column):
self.pieces[column % 7].append(self.turn)
self.turn = 3 - self.turn
def __str__(self):
output = ''
for i in xrange(6):
output += i and '\n ' or ' '
for piece_column in self.pieces:
try:
output += str(piece_column[5 - i]) + ' '
except IndexError:
output += ' '
return output
def start():
pass
|
Change error message per readme.
|
var Office365ConnectorHook = require("./index.js"),
winston = require('winston'),
Logger = winston.Logger,
Console = winston.transports.Console,
hookUrl = process.env.HOOK_URL;
if (!hookUrl) {
console.warn("No process.env.HOOK_URL set. Please set it to your Connector Webhook URL before running this test.");
process.exit();
}
var logger = new Logger({
transports: [
new Console({}),
new Office365ConnectorHook({
"hookUrl": hookUrl,
"colors": {
"debug": "FFFFFF"
}
})
]
});
// will be sent to both console and channel
logger.log('debug', 'Starting tests...');
logger.info('This is a test log from Winston.');
logger.info('This text appears in card body.', { title: 'My puny title' });
logger.info('# Seriously!?\n > This is cool!', { title: 'You can use Markdown in messages.' });
logger.warn('Warning! An error test coming up!');
try {
throw new Error("Everything's alright, just testing error logging.");
}
catch (err) {
logger.error(err.message, err);
}
|
var Office365ConnectorHook = require("./index.js"),
winston = require('winston'),
Logger = winston.Logger,
Console = winston.transports.Console,
hookUrl = process.env.HOOK_URL;
if (!hookUrl) {
console.warn("No process.env.HOOK_URL set. Please set it to your Connector Webhook URL before running this test.");
process.exit();
}
var logger = new Logger({
transports: [
new Console({}),
new Office365ConnectorHook({
"hookUrl": hookUrl,
"colors": {
"debug": "FFFFFF"
}
})
]
});
// will be sent to both console and channel
logger.log('debug', 'Starting tests...');
logger.info('This is a test log from Winston.');
logger.info('This text appears in card body.', { title: 'You can send card titles too!' });
logger.info('# Seriously!?\n > This is cool!', { title: 'You can use Markdown in error messages.' });
logger.warn('Warning! An error test coming up!');
try {
throw new Error("Everything's alright, just testing error logging.");
}
catch (err) {
logger.error(err.message, err);
}
|
Use subsitution for bundle names
|
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
'./app/index.js'
],
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
filename: '[name].bundle.js'
},
module: {
rules: [
{test: /\.(js|jsx)$/, exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react']
}
}
},
{test: /\.css$/, use: ['style-loader', 'css-loader']}
]
},
devServer: {
hot: true,
contentBase: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
plugins: [
new HtmlWebpackPlugin({
template: './app/index.html'
}),
new webpack.HotModuleReplacementPlugin()
]
}
|
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
'./app/index.js'
],
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
filename: 'index_bundle.js'
},
module: {
rules: [
{test: /\.(js|jsx)$/, exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react']
}
}
},
{test: /\.css$/, use: ['style-loader', 'css-loader']}
]
},
devServer: {
hot: true,
contentBase: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
plugins: [
new HtmlWebpackPlugin({
template: './app/index.html'
}),
new webpack.HotModuleReplacementPlugin()
]
}
|
Make test_run_command_on_agent connect to all agents
Increase testing of SSH connection handling by connecting to all
agents in the cluster.
|
from shakedown import *
def test_run_command():
exit_status, output = run_command(master_ip(), 'cat /etc/motd')
assert exit_status
def test_run_command_on_master():
exit_status, output = run_command_on_master('uname -a')
assert exit_status
assert output.startswith('Linux')
def test_run_command_on_leader():
exit_status, output = run_command_on_leader('uname -a')
assert exit_status
assert output.startswith('Linux')
def test_run_command_on_marathon_leader():
exit_status, output = run_command_on_marathon_leader('uname -a')
assert exit_status
assert output.startswith('Linux')
def test_run_command_on_agent():
"""Run 'ps' on all agents looking for jenkins."""
service_ips = get_private_agents() + get_public_agents()
for host in service_ips:
exit_status, output = run_command_on_agent(host, 'ps -eaf | grep -i docker | grep -i jenkins')
assert exit_status
assert output.startswith('root')
def test_run_dcos_command():
stdout, stderr, return_code = run_dcos_command('package search jenkins --json')
result_json = json.loads(stdout)
assert result_json['packages'][0]['name'] == 'jenkins'
|
from shakedown import *
def test_run_command():
exit_status, output = run_command(master_ip(), 'cat /etc/motd')
assert exit_status
def test_run_command_on_master():
exit_status, output = run_command_on_master('uname -a')
assert exit_status
assert output.startswith('Linux')
def test_run_command_on_leader():
exit_status, output = run_command_on_leader('uname -a')
assert exit_status
assert output.startswith('Linux')
def test_run_command_on_marathon_leader():
exit_status, output = run_command_on_marathon_leader('uname -a')
assert exit_status
assert output.startswith('Linux')
def test_run_command_on_agent():
# Get all IPs associated with the 'jenkins' task running in the 'marathon' service
service_ips = get_service_ips('marathon', 'jenkins')
for host in service_ips:
exit_status, output = run_command_on_agent(host, 'ps -eaf | grep -i docker | grep -i jenkins')
assert exit_status
assert output.startswith('root')
def test_run_dcos_command():
stdout, stderr, return_code = run_dcos_command('package search jenkins --json')
result_json = json.loads(stdout)
assert result_json['packages'][0]['name'] == 'jenkins'
|
Fix test for lastcmd mode.
|
package edit
import (
"testing"
"github.com/elves/elvish/edit/ui"
)
var (
theLine = "qw search 'foo bar ~y'"
theLastCmd = newLastCmd(theLine)
lastcmdFilterTests = []listingFilterTestCases{
{"", []shown{
{"M-1", ui.Unstyled(theLine)},
{"0", ui.Unstyled("qw")},
{"1", ui.Unstyled("search")},
{"2", ui.Unstyled("'foo bar ~y'")}}},
{"1", []shown{{"1", ui.Unstyled("search")}}},
{"-", []shown{
{"M-1", ui.Unstyled(theLine)},
{"-3", ui.Unstyled("qw")},
{"-2", ui.Unstyled("search")},
{"-1", ui.Unstyled("'foo bar ~y'")}}},
{"-1", []shown{{"-1", ui.Unstyled("'foo bar ~y'")}}},
}
)
func TestLastCmd(t *testing.T) {
testListingFilter(t, "theLastCmd", theLastCmd, lastcmdFilterTests)
}
|
package edit
import (
"testing"
"github.com/elves/elvish/edit/ui"
)
var (
theLine = "qw search 'foo bar ~y'"
theLastCmd = newLastCmd(theLine)
lastcmdFilterTests = []listingFilterTestCases{
{"", []shown{
{"M-,", ui.Unstyled(theLine)},
{"0", ui.Unstyled("qw")},
{"1", ui.Unstyled("search")},
{"2", ui.Unstyled("'foo bar ~y'")}}},
{"1", []shown{{"1", ui.Unstyled("search")}}},
{"-", []shown{
{"M-,", ui.Unstyled(theLine)},
{"-3", ui.Unstyled("qw")},
{"-2", ui.Unstyled("search")},
{"-1", ui.Unstyled("'foo bar ~y'")}}},
{"-1", []shown{{"-1", ui.Unstyled("'foo bar ~y'")}}},
}
)
func TestLastCmd(t *testing.T) {
testListingFilter(t, "theLastCmd", theLastCmd, lastcmdFilterTests)
}
|
Add test for inner criteria referencing another inner criteria
|
/*
* Copyright 2019 Immutables Authors and 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.immutables.criteria.nested;
import org.immutables.criteria.Criteria;
import org.immutables.value.Value;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Optional;
/**
* Criteria generation for inner classes
*/
public class Inners {
@Value.Immutable
@Criteria
@Criteria.Repository
interface Inner1 {
// reference a different inner criteria
Inner2 inner2();
@Nullable Inner2 nullableInner2();
Optional<Inner2> optionalInner2();
List<Inner2> listInner2();
}
@Value.Immutable
@Criteria
@Criteria.Repository
interface Inner2 {
String value();
}
}
|
/*
* Copyright 2019 Immutables Authors and 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.immutables.criteria.nested;
import org.immutables.criteria.Criteria;
import org.immutables.value.Value;
/**
* Criteria generation for inner classes
*/
public class Inners {
@Value.Immutable
@Criteria
@Criteria.Repository
interface Inner1 { }
@Value.Immutable
@Criteria
@Criteria.Repository
interface Inner2 {
String value();
}
}
|
Rename AsyncSignal to CoroutineSignal for clarity of purpose
|
from inspect import signature
import asyncio
class Signal(object):
def __init__(self, parameters):
self._parameters = frozenset(parameters)
self._receivers = set()
def connect(self, receiver):
# Check that the callback can be called with the given parameter names
if __debug__:
signature(receiver).bind(**{p: None for p in self._parameters})
self._receivers.add(receiver)
def disconnect(self, receiver):
self._receivers.remove(receiver)
def send(self, **kwargs):
for receiver in self._receivers:
receiver(**kwargs)
class CoroutineSignal(Signal):
def connect(self, receiver):
assert asyncio.iscoroutinefunction(receiver), receiver
super().connect(receiver)
@asyncio.coroutine
def send(self, **kwargs):
for receiver in self._receivers:
yield from receiver(**kwargs)
|
from inspect import signature
import asyncio
class Signal(object):
def __init__(self, parameters):
self._parameters = frozenset(parameters)
self._receivers = set()
def connect(self, receiver):
# Check that the callback can be called with the given parameter names
if __debug__:
signature(receiver).bind(**{p: None for p in self._parameters})
self._receivers.add(receiver)
def disconnect(self, receiver):
self._receivers.remove(receiver)
def send(self, **kwargs):
for receiver in self._receivers:
receiver(**kwargs)
class AsyncSignal(Signal):
def connect(self, receiver):
assert asyncio.iscoroutinefunction(receiver), receiver
super().connect(receiver)
@asyncio.coroutine
def send(self, **kwargs):
for receiver in self._receivers:
yield from receiver(**kwargs)
|
Change inf command to nfo and remove err messages
|
package main
import (
"log"
"net"
)
func StartServer() {
listener, err := net.Listen("tcp", Config.String("listen"))
if err != nil {
log.Fatal(err)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
log.Fatal(err)
}
go communicate(conn)
}
}
func communicate(conn net.Conn) {
log.Printf("%v connected", conn.RemoteAddr())
buf := make([]byte, TotalVoxels * 3)
for {
_, err := conn.Read(buf[:3])
if err != nil {
log.Printf("%v disconnected", conn.RemoteAddr())
break
}
switch string(buf[:3]) {
case "nfo":
conn.Write([]byte(INFO))
case "frm":
for completed := 0; completed < TotalVoxels * 3; {
read, err := conn.Read(buf[:TotalVoxels*3 - completed])
if err != nil {
log.Printf("%v disconnected", conn.RemoteAddr())
break
}
for i, b := range buf[:read] {
DisplayBackBuffer[completed+i] = float32(b) / 256
}
completed += read
}
case "swp":
SwapDisplayBuffer()
}
}
}
|
package main
import (
"log"
"net"
)
func StartServer() {
listener, err := net.Listen("tcp", Config.String("listen"))
if err != nil {
log.Fatal(err)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
log.Fatal(err)
}
go communicate(conn)
}
}
func communicate(conn net.Conn) {
log.Printf("%v connected", conn.RemoteAddr())
buf := make([]byte, TotalVoxels * 3)
for {
_, err := conn.Read(buf[:3])
if err != nil {
log.Printf("%v disconnected", conn.RemoteAddr())
break
}
switch string(buf[:3]) {
case "inf":
conn.Write([]byte(INFO))
case "frm":
for completed := 0; completed < TotalVoxels * 3; {
read, err := conn.Read(buf[:TotalVoxels*3 - completed])
if err != nil {
log.Printf("%v disconnected", conn.RemoteAddr())
break
}
for i, b := range buf[:read] {
DisplayBackBuffer[completed+i] = float32(b) / 256
}
completed += read
}
case "swp":
SwapDisplayBuffer()
default:
conn.Write([]byte("err\n"))
}
}
}
|
BAP-3040: Improve date conditions in filters
- fix error message
|
<?php
namespace Oro\Bundle\FilterBundle\Expression\Exception;
use Oro\Bundle\DataGridBundle\Exception\UserInputErrorExceptionInterface;
class ExpressionDenied extends SyntaxException implements UserInputErrorExceptionInterface
{
/** @var string */
private $template = 'Variable of type “%s” cannot be used with a constant!';
/** @var string */
private $variableLabel;
/**
* @param string $variableLabel
*/
public function __construct($variableLabel)
{
$this->variableLabel = $variableLabel;
$message = sprintf($this->template, $variableLabel);
parent::__construct($message);
}
/**
* {@inheritdoc}
*/
public function getMessageTemplate()
{
return $this->template;
}
/**
* {@inheritdoc}
*/
public function getMessageParams()
{
return ['%s' => $this->variableLabel];
}
}
|
<?php
namespace Oro\Bundle\FilterBundle\Expression\Exception;
use Oro\Bundle\DataGridBundle\Exception\UserInputErrorExceptionInterface;
class ExpressionDenied extends SyntaxException implements UserInputErrorExceptionInterface
{
/** @var string */
private $template = 'Expression with "%s" are not supported!';
/** @var string */
private $variableLabel;
/**
* @param string $variableLabel
*/
public function __construct($variableLabel)
{
$this->variableLabel = $variableLabel;
$message = sprintf($this->template, $variableLabel);
parent::__construct($message);
}
/**
* {@inheritdoc}
*/
public function getMessageTemplate()
{
return $this->template;
}
/**
* {@inheritdoc}
*/
public function getMessageParams()
{
return ['%s' => $this->variableLabel];
}
}
|
Remove unnecessary final on interface
JAVA-1215
|
/*
* Copyright (c) 2008-2014 MongoDB, Inc.
*
* 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 com.mongodb.operation;
import com.mongodb.ReadPreference;
/**
* An interface describing the execution of a read or a write operation.
*
* @since 3.0
*/
public interface OperationExecutor {
/**
* Execute the read operation with the given read preference.
*
* @param operation the read operation.
* @param readPreference the read preference.
* @param <T> the operations result type.
* @return the result of executing the operation.
*/
<T> T execute(ReadOperation<T> operation, ReadPreference readPreference);
/**
* Execute the write operation.
*
* @param operation the write operation.
* @param <T> the operations result type.
* @return the result of executing the operation.
*/
<T> T execute(WriteOperation<T> operation);
}
|
/*
* Copyright (c) 2008-2014 MongoDB, Inc.
*
* 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 com.mongodb.operation;
import com.mongodb.ReadPreference;
/**
* An interface describing the execution of a read or a write operation.
*
* @since 3.0
*/
public interface OperationExecutor {
/**
* Execute the read operation with the given read preference.
*
* @param operation the read operation.
* @param readPreference the read preference.
* @param <T> the operations result type.
* @return the result of executing the operation.
*/
<T> T execute(final ReadOperation<T> operation, final ReadPreference readPreference);
/**
* Execute the write operation.
*
* @param operation the write operation.
* @param <T> the operations result type.
* @return the result of executing the operation.
*/
<T> T execute(final WriteOperation<T> operation);
}
|
Add compile step to tests before execution
|
'use strict';
var gulp = require('gulp'),
browserify = require('browserify'),
transform = require('vinyl-transform'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
jasmine = require('gulp-jasmine');
gulp.task('default', ['javascript']);
gulp.task('javascript', function () {
var browserified = transform(function (filename) {
var b = browserify({ entries: filename, debug: true });
return b.bundle();
});
return gulp.src('./src/js/bowler.js')
.pipe(browserified)
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(uglify())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./dist/js'));
});
gulp.task('test', function () {
var browserified = transform(function (filename) {
var b = browserify({ entries: filename, debug: true });
return b.bundle();
});
return gulp.src('./spec/**/*.js')
.pipe(browserified)
.pipe(jasmine());
});
|
'use strict';
var gulp = require('gulp'),
browserify = require('browserify'),
transform = require('vinyl-transform'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
jasmine = require('gulp-jasmine');
gulp.task('default', ['javascript']);
gulp.task('javascript', function () {
var browserified = transform(function (filename) {
var b = browserify({ entries: filename, debug: true });
return b.bundle();
});
return gulp.src('./src/js/bowler.js')
.pipe(browserified)
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(uglify())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./dist/js'));
});
gulp.task('test', function () {
return gulp.src('./spec/**/*.js')
.pipe(jasmine());
});
|
Fix reload on delete post
|
function deletePost(value, post_id, user_id, csrf_token) {
$.ajax( {
type: 'post',
url: 'delete.php',
data: {
type: 2, // refer to /delete.php for information about this POST data.
value: value,
post_id: post_id,
user_id: user_id,
csrf_token: csrf_token
},
success: function(html) {
if(html == 'true') {
$("body").load(window.location.href);
} else {
alert(html);
}
}
});
}
|
function deletePost(value, post_id, user_id, csrf_token) {
$.ajax( {
type: 'post',
url: 'delete.php',
data: {
type: 2, // refer to /delete.php for information about this POST data.
value: value,
post_id: post_id,
user_id: user_id,
csrf_token: csrf_token
},
success: function(html) {
if(html == 'true') {
// Later make it remove the comment from the page WITHOUT reloading?
} else {
alert(html);
}
}
});
}
|
Use XHTML break tag in Urban_dictionary Spice.
|
// `ddg_spice_urban_dictionary` is a callback function that gets
// "urban dictionary cool" or "urban dictionary ROTFL."
// Note: This plugin can display adult content and profanity.
function ddg_spice_urban_dictionary(response) {
if (!(response || response.response.result_type === "exact"
|| response.list || response.list[0]))
return;
var word = response.list[0].word;
var definition = response.list[0].definition.replace(/(\r?\n)+/gi, '<br/>');
Spice.render({
data : { 'definition' : definition },
header1 : word + " (Urban Dictionary)",
source_url : 'http://www.urbandictionary.com/define.php?term=' + word,
source_name : 'Urban Dictionary',
template_normal : 'urban_dictionary',
force_big_header : true,
});
}
|
// `ddg_spice_urban_dictionary` is a callback function that gets
// "urban dictionary cool" or "urban dictionary ROTFL."
// Note: This plugin can display adult content and profanity.
function ddg_spice_urban_dictionary(response) {
if (!(response || response.response.result_type === "exact"
|| response.list || response.list[0]))
return;
var word = response.list[0].word;
var definition = response.list[0].definition.replace(/(\r?\n)+/gi, '<br>');
Spice.render({
data : { 'definition' : definition },
header1 : word + " (Urban Dictionary)",
source_url : 'http://www.urbandictionary.com/define.php?term=' + word,
source_name : 'Urban Dictionary',
template_normal : 'urban_dictionary',
force_big_header : true,
});
}
|
Update pi-montecarlo example to use `sum` again.
|
# encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""
Estimate pi using a Monte Carlo method with distarray.
Usage:
$ python pi_distarray.py <number of points>
"""
from __future__ import division, print_function
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
return 4 * mask.sum().toarray() / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
|
# encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""
Estimate pi using a Monte Carlo method with distarray.
Usage:
$ python pi_distarray.py <number of points>
"""
from __future__ import division
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
def local_sum(mask):
return mask.ndarray.sum()
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
lsum = context.apply(local_sum, (mask.key,))
return 4 * sum(lsum) / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
|
Change line end characters to UNIX (\r\n -> \n)
|
from django.conf import settings
from os import path, listdir
from lxml import etree
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
if not path.exists(settings.XSLT_FILES_DIR):
raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist')
for filename in listdir(settings.XSLT_FILES_DIR):
filepath = path.join(settings.XSLT_FILES_DIR, filename)
if path.isfile(filepath):
try:
xslt_etree = etree.parse(filepath)
except etree.XMLSyntaxError as er:
raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XML file: ' + str(er))
try:
transform = etree.XSLT(xslt_etree)
except etree.XSLTParseError as er:
raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XSLT file: ' + str(er))
|
from django.conf import settings
from os import path, listdir
from lxml import etree
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
if not path.exists(settings.XSLT_FILES_DIR):
raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist')
for filename in listdir(settings.XSLT_FILES_DIR):
filepath = path.join(settings.XSLT_FILES_DIR, filename)
if path.isfile(filepath):
try:
xslt_etree = etree.parse(filepath)
except etree.XMLSyntaxError as er:
raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XML file: ' + str(er))
try:
transform = etree.XSLT(xslt_etree)
except etree.XSLTParseError as er:
raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XSLT file: ' + str(er))
|
Add getValue for checkbox-form-field to return the correct value
|
Kwf.FrontendForm.Checkbox = Ext.extend(Kwf.FrontendForm.Field, {
initField: function() {
this.el.select('input').each(function(input) {
input.on('click', function() {
this.fireEvent('change', this.getValue());
}, this);
}, this);
},
clearValue: function() {
var inp = this.el.child('input');
inp.dom.checked = false;
},
setValue: function(value) {
var inp = this.el.child('input');
inp.dom.checked = !!value;
},
getValue: function(value) {
var inp = this.el.child('input');
return inp.dom.checked;
}
});
Kwf.FrontendForm.fields['kwfFormFieldCheckbox'] = Kwf.FrontendForm.Checkbox;
|
Kwf.FrontendForm.Checkbox = Ext.extend(Kwf.FrontendForm.Field, {
initField: function() {
this.el.select('input').each(function(input) {
input.on('click', function() {
this.fireEvent('change', this.getValue());
}, this);
}, this);
},
clearValue: function() {
var inp = this.el.child('input');
inp.dom.checked = false;
},
setValue: function(value) {
var inp = this.el.child('input');
inp.dom.checked = !!value;
}
});
Kwf.FrontendForm.fields['kwfFormFieldCheckbox'] = Kwf.FrontendForm.Checkbox;
|
Handle the case where JSLint complains about arguments in try/catch already being defined (we use the name 'e' consistently for catch(e) - will work to standardize on that now).
|
load("build/jslint.js");
var src = readFile("dist/jquery.js");
JSLINT(src, { evil: true, forin: true, maxerr: 100 });
// All of the following are known issues that we think are 'ok'
// (in contradiction with JSLint) more information here:
// http://docs.jquery.com/JQuery_Core_Style_Guidelines
var ok = {
"Expected an identifier and instead saw 'undefined' (a reserved word).": true,
"Use '===' to compare with 'null'.": true,
"Use '!==' to compare with 'null'.": true,
"Expected an assignment or function call and instead saw an expression.": true,
"Expected a 'break' statement before 'case'.": true,
"'e' is already defined.": true
};
var e = JSLINT.errors, found = 0, w;
for ( var i = 0; i < e.length; i++ ) {
w = e[i];
if ( !ok[ w.reason ] ) {
found++;
print( "\n" + w.evidence + "\n" );
print( " Problem at line " + w.line + " character " + w.character + ": " + w.reason );
}
}
if ( found > 0 ) {
print( "\n" + found + " Error(s) found." );
} else {
print( "JSLint check passed." );
}
|
load("build/jslint.js");
var src = readFile("dist/jquery.js");
JSLINT(src, { evil: true, forin: true, maxerr: 100 });
// All of the following are known issues that we think are 'ok'
// (in contradiction with JSLint) more information here:
// http://docs.jquery.com/JQuery_Core_Style_Guidelines
var ok = {
"Expected an identifier and instead saw 'undefined' (a reserved word).": true,
"Use '===' to compare with 'null'.": true,
"Use '!==' to compare with 'null'.": true,
"Expected an assignment or function call and instead saw an expression.": true,
"Expected a 'break' statement before 'case'.": true
};
var e = JSLINT.errors, found = 0, w;
for ( var i = 0; i < e.length; i++ ) {
w = e[i];
if ( !ok[ w.reason ] ) {
found++;
print( "\n" + w.evidence + "\n" );
print( " Problem at line " + w.line + " character " + w.character + ": " + w.reason );
}
}
if ( found > 0 ) {
print( "\n" + found + " Error(s) found." );
} else {
print( "JSLint check passed." );
}
|
HPlus: Change Makibes F68 device type
|
package nodomain.freeyourgadget.gadgetbridge.model;
/**
* For every supported device, a device type constant must exist.
*
* Note: they key of every constant is stored in the DB, so it is fixed forever,
* and may not be changed.
*/
public enum DeviceType {
UNKNOWN(-1),
PEBBLE(1),
MIBAND(10),
MIBAND2(11),
VIBRATISSIMO(20),
LIVEVIEW(30),
HPLUS(40),
MAKIBESF68(41),
TEST(1000);
private final int key;
DeviceType(int key) {
this.key = key;
}
public int getKey() {
return key;
}
public boolean isSupported() {
return this != UNKNOWN;
}
public static DeviceType fromKey(int key) {
for (DeviceType type : values()) {
if (type.key == key) {
return type;
}
}
return DeviceType.UNKNOWN;
}
}
|
package nodomain.freeyourgadget.gadgetbridge.model;
/**
* For every supported device, a device type constant must exist.
*
* Note: they key of every constant is stored in the DB, so it is fixed forever,
* and may not be changed.
*/
public enum DeviceType {
UNKNOWN(-1),
PEBBLE(1),
MIBAND(10),
MIBAND2(11),
VIBRATISSIMO(20),
LIVEVIEW(30),
HPLUS(40),
MAKIBESF68(50),
TEST(1000);
private final int key;
DeviceType(int key) {
this.key = key;
}
public int getKey() {
return key;
}
public boolean isSupported() {
return this != UNKNOWN;
}
public static DeviceType fromKey(int key) {
for (DeviceType type : values()) {
if (type.key == key) {
return type;
}
}
return DeviceType.UNKNOWN;
}
}
|
Fix typo in Adler32 name.
|
package au.com.acegi.hashbench.hashers;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.zip.Adler32;
public class AdlerHasher implements Hasher {
public static final String JRE_ADLER_32 = "adler32-jre";
public static final void register(final Map<String, Hasher> hashers) {
hashers.put(AdlerHasher.JRE_ADLER_32, new AdlerHasher());
}
private final Adler32 delegate = new Adler32();
private AdlerHasher() {}
@Override
public long hash(final byte[] in, final int off, final int len) {
this.delegate.reset();
this.delegate.update(in, off, len);
return this.delegate.getValue();
}
@Override
public long hash(final ByteBuffer bb, final int off, final int len) {
this.delegate.reset();
if (bb.hasArray()) {
this.delegate.update(bb.array(), off, len);
return this.delegate.getValue();
}
final ByteBuffer view = bb.duplicate();
view.position(off);
view.limit(off + len);
this.delegate.update(view);
return this.delegate.getValue();
}
}
|
package au.com.acegi.hashbench.hashers;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.zip.Adler32;
public class AdlerHasher implements Hasher {
public static final String JRE_ADLER_32 = "adler320-jre";
public static final void register(final Map<String, Hasher> hashers) {
hashers.put(AdlerHasher.JRE_ADLER_32, new AdlerHasher());
}
private final Adler32 delegate = new Adler32();
private AdlerHasher() {}
@Override
public long hash(final byte[] in, final int off, final int len) {
this.delegate.reset();
this.delegate.update(in, off, len);
return this.delegate.getValue();
}
@Override
public long hash(final ByteBuffer bb, final int off, final int len) {
this.delegate.reset();
if (bb.hasArray()) {
this.delegate.update(bb.array(), off, len);
return this.delegate.getValue();
}
final ByteBuffer view = bb.duplicate();
view.position(off);
view.limit(off + len);
this.delegate.update(view);
return this.delegate.getValue();
}
}
|
Add LDAP settings to default config.
|
<?php
/*
* Copyright 2016 Lukas Metzger <developer@lukas-metzger.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//Database settings
$config['db_type'] = "mysql";
$config['db_host'] = "localhost";
$config['db_user'] = "root";
$config['db_password'] = "";
$config['db_port'] = 3306;
$config['db_name'] = "pdnsmanager";
// Authentication source
$config['auth_type'] = 'db';
// LDAP settings
$config['ldap_uri'] = 'ldapi:///';
$config['ldap_bind_dn'] = '';
$config['ldap_bind_pw'] = '';
$config['ldap_base_dn'] = '';
$config['ldap_search'] = 'uid=%user%';
//Remote update
$config['nonce_lifetime'] = 15;
//Number of rows in domain overview
$config['domain_rows'] = 15;
// If config-user.php does not exist, redirect to the setup page
if(!(include 'config-user.php')) {
Header("Location: install.php");
}
|
<?php
/*
* Copyright 2016 Lukas Metzger <developer@lukas-metzger.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//Database settings
$config['db_type'] = "mysql";
$config['db_host'] = "localhost";
$config['db_user'] = "root";
$config['db_password'] = "";
$config['db_port'] = 3306;
$config['db_name'] = "pdnsmanager";
// Authentication source
$config['auth_type'] = 'db';
//Remote update
$config['nonce_lifetime'] = 15;
//Number of rows in domain overview
$config['domain_rows'] = 15;
// If config-user.php does not exist, redirect to the setup page
if(!(include 'config-user.php')) {
Header("Location: install.php");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.